text
stringlengths
54
60.6k
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "dirconfig.hpp" #include <vespa/vespalib/io/fileutil.h> #include <vespa/vespalib/util/exceptions.h> #include <fstream> #include <atomic> #include <vespa/log/log.h> LOG_SETUP(".dirconfig"); namespace vdstestlib { // When we start up first time, remove old config from the directories // we're using namespace { class Root { public: Root() : _nextDir(0) { memset(_dirname, 0, sizeof(_dirname)); sprintf(_dirname, "dirconfig.tmp.XXXXXX"); char * realName = mkdtemp(_dirname); assert(realName == _dirname); (void) realName; } ~Root() { if (system((std::string("rm -rf ") + _dirname).c_str()) != 0) { abort(); } } std::string nextDir() { char name[64]; uint32_t id = _nextDir++; sprintf(name, "%s/%u", _dirname, id); return name; } private: std::string dir() const { return _dirname; } char _dirname[64]; std::atomic<uint32_t> _nextDir; }; Root _G_root; } DirConfig::Config::Config(const ConfigName& name) : defFileName(name), config(), dirtyCache(false) { } DirConfig::Config::~Config() {} void DirConfig::Config::set(const ConfigKey& key) { set(key, ""); } void DirConfig::Config::set(const ConfigKey& key, const ConfigValue& value) { for (std::list<std::pair<ConfigKey, ConfigValue> >::iterator it = config.begin(); it != config.end(); ++it) { if (it->first == key) { if (it->second == value) return; dirtyCache = true; it->second = value; return; } } dirtyCache = true; config.push_back(std::pair<ConfigKey, ConfigValue>(key, value)); } void DirConfig::Config::remove(const ConfigKey& key) { for (std::list<std::pair<ConfigKey, ConfigValue> >::iterator it = config.begin(); it != config.end(); ++it) { if (it->first == key) { dirtyCache = true; config.erase(it); return; } } } const DirConfig::ConfigValue* DirConfig::Config::get(const ConfigKey& key) const { for (std::list<std::pair<ConfigKey, ConfigValue> >::const_iterator it = config.begin(); it != config.end(); ++it) { if (it->first == key) { return &it->second; } } return 0; } DirConfig::DirConfig() : _configs(), _dirName(_G_root.nextDir()) { vespalib::mkdir(_dirName, true); } DirConfig::~DirConfig() {} DirConfig::Config& DirConfig::addConfig(const ConfigName& name) { std::pair<std::map<ConfigName, Config>::iterator, bool> result = _configs.insert( std::map<ConfigName, Config>::value_type(name, Config(name))); if (!result.second) { throw vespalib::IllegalArgumentException( "There is already a config named " + name, VESPA_STRLOC); } return result.first->second; } DirConfig::Config& DirConfig::getConfig(const ConfigName& name, bool createIfNonExisting) { std::map<ConfigName, Config>::iterator it(_configs.find(name)); if (it == _configs.end()) { if (createIfNonExisting) { return addConfig(name); } throw vespalib::IllegalArgumentException( "No config named " + name, VESPA_STRLOC); } return it->second; } void DirConfig::removeConfig(const ConfigName& name) { _configs.erase(name); } void DirConfig::publish() const { for (std::map<ConfigName, Config>::const_iterator it = _configs.begin(); it != _configs.end(); ++it) { std::string filename = _dirName + "/" + it->first + ".cfg"; std::ofstream out(filename.c_str()); for (std::list<std::pair<ConfigKey, ConfigValue> >::const_iterator i = it->second.config.begin(); i != it->second.config.end(); ++i) { if (i->second.size() > 0) { out << i->first << " " << i->second << "\n"; } else { out << i->first << "\n"; } } out.close(); LOG(debug, "Wrote config file %s.", filename.c_str()); it->second.dirtyCache = false; } } std::string DirConfig::getConfigId() const { // Users are likely to set up config and then give config ids to users. // This is thus a good place to automatically publish changes so users // dont need to call publish manually if (isCacheDirty()) { LOG(debug, "Cache dirty in getConfigId(). Writing config files."); publish(); } return "dir:" + _dirName; } bool DirConfig::isCacheDirty() const { for (std::map<ConfigName, Config>::const_iterator it = _configs.begin(); it != _configs.end(); ++it) { if (it->second.dirtyCache) return true; } return false; } template void DirConfig::Config::setValue(const ConfigKey &, const int &); template std::string DirConfig::Config::getValue(const ConfigKey &, const std::string &) const; } // storage <commit_msg>gcc 7 needs to make sure that what you print will fit in your buffer if it can<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "dirconfig.hpp" #include <vespa/vespalib/io/fileutil.h> #include <vespa/vespalib/util/exceptions.h> #include <fstream> #include <atomic> #include <vespa/log/log.h> LOG_SETUP(".dirconfig"); namespace vdstestlib { // When we start up first time, remove old config from the directories // we're using namespace { class Root { public: Root() : _nextDir(0) { memset(_dirname, 0, sizeof(_dirname)); sprintf(_dirname, "dirconfig.tmp.XXXXXX"); char * realName = mkdtemp(_dirname); assert(realName == _dirname); assert(strlen(realName) < sizeof(_dirname)); (void) realName; } ~Root() { if (system((std::string("rm -rf ") + _dirname).c_str()) != 0) { abort(); } } std::string nextDir() { char name[64]; uint32_t id = _nextDir++; sprintf(name, "%s/%u", _dirname, id); return name; } private: std::string dir() const { return _dirname; } char _dirname[32]; std::atomic<uint32_t> _nextDir; }; Root _G_root; } DirConfig::Config::Config(const ConfigName& name) : defFileName(name), config(), dirtyCache(false) { } DirConfig::Config::~Config() {} void DirConfig::Config::set(const ConfigKey& key) { set(key, ""); } void DirConfig::Config::set(const ConfigKey& key, const ConfigValue& value) { for (std::list<std::pair<ConfigKey, ConfigValue> >::iterator it = config.begin(); it != config.end(); ++it) { if (it->first == key) { if (it->second == value) return; dirtyCache = true; it->second = value; return; } } dirtyCache = true; config.push_back(std::pair<ConfigKey, ConfigValue>(key, value)); } void DirConfig::Config::remove(const ConfigKey& key) { for (std::list<std::pair<ConfigKey, ConfigValue> >::iterator it = config.begin(); it != config.end(); ++it) { if (it->first == key) { dirtyCache = true; config.erase(it); return; } } } const DirConfig::ConfigValue* DirConfig::Config::get(const ConfigKey& key) const { for (std::list<std::pair<ConfigKey, ConfigValue> >::const_iterator it = config.begin(); it != config.end(); ++it) { if (it->first == key) { return &it->second; } } return 0; } DirConfig::DirConfig() : _configs(), _dirName(_G_root.nextDir()) { vespalib::mkdir(_dirName, true); } DirConfig::~DirConfig() {} DirConfig::Config& DirConfig::addConfig(const ConfigName& name) { std::pair<std::map<ConfigName, Config>::iterator, bool> result = _configs.insert( std::map<ConfigName, Config>::value_type(name, Config(name))); if (!result.second) { throw vespalib::IllegalArgumentException( "There is already a config named " + name, VESPA_STRLOC); } return result.first->second; } DirConfig::Config& DirConfig::getConfig(const ConfigName& name, bool createIfNonExisting) { std::map<ConfigName, Config>::iterator it(_configs.find(name)); if (it == _configs.end()) { if (createIfNonExisting) { return addConfig(name); } throw vespalib::IllegalArgumentException( "No config named " + name, VESPA_STRLOC); } return it->second; } void DirConfig::removeConfig(const ConfigName& name) { _configs.erase(name); } void DirConfig::publish() const { for (std::map<ConfigName, Config>::const_iterator it = _configs.begin(); it != _configs.end(); ++it) { std::string filename = _dirName + "/" + it->first + ".cfg"; std::ofstream out(filename.c_str()); for (std::list<std::pair<ConfigKey, ConfigValue> >::const_iterator i = it->second.config.begin(); i != it->second.config.end(); ++i) { if (i->second.size() > 0) { out << i->first << " " << i->second << "\n"; } else { out << i->first << "\n"; } } out.close(); LOG(debug, "Wrote config file %s.", filename.c_str()); it->second.dirtyCache = false; } } std::string DirConfig::getConfigId() const { // Users are likely to set up config and then give config ids to users. // This is thus a good place to automatically publish changes so users // dont need to call publish manually if (isCacheDirty()) { LOG(debug, "Cache dirty in getConfigId(). Writing config files."); publish(); } return "dir:" + _dirName; } bool DirConfig::isCacheDirty() const { for (std::map<ConfigName, Config>::const_iterator it = _configs.begin(); it != _configs.end(); ++it) { if (it->second.dirtyCache) return true; } return false; } template void DirConfig::Config::setValue(const ConfigKey &, const int &); template std::string DirConfig::Config::getValue(const ConfigKey &, const std::string &) const; } // storage <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #define STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #define DEVICE_FILTER CL_DEVICE_TYPE_ALL #ifndef OPENCL_DEVICE_ID #error OPENCL_DEVICE_ID_NOT_SET #endif #ifndef OPENCL_PLATFORM_ID #error OPENCL_PLATFORM_ID_NOT_SET #endif #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/opencl/constants.hpp> #include <stan/math/prim/scal/err/system_error.hpp> #include <CL/cl.hpp> #include <string> #include <iostream> #include <fstream> #include <map> #include <vector> #include <cmath> #include <cerrno> /** * @file stan/math/opencl/opencl_context.hpp * @brief Initialization for OpenCL: * 1. create context * 2. Find OpenCL platforms and devices available * 3. set up command queue * 4. set architecture dependent kernel parameters */ namespace stan { namespace math { /** * The <code>opencl_context_base</code> class represents an OpenCL context * in the standard Meyers singleton design pattern. * * See the OpenCL specification glossary for a list of terms: * https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf. * The context includes the set of devices available on the host, command * queues, manages kernels. * * This is designed so there's only one instance running on the host. * * Some design decisions that may need to be addressed later: * - we are assuming a single OpenCL platform. We may want to run on multiple * platforms simulatenously * - we are assuming a single OpenCL device. We may want to run on multiple * devices simulatenously */ class opencl_context_base { friend class opencl_context; private: /** * Construct the opencl_context by initializing the * OpenCL context, devices, command queues, and kernel * groups. * * This constructor does the following: * 1. Gets the available platforms and selects the platform * with id OPENCL_PLATFORM_ID. * 2. Gets the available devices and selects the device with id * OPENCL_DEVICE_ID. * 3. Creates the OpenCL context with the device. * 4. Creates the OpenCL command queue for the selected device. * 5. Sets OpenCL device dependent kernel parameters * @throw std::system_error if an OpenCL error occurs. */ opencl_context_base() { try { // platform cl::Platform::get(&platforms_); if (OPENCL_PLATFORM_ID >= platforms_.size()) { system_error("OpenCL Initialization", "[Platform]", -1, "CL_INVALID_PLATFORM"); } platform_ = platforms_[OPENCL_PLATFORM_ID]; platform_name_ = platform_.getInfo<CL_PLATFORM_NAME>(); platform_.getDevices(DEVICE_FILTER, &devices_); if (devices_.size() == 0) { system_error("OpenCL Initialization", "[Device]", -1, "CL_DEVICE_NOT_FOUND"); } if (OPENCL_DEVICE_ID >= devices_.size()) { system_error("OpenCL Initialization", "[Device]", -1, "CL_INVALID_DEVICE"); } device_ = devices_[OPENCL_DEVICE_ID]; // context and queue context_ = cl::Context(device_); // Macs do not support out of order execution mode #ifdef __APPLE__ command_queue_ = cl::CommandQueue( context_, device_, 0, nullptr); #else command_queue_ = cl::CommandQueue( context_, device_, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, nullptr); #endif device_.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_thread_block_size_); int thread_block_size_sqrt = static_cast<int>(sqrt(static_cast<double>(max_thread_block_size_))); // Does a compile time check of the maximum allowed // dimension of a square thread block size // WG size of (32,32) works on all recent GPUs but would fail on some // older integrated GPUs or CPUs if (thread_block_size_sqrt < base_opts_["THREAD_BLOCK_SIZE"]) { base_opts_["THREAD_BLOCK_SIZE"] = thread_block_size_sqrt; base_opts_["WORK_PER_THREAD"] = 1; } // Thread block size for the Cholesky // TODO(Steve): This should be tuned in a higher part of the stan language if (max_thread_block_size_ >= 256) { tuning_opts_.cholesky_min_L11_size = 256; } else { tuning_opts_.cholesky_min_L11_size = max_thread_block_size_; } } catch (const cl::Error& e) { check_opencl_error("opencl_context", e); } } protected: cl::Context context_; // Manages the the device, queue, platform, memory,etc. cl::CommandQueue command_queue_; // job queue for device, one per device std::vector<cl::Platform> platforms_; // Vector of available platforms cl::Platform platform_; // The platform for compiling kernels std::string platform_name_; // The platform such as NVIDIA OpenCL or AMD SDK std::vector<cl::Device> devices_; // All available OpenCL devices cl::Device device_; // The selected OpenCL device std::string device_name_; // The name of OpenCL device size_t max_thread_block_size_; // The maximum size of a block of workers on // the device // Holds Default parameter values for each Kernel. typedef std::map<const char*, int> map_base_opts; map_base_opts base_opts_ = {{"LOWER", static_cast<int>(TriangularViewCL::Lower)}, {"UPPER", static_cast<int>(TriangularViewCL::Upper)}, {"ENTIRE", static_cast<int>(TriangularViewCL::Entire)}, {"UPPER_TO_LOWER", static_cast<int>(TriangularMapCL::UpperToLower)}, {"LOWER_TO_UPPER", static_cast<int>(TriangularMapCL::LowerToUpper)}, {"THREAD_BLOCK_SIZE", 32}, {"WORK_PER_THREAD", 8}}; // TODO(Steve): Make these tunable during warmup struct tuning_struct { // Used in stan/math/opencl/cholesky_decompose int cholesky_min_L11_size = 256; int cholesky_partition = 4; int cholesky_size_worth_transfer = 1250; // Used in math/rev/mat/fun/cholesky_decompose int cholesky_rev_min_block_size = 512; int cholesky_rev_block_partition = 8; } tuning_opts_; static opencl_context_base& getInstance() { static opencl_context_base instance_; return instance_; } opencl_context_base(opencl_context_base const&) = delete; void operator=(opencl_context_base const&) = delete; }; /** * The API to access the methods and values in opencl_context_base */ class opencl_context { public: opencl_context() = default; /** * Returns the description of the OpenCL platform and device that is used. * Devices will be an OpenCL and Platforms are a specific OpenCL implimenation * such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string description() const { std::ostringstream msg; msg << "Platform ID: " << OPENCL_DEVICE_ID << "\n"; msg << "Platform Name: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_VENDOR>() << "\n"; msg << "\tDevice " << OPENCL_DEVICE_ID << ": " << "\n"; msg << "\t\tDevice Name: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; return msg.str(); } /** * Returns the description of the OpenCL platforms and devices that * are available. Devices will be an OpenCL and Platforms are a specific * OpenCL implimenation such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string capabilities() const { std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); std::ostringstream msg; int platform_id = 0; int device_id = 0; msg << "Number of Platforms: " << all_platforms.size() << "\n"; for (auto plat_iter : all_platforms) { cl::Platform platform(plat_iter); msg << "Platform ID: " << platform_id++ << "\n"; msg << "Platform Name: " << platform.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>() << "\n"; try { std::vector<cl::Device> all_devices; platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices); for (auto device_iter : all_devices) { cl::Device device(device_iter); msg << "\tDevice " << device_id++ << ": " << "\n"; msg << "\t\tDevice Name: " << device.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << device.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << device.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << device.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << device.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; } } catch (const cl::Error& e) { // if one of the platforms have no devices that match the device type // it will throw the error == -1 (DEVICE_NOT_FOUND) // other errors will throw a system error if (e.err() == -1) { msg << "\tno (OpenCL) devices in the platform with ID " << platform_id << "\n"; } else { check_opencl_error("capabilities", e); } } } return msg.str(); } /** * Returns the reference to the OpenCL context. The OpenCL context manages * objects such as the device, memory, command queue, program, and kernel * objects. For stan, there should only be one context, queue, device, and * program with multiple kernels. */ inline cl::Context& context() { return opencl_context_base::getInstance().context_; } /** * Returns the reference to the active OpenCL command queue for the device. * One command queue will exist per device where * kernels are placed on the command queue and by default executed in order. */ inline cl::CommandQueue& queue() { return opencl_context_base::getInstance().command_queue_; } /** * Returns a copy of the map of kernel defines */ inline opencl_context_base::map_base_opts base_opts() { return opencl_context_base::getInstance().base_opts_; } /** * Returns the maximum thread block size defined by * CL_DEVICE_MAX_WORK_GROUP_SIZE for the device in the context. This is the * maximum product of thread block dimensions for a particular device. IE a * max workgoup of 256 would allow thread blocks of sizes (16,16), (128,2), * (8, 32), etc. */ inline int max_thread_block_size() { return opencl_context_base::getInstance().max_thread_block_size_; } /** * Returns the thread block size for the Cholesky Decompositions L_11. */ inline opencl_context_base::tuning_struct& tuning_opts() { return opencl_context_base::getInstance().tuning_opts_; } /** * Returns a vector containing the OpenCL device used to create the context */ inline std::vector<cl::Device> device() { return {opencl_context_base::getInstance().device_}; } /** * Returns a vector containing the OpenCL platform used to create the context */ inline std::vector<cl::Platform> platform() { return {opencl_context_base::getInstance().platform_}; } }; static opencl_context opencl_context; } // namespace math } // namespace stan #endif #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #define STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #define DEVICE_FILTER CL_DEVICE_TYPE_ALL #ifndef OPENCL_DEVICE_ID #error OPENCL_DEVICE_ID_NOT_SET #endif #ifndef OPENCL_PLATFORM_ID #error OPENCL_PLATFORM_ID_NOT_SET #endif #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/opencl/constants.hpp> #include <stan/math/prim/scal/err/system_error.hpp> #include <CL/cl.hpp> #include <string> #include <iostream> #include <fstream> #include <map> #include <vector> #include <cmath> #include <cerrno> /** * @file stan/math/opencl/opencl_context.hpp * @brief Initialization for OpenCL: * 1. create context * 2. Find OpenCL platforms and devices available * 3. set up command queue * 4. set architecture dependent kernel parameters */ namespace stan { namespace math { /** * The <code>opencl_context_base</code> class represents an OpenCL context * in the standard Meyers singleton design pattern. * * See the OpenCL specification glossary for a list of terms: * https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf. * The context includes the set of devices available on the host, command * queues, manages kernels. * * This is designed so there's only one instance running on the host. * * Some design decisions that may need to be addressed later: * - we are assuming a single OpenCL platform. We may want to run on multiple * platforms simulatenously * - we are assuming a single OpenCL device. We may want to run on multiple * devices simulatenously */ class opencl_context_base { friend class opencl_context; private: /** * Construct the opencl_context by initializing the * OpenCL context, devices, command queues, and kernel * groups. * * This constructor does the following: * 1. Gets the available platforms and selects the platform * with id OPENCL_PLATFORM_ID. * 2. Gets the available devices and selects the device with id * OPENCL_DEVICE_ID. * 3. Creates the OpenCL context with the device. * 4. Creates the OpenCL command queue for the selected device. * 5. Sets OpenCL device dependent kernel parameters * @throw std::system_error if an OpenCL error occurs. */ opencl_context_base() { try { // platform cl::Platform::get(&platforms_); if (OPENCL_PLATFORM_ID >= platforms_.size()) { system_error("OpenCL Initialization", "[Platform]", -1, "CL_INVALID_PLATFORM"); } platform_ = platforms_[OPENCL_PLATFORM_ID]; platform_name_ = platform_.getInfo<CL_PLATFORM_NAME>(); platform_.getDevices(DEVICE_FILTER, &devices_); if (devices_.size() == 0) { system_error("OpenCL Initialization", "[Device]", -1, "CL_DEVICE_NOT_FOUND"); } if (OPENCL_DEVICE_ID >= devices_.size()) { system_error("OpenCL Initialization", "[Device]", -1, "CL_INVALID_DEVICE"); } device_ = devices_[OPENCL_DEVICE_ID]; // context and queue context_ = cl::Context(device_); // Macs do not support out of order execution mode #ifdef __APPLE__ command_queue_ = cl::CommandQueue(context_, device_, 0, nullptr); #else command_queue_ = cl::CommandQueue( context_, device_, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, nullptr); #endif device_.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_thread_block_size_); int thread_block_size_sqrt = static_cast<int>(sqrt(static_cast<double>(max_thread_block_size_))); // Does a compile time check of the maximum allowed // dimension of a square thread block size // WG size of (32,32) works on all recent GPUs but would fail on some // older integrated GPUs or CPUs if (thread_block_size_sqrt < base_opts_["THREAD_BLOCK_SIZE"]) { base_opts_["THREAD_BLOCK_SIZE"] = thread_block_size_sqrt; base_opts_["WORK_PER_THREAD"] = 1; } // Thread block size for the Cholesky // TODO(Steve): This should be tuned in a higher part of the stan language if (max_thread_block_size_ >= 256) { tuning_opts_.cholesky_min_L11_size = 256; } else { tuning_opts_.cholesky_min_L11_size = max_thread_block_size_; } } catch (const cl::Error& e) { check_opencl_error("opencl_context", e); } } protected: cl::Context context_; // Manages the the device, queue, platform, memory,etc. cl::CommandQueue command_queue_; // job queue for device, one per device std::vector<cl::Platform> platforms_; // Vector of available platforms cl::Platform platform_; // The platform for compiling kernels std::string platform_name_; // The platform such as NVIDIA OpenCL or AMD SDK std::vector<cl::Device> devices_; // All available OpenCL devices cl::Device device_; // The selected OpenCL device std::string device_name_; // The name of OpenCL device size_t max_thread_block_size_; // The maximum size of a block of workers on // the device // Holds Default parameter values for each Kernel. typedef std::map<const char*, int> map_base_opts; map_base_opts base_opts_ = {{"LOWER", static_cast<int>(TriangularViewCL::Lower)}, {"UPPER", static_cast<int>(TriangularViewCL::Upper)}, {"ENTIRE", static_cast<int>(TriangularViewCL::Entire)}, {"UPPER_TO_LOWER", static_cast<int>(TriangularMapCL::UpperToLower)}, {"LOWER_TO_UPPER", static_cast<int>(TriangularMapCL::LowerToUpper)}, {"THREAD_BLOCK_SIZE", 32}, {"WORK_PER_THREAD", 8}}; // TODO(Steve): Make these tunable during warmup struct tuning_struct { // Used in stan/math/opencl/cholesky_decompose int cholesky_min_L11_size = 256; int cholesky_partition = 4; int cholesky_size_worth_transfer = 1250; // Used in math/rev/mat/fun/cholesky_decompose int cholesky_rev_min_block_size = 512; int cholesky_rev_block_partition = 8; } tuning_opts_; static opencl_context_base& getInstance() { static opencl_context_base instance_; return instance_; } opencl_context_base(opencl_context_base const&) = delete; void operator=(opencl_context_base const&) = delete; }; /** * The API to access the methods and values in opencl_context_base */ class opencl_context { public: opencl_context() = default; /** * Returns the description of the OpenCL platform and device that is used. * Devices will be an OpenCL and Platforms are a specific OpenCL implimenation * such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string description() const { std::ostringstream msg; msg << "Platform ID: " << OPENCL_DEVICE_ID << "\n"; msg << "Platform Name: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_VENDOR>() << "\n"; msg << "\tDevice " << OPENCL_DEVICE_ID << ": " << "\n"; msg << "\t\tDevice Name: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; return msg.str(); } /** * Returns the description of the OpenCL platforms and devices that * are available. Devices will be an OpenCL and Platforms are a specific * OpenCL implimenation such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string capabilities() const { std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); std::ostringstream msg; int platform_id = 0; int device_id = 0; msg << "Number of Platforms: " << all_platforms.size() << "\n"; for (auto plat_iter : all_platforms) { cl::Platform platform(plat_iter); msg << "Platform ID: " << platform_id++ << "\n"; msg << "Platform Name: " << platform.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>() << "\n"; try { std::vector<cl::Device> all_devices; platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices); for (auto device_iter : all_devices) { cl::Device device(device_iter); msg << "\tDevice " << device_id++ << ": " << "\n"; msg << "\t\tDevice Name: " << device.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << device.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << device.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << device.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << device.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; } } catch (const cl::Error& e) { // if one of the platforms have no devices that match the device type // it will throw the error == -1 (DEVICE_NOT_FOUND) // other errors will throw a system error if (e.err() == -1) { msg << "\tno (OpenCL) devices in the platform with ID " << platform_id << "\n"; } else { check_opencl_error("capabilities", e); } } } return msg.str(); } /** * Returns the reference to the OpenCL context. The OpenCL context manages * objects such as the device, memory, command queue, program, and kernel * objects. For stan, there should only be one context, queue, device, and * program with multiple kernels. */ inline cl::Context& context() { return opencl_context_base::getInstance().context_; } /** * Returns the reference to the active OpenCL command queue for the device. * One command queue will exist per device where * kernels are placed on the command queue and by default executed in order. */ inline cl::CommandQueue& queue() { return opencl_context_base::getInstance().command_queue_; } /** * Returns a copy of the map of kernel defines */ inline opencl_context_base::map_base_opts base_opts() { return opencl_context_base::getInstance().base_opts_; } /** * Returns the maximum thread block size defined by * CL_DEVICE_MAX_WORK_GROUP_SIZE for the device in the context. This is the * maximum product of thread block dimensions for a particular device. IE a * max workgoup of 256 would allow thread blocks of sizes (16,16), (128,2), * (8, 32), etc. */ inline int max_thread_block_size() { return opencl_context_base::getInstance().max_thread_block_size_; } /** * Returns the thread block size for the Cholesky Decompositions L_11. */ inline opencl_context_base::tuning_struct& tuning_opts() { return opencl_context_base::getInstance().tuning_opts_; } /** * Returns a vector containing the OpenCL device used to create the context */ inline std::vector<cl::Device> device() { return {opencl_context_base::getInstance().device_}; } /** * Returns a vector containing the OpenCL platform used to create the context */ inline std::vector<cl::Platform> platform() { return {opencl_context_base::getInstance().platform_}; } }; static opencl_context opencl_context; } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#include <osg/GLExtensions> #include <osg/Node> #include <osg/Geometry> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/Texture2D> #include <osg/Stencil> #include <osg/ColorMask> #include <osg/Depth> #include <osg/Billboard> #include <osg/Material> #include <osg/Projection> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgUtil/TransformCallback> #include <osgUtil/RenderToTextureStage> #include <osgUtil/SmoothingVisitor> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgProducer/Viewer> using namespace osg; class DistortionNode : public osg::Group { public: DistortionNode(); DistortionNode(const DistortionNode& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): osg::Group(rhs,copyop) {} META_Node(osgDistortion, DistortionNode); virtual void traverse(osg::NodeVisitor& nv); protected: void createHUDSubgraph(); void preRender(osgUtil::CullVisitor& nv); osg::ref_ptr<osg::Node> _hudSubgraph; osg::ref_ptr<osg::Texture2D> _texture; osg::ref_ptr<osg::StateSet> _localStateSet; }; DistortionNode::DistortionNode() { createHUDSubgraph(); } void DistortionNode::createHUDSubgraph() { // create the quad to visualize. osg::Geometry* polyGeom = new osg::Geometry(); polyGeom->setSupportsDisplayList(false); osg::Vec3 origin(0.0f,0.0f,0.0f); osg::Vec3 xAxis(1.0f,0.0f,0.0f); osg::Vec3 yAxis(0.0f,1.0f,0.0f); osg::Vec3 zAxis(0.0f,0.0f,1.0f); float height = 1024.0f; float width = 1280.0f; int noSteps = 50; osg::Vec3Array* vertices = new osg::Vec3Array; osg::Vec2Array* texcoords = new osg::Vec2Array; osg::Vec4Array* colors = new osg::Vec4Array; osg::Vec3 bottom = origin; osg::Vec3 dx = xAxis*(width/((float)(noSteps-1))); osg::Vec3 dy = yAxis*(height/((float)(noSteps-1))); osg::Vec2 bottom_texcoord(0.0f,0.0f); osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f); osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1)); osg::Vec3 cursor = bottom; osg::Vec2 texcoord = bottom_texcoord; int i,j; for(i=0;i<noSteps;++i) { osg::Vec3 cursor = bottom+dy*(float)i; osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i; for(j=0;j<noSteps;++j) { vertices->push_back(cursor); texcoords->push_back(osg::Vec2((sin(texcoord.x()*osg::PI-osg::PI*0.5)+1.0f)*0.5f,(sin(texcoord.y()*osg::PI-osg::PI*0.5)+1.0f)*0.5f)); colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); cursor += dx; texcoord += dx_texcoord; } } // pass the created vertex array to the points geometry object. polyGeom->setVertexArray(vertices); polyGeom->setColorArray(colors); polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX); polyGeom->setTexCoordArray(0,texcoords); for(i=0;i<noSteps-1;++i) { osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP); for(j=0;j<noSteps;++j) { elements->push_back(j+(i+1)*noSteps); elements->push_back(j+(i)*noSteps); } polyGeom->addPrimitiveSet(elements); } // new we need to add the texture to the Drawable, we do so by creating a // StateSet to contain the Texture StateAttribute. osg::StateSet* stateset = new osg::StateSet; osg::Texture2D* texture = new osg::Texture2D; // texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST); // texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST); texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); polyGeom->setStateSet(stateset); _texture = texture; osg::Geode* geode = new osg::Geode(); geode->addDrawable(polyGeom); // create the hud. osg::MatrixTransform* modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE); modelview_abs->setMatrix(osg::Matrix::identity()); modelview_abs->addChild(geode); osg::Projection* projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs); _hudSubgraph = projection; _localStateSet = new osg::StateSet; } void DistortionNode::traverse(osg::NodeVisitor& nv) { if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR) { osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(&nv); if (cullVisitor && _texture.valid() && _hudSubgraph.valid()) { preRender(*cullVisitor); _hudSubgraph->accept(nv); return; } } Group::traverse(nv); } void DistortionNode::preRender(osgUtil::CullVisitor& cv) { // create the render to texture stage. osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage; // set up lighting. // currently ignore lights in the scene graph itself.. // will do later. osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->getStage(); // set up the background color and clear mask. rtts->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f)); rtts->setClearMask(previous_stage->getClearMask()); // set up to charge the same RenderStageLighting is the parent previous stage. rtts->setRenderStageLighting(previous_stage->getRenderStageLighting()); // record the render bin, to be restored after creation // of the render to text osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin(); // set the current renderbin to be the newly created stage. cv.setCurrentRenderBin(rtts.get()); cv.pushStateSet(_localStateSet.get()); { // traverse the subgraph Group::traverse(cv); } cv.popStateSet(); // restore the previous renderbin. cv.setCurrentRenderBin(previousRenderBin); if (rtts->getRenderGraphList().size()==0 && rtts->getRenderBinList().size()==0) { // getting to this point means that all the subgraph has been // culled by small feature culling or is beyond LOD ranges. return; } int height = 1024; int width = 1024; const osg::Viewport& viewport = *cv.getViewport(); // offset the impostor viewport from the center of the main window // viewport as often the edges of the viewport might be obscured by // other windows, which can cause image/reading writing problems. int center_x = viewport.x()+viewport.width()/2; int center_y = viewport.y()+viewport.height()/2; osg::Viewport* new_viewport = new osg::Viewport; new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height); rtts->setViewport(new_viewport); _localStateSet->setAttribute(new_viewport); // and the render to texture stage to the current stages // dependancy list. cv.getCurrentRenderBin()->getStage()->addToDependencyList(rtts.get()); // if one exist attach texture to the RenderToTextureStage. if (_texture.valid()) rtts->setTexture(_texture.get()); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // load the nodes from the commandline arguments. osg::Node* loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { // write_usage(osg::notify(osg::NOTICE),argv[0]); return 1; } // create a transform to spin the model. DistortionNode* distortionNode = new DistortionNode; distortionNode->addChild(loadedModel); // add model to the viewer. viewer.setSceneData( distortionNode ); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <commit_msg>Disabled the culling on the DistortionNode.<commit_after>#include <osg/GLExtensions> #include <osg/Node> #include <osg/Geometry> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/Texture2D> #include <osg/Stencil> #include <osg/ColorMask> #include <osg/Depth> #include <osg/Billboard> #include <osg/Material> #include <osg/Projection> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgUtil/TransformCallback> #include <osgUtil/RenderToTextureStage> #include <osgUtil/SmoothingVisitor> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgProducer/Viewer> using namespace osg; class DistortionNode : public osg::Group { public: DistortionNode(); DistortionNode(const DistortionNode& rhs,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): osg::Group(rhs,copyop) {} META_Node(osgDistortion, DistortionNode); virtual void traverse(osg::NodeVisitor& nv); protected: void createHUDSubgraph(); void preRender(osgUtil::CullVisitor& nv); osg::ref_ptr<osg::Node> _hudSubgraph; osg::ref_ptr<osg::Texture2D> _texture; osg::ref_ptr<osg::StateSet> _localStateSet; }; DistortionNode::DistortionNode() { setCullingActive(false); createHUDSubgraph(); } void DistortionNode::createHUDSubgraph() { // create the quad to visualize. osg::Geometry* polyGeom = new osg::Geometry(); polyGeom->setSupportsDisplayList(false); osg::Vec3 origin(0.0f,0.0f,0.0f); osg::Vec3 xAxis(1.0f,0.0f,0.0f); osg::Vec3 yAxis(0.0f,1.0f,0.0f); osg::Vec3 zAxis(0.0f,0.0f,1.0f); float height = 1024.0f; float width = 1280.0f; int noSteps = 50; osg::Vec3Array* vertices = new osg::Vec3Array; osg::Vec2Array* texcoords = new osg::Vec2Array; osg::Vec4Array* colors = new osg::Vec4Array; osg::Vec3 bottom = origin; osg::Vec3 dx = xAxis*(width/((float)(noSteps-1))); osg::Vec3 dy = yAxis*(height/((float)(noSteps-1))); osg::Vec2 bottom_texcoord(0.0f,0.0f); osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f); osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1)); osg::Vec3 cursor = bottom; osg::Vec2 texcoord = bottom_texcoord; int i,j; for(i=0;i<noSteps;++i) { osg::Vec3 cursor = bottom+dy*(float)i; osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i; for(j=0;j<noSteps;++j) { vertices->push_back(cursor); texcoords->push_back(osg::Vec2((sin(texcoord.x()*osg::PI-osg::PI*0.5)+1.0f)*0.5f,(sin(texcoord.y()*osg::PI-osg::PI*0.5)+1.0f)*0.5f)); colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); cursor += dx; texcoord += dx_texcoord; } } // pass the created vertex array to the points geometry object. polyGeom->setVertexArray(vertices); polyGeom->setColorArray(colors); polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX); polyGeom->setTexCoordArray(0,texcoords); for(i=0;i<noSteps-1;++i) { osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP); for(j=0;j<noSteps;++j) { elements->push_back(j+(i+1)*noSteps); elements->push_back(j+(i)*noSteps); } polyGeom->addPrimitiveSet(elements); } // new we need to add the texture to the Drawable, we do so by creating a // StateSet to contain the Texture StateAttribute. osg::StateSet* stateset = new osg::StateSet; osg::Texture2D* texture = new osg::Texture2D; // texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::NEAREST); // texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::NEAREST); texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); polyGeom->setStateSet(stateset); _texture = texture; osg::Geode* geode = new osg::Geode(); geode->addDrawable(polyGeom); // create the hud. osg::MatrixTransform* modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE); modelview_abs->setMatrix(osg::Matrix::identity()); modelview_abs->addChild(geode); osg::Projection* projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs); _hudSubgraph = projection; _localStateSet = new osg::StateSet; } void DistortionNode::traverse(osg::NodeVisitor& nv) { if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR) { osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(&nv); if (cullVisitor && _texture.valid() && _hudSubgraph.valid()) { preRender(*cullVisitor); _hudSubgraph->accept(nv); return; } } Group::traverse(nv); } void DistortionNode::preRender(osgUtil::CullVisitor& cv) { // create the render to texture stage. osg::ref_ptr<osgUtil::RenderToTextureStage> rtts = new osgUtil::RenderToTextureStage; // set up lighting. // currently ignore lights in the scene graph itself.. // will do later. osgUtil::RenderStage* previous_stage = cv.getCurrentRenderBin()->getStage(); // set up the background color and clear mask. rtts->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f)); rtts->setClearMask(previous_stage->getClearMask()); // set up to charge the same RenderStageLighting is the parent previous stage. rtts->setRenderStageLighting(previous_stage->getRenderStageLighting()); // record the render bin, to be restored after creation // of the render to text osgUtil::RenderBin* previousRenderBin = cv.getCurrentRenderBin(); // set the current renderbin to be the newly created stage. cv.setCurrentRenderBin(rtts.get()); cv.pushStateSet(_localStateSet.get()); { // traverse the subgraph Group::traverse(cv); } cv.popStateSet(); // restore the previous renderbin. cv.setCurrentRenderBin(previousRenderBin); if (rtts->getRenderGraphList().size()==0 && rtts->getRenderBinList().size()==0) { // getting to this point means that all the subgraph has been // culled by small feature culling or is beyond LOD ranges. return; } int height = 1024; int width = 1024; const osg::Viewport& viewport = *cv.getViewport(); // offset the impostor viewport from the center of the main window // viewport as often the edges of the viewport might be obscured by // other windows, which can cause image/reading writing problems. int center_x = viewport.x()+viewport.width()/2; int center_y = viewport.y()+viewport.height()/2; osg::Viewport* new_viewport = new osg::Viewport; new_viewport->setViewport(center_x-width/2,center_y-height/2,width,height); rtts->setViewport(new_viewport); _localStateSet->setAttribute(new_viewport); // and the render to texture stage to the current stages // dependancy list. cv.getCurrentRenderBin()->getStage()->addToDependencyList(rtts.get()); // if one exist attach texture to the RenderToTextureStage. if (_texture.valid()) rtts->setTexture(_texture.get()); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // load the nodes from the commandline arguments. osg::Node* loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { // write_usage(osg::notify(osg::NOTICE),argv[0]); return 1; } // create a transform to spin the model. DistortionNode* distortionNode = new DistortionNode; distortionNode->addChild(loadedModel); // add model to the viewer. viewer.setSceneData( distortionNode ); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <|endoftext|>
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL. // Simple example using GLUT to create an OpenGL window and OSG for rendering. // Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp #include <iostream> #ifdef WIN32 #include <windows.h> #endif #ifdef __APPLE__ # include <GLUT/glut.h> #else # include <GL/glut.h> #endif #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> osg::ref_ptr<osgViewer::Viewer> viewer; osg::ref_ptr<osgViewer::GraphicsWindow> window; void display(void) { // update and render the scene graph viewer->frame(); // Swap Buffers glutSwapBuffers(); glutPostRedisplay(); } void reshape( int w, int h ) { // update the window dimensions, in case the window has been resized. window->resized(window->getTraits()->x, window->getTraits()->y, w, h); window->getEventQueue()->windowResize(window->getTraits()->x, window->getTraits()->y, w, h ); } void mousebutton( int button, int state, int x, int y ) { if (state==0) window->getEventQueue()->mouseButtonPress( x, y, button+1 ); else window->getEventQueue()->mouseButtonRelease( x, y, button+1 ); } void mousemove( int x, int y ) { window->getEventQueue()->mouseMotion( x, y ); } void keyboard( unsigned char key, int /*x*/, int /*y*/ ) { switch( key ) { case 27: glutDestroyWindow(glutGetWindow()); break; default: window->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) key ); window->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) key ); break; } } int main( int argc, char **argv ) { glutInit(&argc, argv); if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_ALPHA ); glutInitWindowPosition( 100, 100 ); glutInitWindowSize( 800, 600 ); glutCreateWindow( argv[0] ); glutDisplayFunc( display ); glutReshapeFunc( reshape ); glutMouseFunc( mousebutton ); glutMotionFunc( mousemove ); glutKeyboardFunc( keyboard ); // create the view of the scene. viewer = new osgViewer::Viewer; window = viewer->setUpViewerAsEmbeddedInWindow(100,100,800,600); viewer->setSceneData(loadedModel.get()); viewer->setCameraManipulator(new osgGA::TrackballManipulator); viewer->addEventHandler(new osgViewer::StatsHandler); viewer->realize(); glutMainLoop(); return 0; } /*EOF*/ <commit_msg>Added clean up of the view before destruction of the window<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL. // Simple example using GLUT to create an OpenGL window and OSG for rendering. // Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp #include <iostream> #ifdef WIN32 #include <windows.h> #endif #ifdef __APPLE__ # include <GLUT/glut.h> #else # include <GL/glut.h> #endif #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> osg::ref_ptr<osgViewer::Viewer> viewer; osg::observer_ptr<osgViewer::GraphicsWindow> window; void display(void) { // update and render the scene graph if (viewer.valid()) viewer->frame(); // Swap Buffers glutSwapBuffers(); glutPostRedisplay(); } void reshape( int w, int h ) { // update the window dimensions, in case the window has been resized. if (window.valid()) { window->resized(window->getTraits()->x, window->getTraits()->y, w, h); window->getEventQueue()->windowResize(window->getTraits()->x, window->getTraits()->y, w, h ); } } void mousebutton( int button, int state, int x, int y ) { if (window.valid()) { if (state==0) window->getEventQueue()->mouseButtonPress( x, y, button+1 ); else window->getEventQueue()->mouseButtonRelease( x, y, button+1 ); } } void mousemove( int x, int y ) { if (window.valid()) { window->getEventQueue()->mouseMotion( x, y ); } } void keyboard( unsigned char key, int /*x*/, int /*y*/ ) { switch( key ) { case 27: // clean up the viewer if (viewer.valid()) viewer = 0; glutDestroyWindow(glutGetWindow()); break; default: if (window.valid()) { window->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) key ); window->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) key ); } break; } } int main( int argc, char **argv ) { glutInit(&argc, argv); if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_ALPHA ); glutInitWindowPosition( 100, 100 ); glutInitWindowSize( 800, 600 ); glutCreateWindow( argv[0] ); glutDisplayFunc( display ); glutReshapeFunc( reshape ); glutMouseFunc( mousebutton ); glutMotionFunc( mousemove ); glutKeyboardFunc( keyboard ); // create the view of the scene. viewer = new osgViewer::Viewer; window = viewer->setUpViewerAsEmbeddedInWindow(100,100,800,600); viewer->setSceneData(loadedModel.get()); viewer->setCameraManipulator(new osgGA::TrackballManipulator); viewer->addEventHandler(new osgViewer::StatsHandler); viewer->realize(); glutMainLoop(); return 0; } /*EOF*/ <|endoftext|>
<commit_before>// #include <compare> // #include <concepts> #include "acmacs-base/argv.hh" #include "acmacs-base/range-v3.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-base/quicklook.hh" #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/stress.hh" #include "acmacs-chart-2/randomizer.hh" #include "acmacs-chart-2/bounding-ball.hh" #include "acmacs-draw/surface-cairo.hh" #include "acmacs-draw/drawi-generator.hh" // ---------------------------------------------------------------------- // template <typename T> requires requires (const T& a, const T& b) // { // a.compare(b); // // { // // a.compare(b) // // } -> concepts::convertible_to<int>; // } // inline std::strong_ordering operator<=>(const T& lhs, const T& rhs) // { // if (const auto res = lhs.compare(rhs); res == 0) // return std::strong_ordering::equal; // else if (res < 0) // return std::strong_ordering::less; // else // return std::strong_ordering::greater; // } struct TiterRef { std::string serum; std::string antigen; size_t table_no; acmacs::chart::Titer titer; bool operator<(const TiterRef& rhs) const { if (const auto r1 = serum.compare(rhs.serum); r1 != 0) return r1 < 0; if (const auto r1 = antigen.compare(rhs.antigen); r1 != 0) return r1 < 0; return table_no < rhs.table_no; } // std::strong_ordering operator<=>(const TiterRef&) const = default; }; struct TiterRefCollapsed { std::string serum; std::string antigen; std::vector<acmacs::chart::Titer> titers; TiterRefCollapsed(const std::string& a_serum, const std::string& a_antigen, size_t num_tables) : serum{a_serum}, antigen{a_antigen}, titers(num_tables) {} static inline bool valid(const acmacs::chart::Titer& titer) { return !titer.is_dont_care(); } auto num_tables() const { return ranges::count_if(titers, valid); } auto mean_logged_titer() const { return ranges::accumulate(titers | ranges::views::filter(valid), 0.0, [](double sum, const auto& titer) { return sum + titer.logged_with_thresholded(); }) / static_cast<double>(num_tables()); } bool eq(const TiterRef& raw) const { return serum == raw.serum && antigen == raw.antigen; } }; class ChartData { public: void scan(const acmacs::chart::Chart& chart) { const auto table_no = tables_.size(); tables_.push_back(chart.info()->date()); auto chart_antigens = chart.antigens(); auto chart_sera = chart.sera(); auto chart_titers = chart.titers(); for (auto [ag_no, ag] : acmacs::enumerate(*chart_antigens)) { for (auto [sr_no, sr] : acmacs::enumerate(*chart_sera)) { if (const auto& titer = chart_titers->titer(ag_no, sr_no); !titer.is_dont_care()) raw_.push_back(TiterRef{.serum = sr->full_name(), .antigen = ag->full_name(), .table_no = table_no, .titer = titer}); } } } void collapse() { ranges::sort(raw_, &TiterRef::operator<); for (const auto& raw : raw_) { if (collapsed_.empty()) collapsed_.emplace_back(raw.serum, raw.antigen, tables_.size()); else if (!collapsed_.back().eq(raw)) { if (collapsed_.back().num_tables() < 2) collapsed_.pop_back(); collapsed_.emplace_back(raw.serum, raw.antigen, tables_.size()); } collapsed_.back().titers[raw.table_no] = raw.titer; } } void report_deviation_from_mean() const { for (const auto& en : collapsed_) { fmt::print("{}\n{}\n", en.serum, en.antigen); const auto mean = en.mean_logged_titer(); for (size_t t_no = 0; t_no < tables_.size(); ++t_no) { if (!en.titers[t_no].is_dont_care()) fmt::print(" {} {:>7s} {:.2f}\n", tables_[t_no], en.titers[t_no], std::abs(en.titers[t_no].logged_with_thresholded() - mean)); else fmt::print(" {}\n", tables_[t_no]); } fmt::print(" {:.2f}\n\n", mean); } } void report_average_deviation_from_mean_per_table() const { std::vector<std::pair<double, size_t>> deviations(tables_.size(), {0.0, 0}); for (const auto& en : collapsed_) { const auto mean = en.mean_logged_titer(); ranges::for_each(ranges::views::iota(0ul, deviations.size()) // | ranges::views::filter([&en](size_t t_no) { return !en.titers[t_no].is_dont_care(); }), [&en, &deviations, mean](size_t t_no) { deviations[t_no].first += std::abs(en.titers[t_no].logged_with_thresholded() - mean); ++deviations[t_no].second; }); } for (size_t t_no = 0; t_no < tables_.size(); ++t_no) fmt::print("{:2d} {} {:.2f} {:4d}\n", t_no, tables_[t_no], deviations[t_no].first / static_cast<double>(deviations[t_no].second), deviations[t_no].second); } auto make_distance_matrix(bool report = false) const { std::vector<std::vector<double>> matrix(tables_.size() * tables_.size()); for (const auto& en : collapsed_) { for (size_t t1 = 0; t1 < (tables_.size() - 1); ++t1) { for (size_t t2 = t1 + 1; t2 < tables_.size(); ++t2) { if (!en.titers[t1].is_dont_care() && !en.titers[t2].is_dont_care()) matrix[t1 * tables_.size() + t2].push_back(std::abs(en.titers[t1].logged_with_thresholded() - en.titers[t2].logged_with_thresholded())); } } } if (report) { for (size_t t1 = 0; t1 < (tables_.size() - 1); ++t1) { for (size_t t2 = t1 + 1; t2 < tables_.size(); ++t2) { if (auto& distances = matrix[t1 * tables_.size() + t2]; !distances.empty()) { ranges::sort(distances); fmt::print("{} {} mean:{} median:{} max:{} {}\n", tables_[t1], tables_[t2], ranges::accumulate(distances, 0.0) / static_cast<double>(distances.size()), distances[distances.size() / 2], distances.back(), distances); } else fmt::print("{} {}: *no distances*\n", tables_[t1], tables_[t2]); } } } acmacs::chart::TableDistances table_distances; for (size_t t1 = 0; t1 < (tables_.size() - 1); ++t1) { for (size_t t2 = t1 + 1; t2 < tables_.size(); ++t2) { if (auto& distances = matrix[t1 * tables_.size() + t2]; !distances.empty()) { const auto mean = ranges::accumulate(distances, 0.0) / static_cast<double>(distances.size()); table_distances.add_value(acmacs::chart::Titer::Regular, t1, t2, mean); } } } return table_distances; } size_t num_tables() const { return tables_.size(); } constexpr const auto& tables() const { return tables_; } private: std::vector<acmacs::chart::TableDate> tables_; std::vector<TiterRef> raw_; std::vector<TiterRefCollapsed> collapsed_; }; // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } std::string_view help_pre() const override { return "compare titers of mutiple tables"; } argument<str_array> charts{*this, arg_name{"chart"}, mandatory}; option<str> output{*this, 'o', desc{"output .drawi file"}}; option<size_t> number_of_optimizations{*this, 'n', dflt{100ul}}; }; int main(int argc, char* const argv[]) { int exit_code = 0; try { Options opt(argc, argv); ChartData data; for (const auto& fn : opt.charts) data.scan(*acmacs::chart::import_from_file(fn)); data.collapse(); // data.report_deviation_from_mean(); data.report_average_deviation_from_mean_per_table(); acmacs::chart::Stress stress(acmacs::number_of_dimensions_t{2}, data.num_tables()); stress.table_distances() = data.make_distance_matrix(); double best_stress{9e99}; acmacs::Layout best_layout(data.num_tables(), stress.number_of_dimensions()); for ([[maybe_unused]] auto attempt : acmacs::range(*opt.number_of_optimizations)) { acmacs::Layout layout(data.num_tables(), stress.number_of_dimensions()); acmacs::chart::LayoutRandomizerPlain rnd(10.0, std::nullopt); for (auto point_no : acmacs::range(layout.number_of_points())) layout.update(point_no, rnd.get(stress.number_of_dimensions())); const auto status1 = acmacs::chart::optimize(acmacs::chart::optimization_method::alglib_cg_pca, stress, layout.data(), layout.data() + layout.size(), acmacs::chart::optimization_precision::rough); // fmt::print("{:3d} stress: {} <- {} iterations: {}\n", attempt, status1.final_stress, status1.initial_stress, status1.number_of_iterations); if (status1.final_stress < best_stress) { best_stress = status1.final_stress; best_layout = layout; } } fmt::print("best_stress: {}\n", best_stress); if (opt.output) { acmacs::drawi::Generator gen; const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)}; gen.viewport().set_from_center_size(bb.center(), bb.diameter()); for (size_t t1 = 0; t1 < data.num_tables(); ++t1) { gen.add_point().coord(best_layout[t1]).fill(GREEN).outline(BLACK).outline_width(Pixels{1}).size(Pixels{10}).shape(acmacs::drawi::Generator::Point::Triangle).label(data.tables()[t1]); // rescaled_surface.text(best_layout[t1] + acmacs::PointCoordinates{-0.05, 0.05}, data.tables()[t1], BLACK, Pixels{10}); } gen.generate(opt.output); } // if (opt.output) { // const std::array colors_of_tables{ // GREEN, // 20180206 Leah G/Heidi // RED, // 20180227 Tasuola // BLUE, // 20180528 Rob // RED, // 20180605 Tasuola // BLUE, // 20180626 Rob // GREEN, // 20180821 Heidi/Malet // GREEN, // 20180918 Heidi/Tas // GREEN, // 20181127 Heidi // RED, // 20181213 Tasuola // RED, // 20190211 Tasuola/Rob // RED, // 20190409 Tasuola // GREEN, // 20190514 Leah // GREEN, // 20190521 Leah // GREEN, // 20190716 Leah/Heidi // GREEN, // 20190820 Leah // GREEN, // 20190903 Leah // GREEN, // 20190918 Leah // }; // const double size = 800.0; // acmacs::surface::PdfCairo surface(opt.output, size, size, size); // const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)}; // acmacs::Viewport viewport; // viewport.set_from_center_size(bb.center(), bb.diameter()); // viewport.whole_width(); // fmt::print("{}\n", viewport); // acmacs::surface::Surface& rescaled_surface = surface.subsurface(acmacs::PointCoordinates::zero2D, Scaled{surface.viewport().size.width}, viewport, true); // rescaled_surface.grid(Scaled{1.0}, GREY, Pixels{1}); // for (size_t t1 = 0; t1 < data.num_tables(); ++t1) { // const auto fill = t1 < colors_of_tables.size() ? colors_of_tables[t1] : GREEN; // rescaled_surface.circle_filled(best_layout[t1], Pixels{10}, AspectNormal, NoRotation, BLACK, Pixels{1}, acmacs::surface::Dash::NoDash, fill); // rescaled_surface.text(best_layout[t1] + acmacs::PointCoordinates{-0.05, 0.05}, data.tables()[t1], BLACK, Pixels{10}); // } // acmacs::open(opt.output, 1, 1); // } } catch (std::exception& err) { AD_ERROR("{}", err); exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>chart-table-compare<commit_after>// #include <compare> // #include <concepts> #include "acmacs-base/argv.hh" #include "acmacs-base/range-v3.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-base/quicklook.hh" #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/stress.hh" #include "acmacs-chart-2/randomizer.hh" #include "acmacs-chart-2/bounding-ball.hh" #include "acmacs-draw/surface-cairo.hh" #include "acmacs-draw/drawi-generator.hh" // ---------------------------------------------------------------------- // template <typename T> requires requires (const T& a, const T& b) // { // a.compare(b); // // { // // a.compare(b) // // } -> concepts::convertible_to<int>; // } // inline std::strong_ordering operator<=>(const T& lhs, const T& rhs) // { // if (const auto res = lhs.compare(rhs); res == 0) // return std::strong_ordering::equal; // else if (res < 0) // return std::strong_ordering::less; // else // return std::strong_ordering::greater; // } struct TiterRef { std::string serum; std::string antigen; size_t table_no; acmacs::chart::Titer titer; bool operator<(const TiterRef& rhs) const { if (const auto r1 = serum.compare(rhs.serum); r1 != 0) return r1 < 0; if (const auto r1 = antigen.compare(rhs.antigen); r1 != 0) return r1 < 0; return table_no < rhs.table_no; } // std::strong_ordering operator<=>(const TiterRef&) const = default; }; struct TiterRefCollapsed { std::string serum; std::string antigen; std::vector<acmacs::chart::Titer> titers; TiterRefCollapsed(const std::string& a_serum, const std::string& a_antigen, size_t num_tables) : serum{a_serum}, antigen{a_antigen}, titers(num_tables) {} static inline bool valid(const acmacs::chart::Titer& titer) { return !titer.is_dont_care(); } auto num_tables() const { return ranges::count_if(titers, valid); } auto mean_logged_titer() const { return ranges::accumulate(titers | ranges::views::filter(valid), 0.0, [](double sum, const auto& titer) { return sum + titer.logged_with_thresholded(); }) / static_cast<double>(num_tables()); } bool eq(const TiterRef& raw) const { return serum == raw.serum && antigen == raw.antigen; } }; class ChartData { public: void scan(const acmacs::chart::Chart& chart) { const auto table_no = tables_.size(); tables_.push_back(chart.info()->date()); auto chart_antigens = chart.antigens(); auto chart_sera = chart.sera(); auto chart_titers = chart.titers(); for (auto [ag_no, ag] : acmacs::enumerate(*chart_antigens)) { for (auto [sr_no, sr] : acmacs::enumerate(*chart_sera)) { if (const auto& titer = chart_titers->titer(ag_no, sr_no); !titer.is_dont_care()) raw_.push_back(TiterRef{.serum = sr->full_name(), .antigen = ag->full_name(), .table_no = table_no, .titer = titer}); } } } void collapse() { ranges::sort(raw_, &TiterRef::operator<); for (const auto& raw : raw_) { if (collapsed_.empty()) collapsed_.emplace_back(raw.serum, raw.antigen, tables_.size()); else if (!collapsed_.back().eq(raw)) { if (collapsed_.back().num_tables() < 2) collapsed_.pop_back(); collapsed_.emplace_back(raw.serum, raw.antigen, tables_.size()); } collapsed_.back().titers[raw.table_no] = raw.titer; } } void report_deviation_from_mean() const { for (const auto& en : collapsed_) { fmt::print("{}\n{}\n", en.serum, en.antigen); const auto mean = en.mean_logged_titer(); for (size_t t_no = 0; t_no < tables_.size(); ++t_no) { if (!en.titers[t_no].is_dont_care()) fmt::print(" {} {:>7s} {:.2f}\n", tables_[t_no], en.titers[t_no], std::abs(en.titers[t_no].logged_with_thresholded() - mean)); else fmt::print(" {}\n", tables_[t_no]); } fmt::print(" {:.2f}\n\n", mean); } } void report_average_deviation_from_mean_per_table() const { std::vector<std::pair<double, size_t>> deviations(tables_.size(), {0.0, 0}); for (const auto& en : collapsed_) { const auto mean = en.mean_logged_titer(); ranges::for_each(ranges::views::iota(0ul, deviations.size()) // | ranges::views::filter([&en](size_t t_no) { return !en.titers[t_no].is_dont_care(); }), [&en, &deviations, mean](size_t t_no) { deviations[t_no].first += std::abs(en.titers[t_no].logged_with_thresholded() - mean); ++deviations[t_no].second; }); } for (size_t t_no = 0; t_no < tables_.size(); ++t_no) fmt::print("{:2d} {} {:.2f} {:4d}\n", t_no, tables_[t_no], deviations[t_no].first / static_cast<double>(deviations[t_no].second), deviations[t_no].second); } auto make_distance_matrix(bool report = false) const { std::vector<std::vector<double>> matrix(tables_.size() * tables_.size()); for (const auto& en : collapsed_) { for (size_t t1 = 0; t1 < (tables_.size() - 1); ++t1) { for (size_t t2 = t1 + 1; t2 < tables_.size(); ++t2) { if (!en.titers[t1].is_dont_care() && !en.titers[t2].is_dont_care()) matrix[t1 * tables_.size() + t2].push_back(std::abs(en.titers[t1].logged_with_thresholded() - en.titers[t2].logged_with_thresholded())); } } } if (report) { for (size_t t1 = 0; t1 < (tables_.size() - 1); ++t1) { for (size_t t2 = t1 + 1; t2 < tables_.size(); ++t2) { if (auto& distances = matrix[t1 * tables_.size() + t2]; !distances.empty()) { ranges::sort(distances); fmt::print("{} {} mean:{} median:{} max:{} {}\n", tables_[t1], tables_[t2], ranges::accumulate(distances, 0.0) / static_cast<double>(distances.size()), distances[distances.size() / 2], distances.back(), distances); } else fmt::print("{} {}: *no distances*\n", tables_[t1], tables_[t2]); } } } acmacs::chart::TableDistances table_distances; for (size_t t1 = 0; t1 < (tables_.size() - 1); ++t1) { for (size_t t2 = t1 + 1; t2 < tables_.size(); ++t2) { if (auto& distances = matrix[t1 * tables_.size() + t2]; !distances.empty()) { const auto mean = ranges::accumulate(distances, 0.0) / static_cast<double>(distances.size()); table_distances.add_value(acmacs::chart::Titer::Regular, t1, t2, mean); } } } return table_distances; } size_t num_tables() const { return tables_.size(); } constexpr const auto& tables() const { return tables_; } private: std::vector<acmacs::chart::TableDate> tables_; std::vector<TiterRef> raw_; std::vector<TiterRefCollapsed> collapsed_; }; // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } std::string_view help_pre() const override { return "compare titers of mutiple tables"; } argument<str_array> charts{*this, arg_name{"chart"}, mandatory}; option<str> output{*this, 'o', desc{"output .drawi file"}}; option<size_t> number_of_optimizations{*this, 'n', dflt{100ul}}; }; int main(int argc, char* const argv[]) { int exit_code = 0; try { Options opt(argc, argv); ChartData data; for (const auto& fn : opt.charts) data.scan(*acmacs::chart::import_from_file(fn)); data.collapse(); // data.report_deviation_from_mean(); data.report_average_deviation_from_mean_per_table(); acmacs::chart::Stress stress(acmacs::number_of_dimensions_t{2}, data.num_tables()); stress.table_distances() = data.make_distance_matrix(); double best_stress{9e99}; acmacs::Layout best_layout(data.num_tables(), stress.number_of_dimensions()); for ([[maybe_unused]] auto attempt : acmacs::range(*opt.number_of_optimizations)) { acmacs::Layout layout(data.num_tables(), stress.number_of_dimensions()); acmacs::chart::LayoutRandomizerPlain rnd(10.0, std::nullopt); for (auto point_no : acmacs::range(layout.number_of_points())) layout.update(point_no, rnd.get(stress.number_of_dimensions())); const auto status1 = acmacs::chart::optimize(acmacs::chart::optimization_method::alglib_cg_pca, stress, layout.data(), layout.data() + layout.size(), acmacs::chart::optimization_precision::rough); // fmt::print("{:3d} stress: {} <- {} iterations: {}\n", attempt, status1.final_stress, status1.initial_stress, status1.number_of_iterations); if (status1.final_stress < best_stress) { best_stress = status1.final_stress; best_layout = layout; } } fmt::print("best_stress: {}\n", best_stress); if (opt.output) { acmacs::drawi::Generator gen; const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)}; gen.viewport().set_from_center_size(bb.center(), bb.diameter()); for (size_t t1 = 0; t1 < data.num_tables(); ++t1) { gen.add_point().coord(best_layout[t1]).fill(GREEN).outline(BLACK).outline_width(Pixels{1}).size(Pixels{10}).shape(acmacs::drawi::Generator::Point::Triangle).label(data.tables()[t1]); } gen.generate(opt.output); } // if (opt.output) { // const std::array colors_of_tables{ // GREEN, // 20180206 Leah G/Heidi // RED, // 20180227 Tasuola // BLUE, // 20180528 Rob // RED, // 20180605 Tasuola // BLUE, // 20180626 Rob // GREEN, // 20180821 Heidi/Malet // GREEN, // 20180918 Heidi/Tas // GREEN, // 20181127 Heidi // RED, // 20181213 Tasuola // RED, // 20190211 Tasuola/Rob // RED, // 20190409 Tasuola // GREEN, // 20190514 Leah // GREEN, // 20190521 Leah // GREEN, // 20190716 Leah/Heidi // GREEN, // 20190820 Leah // GREEN, // 20190903 Leah // GREEN, // 20190918 Leah // }; // } } catch (std::exception& err) { AD_ERROR("{}", err); exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/ #include <ctf.hpp> #include <assert.h> #include <stdlib.h> /** * \brief Forms N-by-N DFT matrix A and inverse-dft iA and checks A*iA=I */ int main(int argc, char ** argv){ int myRank, numPes, logn, i, j; int64_t n, np; int64_t * idx; std::complex<double> * data; std::complex<double> imag(0,1); MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numPes); MPI_Comm_rank(MPI_COMM_WORLD, &myRank); if (argc > 1){ logn = atoi(argv[1]); if (logn<0) logn = 5; } else { logn = 5; } n = 1<<logn; int len[] = {n,n,n}; int sym[] = {NS,NS,NS}; cCTF_World wrld; cCTF_Matrix DFT(n, n, SY, wrld); cCTF_Matrix IDFT(n, n, SY, wrld); cCTF_Tensor MESH(3, len, sym, wrld); DFT.get_local_data(&np, &idx, &data); for (i=0; i<np; i++){ data[i] = (1./n)*exp(-2.*(idx[i]/n)*(idx[i]%n)*(M_PI/n)*imag); } DFT.write_remote_data(np, idx, data); //DFT.print(stdout); free(idx); free(data); IDFT.get_local_data(&np, &idx, &data); for (i=0; i<np; i++){ data[i] = (1./n)*exp(2.*(idx[i]/n)*(idx[i]%n)*(M_PI/n)*imag); } IDFT.write_remote_data(np, idx, data); //IDFT.print(stdout); free(idx); free(data); MESH.get_local_data(&np, &idx, &data); for (i=0; i<np; i++){ for (j=0; j<n; j++){ data[i] += exp(imag*((-2.*M_PI*(j/(double)(n))) *((idx[i]%n) + ((idx[i]/n)%n) +(idx[i]/(n*n))))); } } MESH.write_remote_data(np, idx, data); //MESH.print(stdout); free(idx); free(data); MESH["ijk"] = MESH["pqr"]*DFT["ip"]*DFT["jq"]*DFT["kr"]; MESH.get_local_data(&np, &idx, &data); //MESH.print(stdout); for (i=0; i<np; i++){ if (idx[i]%n == (idx[i]/n)%n && idx[i]%n == idx[i]/(n*n)) assert(fabs(data[i].real() - 1.)<=1.E-9); else assert(fabs(data[i].real())<=1.E-9); } if (myRank == 0) printf("{ 3D_IDFT(3D_DFT(I))) = I } confirmed\n"); MPI_Barrier(MPI_COMM_WORLD); free(idx); free(data); } <commit_msg>straggler commit<commit_after>/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/ #include <ctf.hpp> #include <assert.h> #include <stdlib.h> /** * \brief Forms N-by-N DFT matrix A and inverse-dft iA and checks A*iA=I */ int main(int argc, char ** argv){ int myRank, numPes, logn, i, j; int64_t n, np; int64_t * idx; std::complex<double> * data; std::complex<double> imag(0,1); MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numPes); MPI_Comm_rank(MPI_COMM_WORLD, &myRank); if (argc > 1){ logn = atoi(argv[1]); if (logn<0) logn = 5; } else { logn = 5; } n = 1<<logn; int len[] = {n,n,n}; int sym[] = {NS,NS,NS}; { cCTF_World wrld; cCTF_Matrix DFT(n, n, SY, wrld); cCTF_Matrix IDFT(n, n, SY, wrld); cCTF_Tensor MESH(3, len, sym, wrld); DFT.get_local_data(&np, &idx, &data); for (i=0; i<np; i++){ data[i] = (1./n)*exp(-2.*(idx[i]/n)*(idx[i]%n)*(M_PI/n)*imag); } DFT.write_remote_data(np, idx, data); //DFT.print(stdout); free(idx); free(data); IDFT.get_local_data(&np, &idx, &data); for (i=0; i<np; i++){ data[i] = (1./n)*exp(2.*(idx[i]/n)*(idx[i]%n)*(M_PI/n)*imag); } IDFT.write_remote_data(np, idx, data); //IDFT.print(stdout); free(idx); free(data); MESH.get_local_data(&np, &idx, &data); for (i=0; i<np; i++){ for (j=0; j<n; j++){ data[i] += exp(imag*((-2.*M_PI*(j/(double)(n))) *((idx[i]%n) + ((idx[i]/n)%n) +(idx[i]/(n*n))))); } } MESH.write_remote_data(np, idx, data); //MESH.print(stdout); free(idx); free(data); MESH["ijk"] = MESH["pqr"]*DFT["ip"]*DFT["jq"]*DFT["kr"]; MESH.get_local_data(&np, &idx, &data); //MESH.print(stdout); for (i=0; i<np; i++){ if (idx[i]%n == (idx[i]/n)%n && idx[i]%n == idx[i]/(n*n)) assert(fabs(data[i].real() - 1.)<=1.E-9); else assert(fabs(data[i].real())<=1.E-9); } if (myRank == 0) printf("{ 3D_IDFT(3D_DFT(I))) = I } confirmed\n"); MPI_Barrier(MPI_COMM_WORLD); free(idx); free(data); } MPI_Finalize(); } <|endoftext|>
<commit_before>#include "../../Framework.hpp" #include "../../../core/jni_helper.hpp" namespace { ::Framework * frm() { return g_framework->NativeFramework(); } } extern "C" { JNIEXPORT void JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_putBookmark( JNIEnv * env, jobject thiz, jint x, jint y, jstring bookmarkName, jstring categoryName) { Bookmark bm(frm()->PtoG(m2::PointD(x, y)), jni::ToNativeString(env, bookmarkName), "placemark-red"); frm()->AddBookmark(jni::ToNativeString(env, categoryName), bm)->SaveToKMLFile(); } JNIEXPORT void JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nLoadBookmarks( JNIEnv * env, jobject thiz) { frm()->LoadBookmarks(); } JNIEXPORT jint JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_getCategoriesCount( JNIEnv * env, jobject thiz) { return frm()->GetBmCategoriesCount(); } JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nGetCategoryByName( JNIEnv * env, jobject thiz, jstring name) { return frm()->IsCategoryExist(jni::ToNativeString(env, name)); } JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nDeleteCategory( JNIEnv * env, jobject thiz, jint index) { return frm()->DeleteBmCategory(index); } JNIEXPORT void JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nDeleteBookmark(JNIEnv * env, jobject thiz, jint cat, jint bmk) { frm()->GetBmCategory(cat)->DeleteBookmark(bmk); } JNIEXPORT jintArray JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nGetBookmark(JNIEnv * env, jobject thiz, jint x, jint y) { BookmarkAndCategory bac = frm()->GetBookmark(m2::PointD(x, y)); jintArray result; result = env->NewIntArray(2); if (result == NULL) { return NULL; /* out of memory error thrown */ } int fill[2]; fill[0] = bac.first; fill[1] = bac.second; env->SetIntArrayRegion(result, 0, 2, fill); return result; } } <commit_msg>[android] [bookmarks] show bookmark from bookmarks manager<commit_after>#include "../../Framework.hpp" #include "../../../core/jni_helper.hpp" namespace { ::Framework * frm() { return g_framework->NativeFramework(); } } extern "C" { JNIEXPORT jint JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nShowBookmark(JNIEnv * env, jobject thiz, jint c, jint b) { frm()->ShowBookmark(*g_framework->NativeFramework()->GetBmCategory(c)->GetBookmark(b)); } JNIEXPORT void JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_putBookmark( JNIEnv * env, jobject thiz, jint x, jint y, jstring bookmarkName, jstring categoryName) { Bookmark bm(frm()->PtoG(m2::PointD(x, y)), jni::ToNativeString(env, bookmarkName), "placemark-red"); frm()->AddBookmark(jni::ToNativeString(env, categoryName), bm)->SaveToKMLFile(); } JNIEXPORT void JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nLoadBookmarks( JNIEnv * env, jobject thiz) { frm()->LoadBookmarks(); } JNIEXPORT jint JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_getCategoriesCount( JNIEnv * env, jobject thiz) { return frm()->GetBmCategoriesCount(); } JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nGetCategoryByName( JNIEnv * env, jobject thiz, jstring name) { return frm()->IsCategoryExist(jni::ToNativeString(env, name)); } JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nDeleteCategory( JNIEnv * env, jobject thiz, jint index) { return frm()->DeleteBmCategory(index); } JNIEXPORT void JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nDeleteBookmark(JNIEnv * env, jobject thiz, jint cat, jint bmk) { frm()->GetBmCategory(cat)->DeleteBookmark(bmk); } JNIEXPORT jintArray JNICALL Java_com_mapswithme_maps_bookmarks_data_BookmarkManager_nGetBookmark(JNIEnv * env, jobject thiz, jint x, jint y) { BookmarkAndCategory bac = frm()->GetBookmark(m2::PointD(x, y)); jintArray result; result = env->NewIntArray(2); if (result == NULL) { return NULL; /* out of memory error thrown */ } int fill[2]; fill[0] = bac.first; fill[1] = bac.second; env->SetIntArrayRegion(result, 0, 2, fill); return result; } } <|endoftext|>
<commit_before>#include <memory> #include <gmock/gmock.h> #include <sys/types.h> #include <sys/socket.h> #include "src/bash/bash_log_receiver.h" #include "src/bash/exception/detail/cant_open_socket_exception.h" #include "src/bash/exception/detail/loop_poll_exception.h" #include "src/bash/exception/detail/loop_recv_exception.h" #include "src/bash/exception/detail/loop_accept_exception.h" #include "src/bash/exception/detail/loop_getsockopt_exception.h" #include "src/bash/exception/detail/loop_time_exception.h" #include "src/bash/exception/detail/loop_gmtime_exception.h" #include "src/bash/exception/detail/loop_gethostname_exception.h" #include "src/bash/exception/detail/socket_is_not_open_exception.h" #include "tests/mock/bash/detail/system.h" #include "tests/mock/dbus/bus.h" #include "tests/mock/dbus/dbus_thread.h" using namespace std; using namespace bash; using namespace testing; constexpr int SOCKET_FD = 3; constexpr int TIMEOUT = 5 * 1000; #define EXAMPLE_PTR_VALUE (reinterpret_cast<struct tm*>(0x000001)) class BashLogReceiverTest : public ::testing::Test { public: void SetUp() { bus = make_shared<mock::dbus::Bus>(); dbus_thread = make_shared<mock::dbus::DBusThread>(); system = make_shared<mock::bash::System>(); } void TearDown() { } virtual ~BashLogReceiverTest() { } shared_ptr<dbus::detail::BusInterface> bus; shared_ptr<mock::dbus::DBusThread> dbus_thread; shared_ptr<mock::bash::System> system; const char *socket_path = "/tmp/bash-mod.sock"; }; TEST_F(BashLogReceiverTest, LoopNotRunningWhenObjectIsCreated) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_FALSE(receiver->IsRunning()); } TEST_F(BashLogReceiverTest, OpenSocket) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); receiver->OpenSocket(socket_path); } TEST_F(BashLogReceiverTest, OpenSocketWhenUnlinkFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenSocketFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenBindFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenListenFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenChmodFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, StartLoopWithoutOpenSocket) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); ASSERT_FALSE(receiver->IsRunning()); EXPECT_THROW(receiver->StartLoop(), exception::detail::SocketIsNotOpenException); EXPECT_FALSE(receiver->IsRunning()); } TEST_F(BashLogReceiverTest, StartLoopWhenPollFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopPollException); } TEST_F(BashLogReceiverTest, StartLoopWhenAcceptFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopAcceptException); } TEST_F(BashLogReceiverTest, StartLoopWhenGetsockoptFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopGetsockoptException); } TEST_F(BashLogReceiverTest, StartLoopWhenRecvFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopRecvException); } TEST_F(BashLogReceiverTest, StartLoopWhenTimeFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(1)); EXPECT_CALL(*system, Time(nullptr)).WillOnce(Return((time_t) (-1))); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopTimeException); } TEST_F(BashLogReceiverTest, StartLoopWhenGMTimeFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(1)); EXPECT_CALL(*system, Time(nullptr)).WillOnce(Return(1)); EXPECT_CALL(*system, GMTime(_)).WillOnce(Return(nullptr)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopGMTimeException); } TEST_F(BashLogReceiverTest, StartLoopWhenGethostnameFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(1)); EXPECT_CALL(*system, Time(nullptr)).WillOnce(Return(1)); EXPECT_CALL(*system, GMTime(_)).WillOnce(Return(EXAMPLE_PTR_VALUE)); EXPECT_CALL(*system, Gethostname(_, _)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopGethostnameException); } <commit_msg>Fix tests<commit_after>#include <memory> #include <gmock/gmock.h> #include <sys/types.h> #include <sys/socket.h> #include "src/bash/bash_log_receiver.h" #include "src/bash/exception/detail/cant_open_socket_exception.h" #include "src/bash/exception/detail/loop_poll_exception.h" #include "src/bash/exception/detail/loop_recv_exception.h" #include "src/bash/exception/detail/loop_accept_exception.h" #include "src/bash/exception/detail/loop_getsockopt_exception.h" #include "src/bash/exception/detail/loop_time_exception.h" #include "src/bash/exception/detail/loop_gmtime_exception.h" #include "src/bash/exception/detail/loop_gethostname_exception.h" #include "src/bash/exception/detail/socket_is_not_open_exception.h" #include "tests/mock/bash/detail/system.h" #include "tests/mock/dbus/bus.h" #include "tests/mock/dbus/dbus_thread.h" using namespace std; using namespace bash; using namespace testing; constexpr int SOCKET_FD = 3; constexpr int TIMEOUT = 5 * 1000; #define EXAMPLE_PTR_VALUE (reinterpret_cast<struct tm*>(0x000001)) class BashLogReceiverTest : public ::testing::Test { public: void SetUp() { bus = make_shared<mock::dbus::Bus>(); dbus_thread = make_shared<mock::dbus::DBusThread>(); system = make_shared<mock::bash::System>(); } void TearDown() { } virtual ~BashLogReceiverTest() { } shared_ptr<dbus::detail::BusInterface> bus; shared_ptr<mock::dbus::DBusThread> dbus_thread; shared_ptr<mock::bash::System> system; const char *socket_path = "/tmp/bash-mod.sock"; }; TEST_F(BashLogReceiverTest, LoopNotRunningWhenObjectIsCreated) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_FALSE(receiver->IsRunning()); } TEST_F(BashLogReceiverTest, OpenSocket) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); receiver->OpenSocket(socket_path); } TEST_F(BashLogReceiverTest, OpenSocketWhenUnlinkFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(-1)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); receiver->OpenSocket(socket_path); } TEST_F(BashLogReceiverTest, OpenSocketWhenSocketFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenBindFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenListenFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, OpenSocketWhenChmodFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(-1)); EXPECT_THROW(receiver->OpenSocket(socket_path), exception::detail::CantOpenSocketException); } TEST_F(BashLogReceiverTest, StartLoopWithoutOpenSocket) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); ASSERT_FALSE(receiver->IsRunning()); EXPECT_THROW(receiver->StartLoop(), exception::detail::SocketIsNotOpenException); EXPECT_FALSE(receiver->IsRunning()); } TEST_F(BashLogReceiverTest, StartLoopWhenPollFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopPollException); } TEST_F(BashLogReceiverTest, StartLoopWhenAcceptFailed) { shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopAcceptException); } TEST_F(BashLogReceiverTest, StartLoopWhenGetsockoptFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopGetsockoptException); } TEST_F(BashLogReceiverTest, StartLoopWhenRecvFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopRecvException); } TEST_F(BashLogReceiverTest, StartLoopWhenTimeFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(1)); EXPECT_CALL(*system, Time(nullptr)).WillOnce(Return((time_t) (-1))); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopTimeException); } TEST_F(BashLogReceiverTest, StartLoopWhenGMTimeFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(1)); EXPECT_CALL(*system, Time(nullptr)).WillOnce(Return(1)); EXPECT_CALL(*system, GMTime(_)).WillOnce(Return(nullptr)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopGMTimeException); } TEST_F(BashLogReceiverTest, StartLoopWhenGethostnameFailed) { constexpr int new_fd = 95; shared_ptr<BashLogReceiver> receiver = BashLogReceiver::Create(bus, dbus_thread, system); EXPECT_CALL(*system, Unlink(StrEq(socket_path))).WillOnce(Return(0)); EXPECT_CALL(*system, Socket(PF_UNIX, SOCK_STREAM, 0)).WillOnce(Return(SOCKET_FD)); EXPECT_CALL(*system, Bind(SOCKET_FD, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Listen(SOCKET_FD, 20)).WillOnce(Return(0)); EXPECT_CALL(*system, Chmod(StrEq(socket_path), 0622)).WillOnce(Return(0)); EXPECT_CALL(*system, Poll(NotNull(), Eq(1), TIMEOUT)).WillOnce(Return(1)); EXPECT_CALL(*system, Accept(SOCKET_FD, _, _)).WillOnce(Return(new_fd)); EXPECT_CALL(*system, Getsockopt(new_fd, SOL_SOCKET, SO_PEERCRED, _, _)).WillOnce(Return(0)); EXPECT_CALL(*system, Recv(new_fd, _, _, 0)).WillOnce(Return(1)); EXPECT_CALL(*system, Time(nullptr)).WillOnce(Return(1)); EXPECT_CALL(*system, GMTime(_)).WillOnce(Return(EXAMPLE_PTR_VALUE)); EXPECT_CALL(*system, Gethostname(_, _)).WillOnce(Return(-1)); receiver->OpenSocket(socket_path); EXPECT_THROW(receiver->StartLoop(), exception::detail::LoopGethostnameException); } <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <tinyxml2.h> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <dart/common/Console.h> #include <dart/common/Uri.h> #include <dart/common/LocalResourceRetriever.h> #include <aikido/util/CatkinResourceRetriever.hpp> static const std::string CATKIN_MARKER(".catkin"); using dart::common::Uri; namespace aikido { namespace util { namespace { std::string getPackageNameFromXML(const std::string& _path) { using tinyxml2::XMLHandle; using tinyxml2::XMLElement; tinyxml2::XMLDocument document; if (document.LoadFile(_path.c_str())) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': " << document.GetErrorStr1() << "\n"; return ""; } XMLHandle root_handle(document.RootElement()); XMLHandle name_handle = root_handle.FirstChildElement("name"); XMLElement* name_element = name_handle.ToElement(); if (!name_element) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': File does not contain a <name> element.\n"; return ""; } if (!name_element->GetText()) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': <name> element is empty.\n"; return ""; } std::string package_name = name_element->GetText(); boost::algorithm::trim(package_name); if (package_name.empty()) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': <name> element is empty.\n"; return ""; } return package_name; } void searchForPackages(const boost::filesystem::path& _packagePath, std::unordered_map<std::string, std::string>& _packageMap) { using boost::filesystem::directory_iterator; using boost::filesystem::path; using boost::filesystem::file_status; using boost::filesystem::exists; // Ignore this directory if it contains a CATKIN_IGNORE file. const path catkin_ignore_path = _packagePath / "CATKIN_IGNORE"; if (exists(catkin_ignore_path)) return; // Try loading the package.xml file. const path package_xml_path = _packagePath / "package.xml"; if (exists(package_xml_path)) { const std::string package_name = getPackageNameFromXML( package_xml_path.string()); if (!package_name.empty()) { const auto result = _packageMap.insert( std::make_pair(package_name, _packagePath.string())); if (!result.second) { dtwarn << "[CatkinResourceRetriever] Found two package.xml" " files for package '" << package_name << "': '" << result.first->second << "' and '" << _packagePath << "'.\n"; } return; // Don't search for packages inside packages. } } // Recurse on subdirectories. directory_iterator it(_packagePath); directory_iterator end; while (it != end) { boost::system::error_code status_error; const file_status status = it->status(status_error); if (status_error) { dtwarn << "[CatkinResourceRetriever] Failed recursing into directory '" << it->path() << "'.\n"; continue; } if (status.type() == boost::filesystem::directory_file) searchForPackages(it->path().string(), _packageMap); ++it; } } } // namespace CatkinResourceRetriever::CatkinResourceRetriever() : CatkinResourceRetriever( std::make_shared<dart::common::LocalResourceRetriever>()) { } CatkinResourceRetriever::CatkinResourceRetriever( const dart::common::ResourceRetrieverPtr& _delegate) : mDelegate(_delegate) , mWorkspaces(getWorkspaces()) { } bool CatkinResourceRetriever::exists(const Uri& _uri) { const Uri resolvedUri = resolvePackageUri(_uri); if(resolvedUri.mPath) return mDelegate->exists(resolvedUri); else return false; } dart::common::ResourcePtr CatkinResourceRetriever::retrieve(const Uri& _uri) { const Uri resolvedUri = resolvePackageUri(_uri); if(resolvedUri.mPath) return mDelegate->retrieve(resolvedUri); else return nullptr; } auto CatkinResourceRetriever::getWorkspaces() const -> std::vector<Workspace> { using dart::common::ResourcePtr; using boost::filesystem::path; const char *cmake_prefix_path = std::getenv("CMAKE_PREFIX_PATH"); if (!cmake_prefix_path) { dtwarn << "[CatkinResourceRetriever::getWorkspaces] The CMAKE_PREFIX_PATH" " environmental variable is not defined. Did you source" " 'setup.bash' in this shell?\n"; return std::vector<Workspace>(); } // Split CMAKE_PREFIX_PATH by the ':' path separator delimiter. std::vector<std::string> workspace_candidates; boost::split(workspace_candidates, cmake_prefix_path, boost::is_any_of(":")); // Filter out directories that are missing the Catkin marker file. If the // marker file exists, then we also read its contents to build a list of all // source directories. std::vector<Workspace> workspaces; for (const std::string& workspace_path : workspace_candidates) { if (workspace_path.empty()) continue; const Uri workspace_uri = Uri::createFromPath(workspace_path + "/"); const Uri marker_uri = Uri::createFromRelativeUri( workspace_uri, CATKIN_MARKER); // Skip non-Catkin workspaces by checking for the marker file. We do this // before reading the file because there is no way to differentiate between // "file does not exist" and other types of errors (e.g. permission) // through the std::ifstream API. if (!mDelegate->exists(workspace_uri)) continue; Workspace workspace; workspace.mPath = workspace_path; // Read the list of source packages (if any) from the marker file. const ResourcePtr marker_resource = mDelegate->retrieve(marker_uri); if (marker_resource) { const size_t filesize = marker_resource->getSize(); std::string contents; contents.resize(filesize); marker_resource->read(&contents.front(), filesize, 1); // Split the string into a list of paths by the ';' delimiter. I'm not // sure why this doesn't use the standard path separator delimitor ':'. std::vector<std::string> source_paths; if (!contents.empty()) boost::split(source_paths, contents, boost::is_any_of(";")); for (const std::string& source_path : source_paths) searchForPackages(source_path, workspace.mSourceMap); } else { dtwarn << "[CatkinResourceRetriever::getWorkspaces] Failed reading package" " source directories from the marker file '" << marker_uri.getFilesystemPath() << "'. Resources in the source" " space of this workspace will not resolve.\n"; } workspaces.push_back(workspace); } return workspaces; } Uri CatkinResourceRetriever::resolvePackageUri(const Uri& _uri) const { using boost::filesystem::path; if(!_uri.mScheme || *_uri.mScheme != "package") return ""; if(!_uri.mAuthority) { dtwarn << "Failed extracting package name from URI '" << _uri.toString() << ".\n"; return ""; } const std::string& packageName = *_uri.mAuthority; std::string relativePath = _uri.mPath.get_value_or(""); // Strip the leading "/", so this path will be interpreted as being relative // to the package directory. if (!relativePath.empty() && relativePath.front() == '/') relativePath = relativePath.substr(1); // Sequentially check each chained workspace. for (const Workspace& workspace : mWorkspaces) { // First check the 'devel' or 'install' space. const path develPath = path(workspace.mPath) / "share" / packageName; const Uri resourceDevelUri = Uri::createFromRelativeUri( Uri::createFromPath(develPath.string() + "/"), relativePath); if (mDelegate->exists(resourceDevelUri)) return resourceDevelUri; // Next, check the source space. const auto it = workspace.mSourceMap.find(packageName); if (it != std::end(workspace.mSourceMap)) { const Uri resourceSourceUri = Uri::createFromRelativeUri( Uri::createFromPath(it->second + "/"), relativePath); if (mDelegate->exists(resourceSourceUri)) return resourceSourceUri; } } return Uri(); } } // namespace util } // namespace aikido <commit_msg>Return nullptr instead of blank string<commit_after>#include <fstream> #include <iostream> #include <tinyxml2.h> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <dart/common/Console.h> #include <dart/common/Uri.h> #include <dart/common/LocalResourceRetriever.h> #include <aikido/util/CatkinResourceRetriever.hpp> static const std::string CATKIN_MARKER(".catkin"); using dart::common::Uri; namespace aikido { namespace util { namespace { std::string getPackageNameFromXML(const std::string& _path) { using tinyxml2::XMLHandle; using tinyxml2::XMLElement; tinyxml2::XMLDocument document; if (document.LoadFile(_path.c_str())) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': " << document.GetErrorStr1() << "\n"; return ""; } XMLHandle root_handle(document.RootElement()); XMLHandle name_handle = root_handle.FirstChildElement("name"); XMLElement* name_element = name_handle.ToElement(); if (!name_element) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': File does not contain a <name> element.\n"; return ""; } if (!name_element->GetText()) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': <name> element is empty.\n"; return ""; } std::string package_name = name_element->GetText(); boost::algorithm::trim(package_name); if (package_name.empty()) { dtwarn << "[CatkinResourceRetriever] Failed loading package.xml file '" << _path << "': <name> element is empty.\n"; return ""; } return package_name; } void searchForPackages(const boost::filesystem::path& _packagePath, std::unordered_map<std::string, std::string>& _packageMap) { using boost::filesystem::directory_iterator; using boost::filesystem::path; using boost::filesystem::file_status; using boost::filesystem::exists; // Ignore this directory if it contains a CATKIN_IGNORE file. const path catkin_ignore_path = _packagePath / "CATKIN_IGNORE"; if (exists(catkin_ignore_path)) return; // Try loading the package.xml file. const path package_xml_path = _packagePath / "package.xml"; if (exists(package_xml_path)) { const std::string package_name = getPackageNameFromXML( package_xml_path.string()); if (!package_name.empty()) { const auto result = _packageMap.insert( std::make_pair(package_name, _packagePath.string())); if (!result.second) { dtwarn << "[CatkinResourceRetriever] Found two package.xml" " files for package '" << package_name << "': '" << result.first->second << "' and '" << _packagePath << "'.\n"; } return; // Don't search for packages inside packages. } } // Recurse on subdirectories. directory_iterator it(_packagePath); directory_iterator end; while (it != end) { boost::system::error_code status_error; const file_status status = it->status(status_error); if (status_error) { dtwarn << "[CatkinResourceRetriever] Failed recursing into directory '" << it->path() << "'.\n"; continue; } if (status.type() == boost::filesystem::directory_file) searchForPackages(it->path().string(), _packageMap); ++it; } } } // namespace CatkinResourceRetriever::CatkinResourceRetriever() : CatkinResourceRetriever( std::make_shared<dart::common::LocalResourceRetriever>()) { } CatkinResourceRetriever::CatkinResourceRetriever( const dart::common::ResourceRetrieverPtr& _delegate) : mDelegate(_delegate) , mWorkspaces(getWorkspaces()) { } bool CatkinResourceRetriever::exists(const Uri& _uri) { const Uri resolvedUri = resolvePackageUri(_uri); if(resolvedUri.mPath) return mDelegate->exists(resolvedUri); else return false; } dart::common::ResourcePtr CatkinResourceRetriever::retrieve(const Uri& _uri) { const Uri resolvedUri = resolvePackageUri(_uri); if(resolvedUri.mPath) return mDelegate->retrieve(resolvedUri); else return nullptr; } auto CatkinResourceRetriever::getWorkspaces() const -> std::vector<Workspace> { using dart::common::ResourcePtr; using boost::filesystem::path; const char *cmake_prefix_path = std::getenv("CMAKE_PREFIX_PATH"); if (!cmake_prefix_path) { dtwarn << "[CatkinResourceRetriever::getWorkspaces] The CMAKE_PREFIX_PATH" " environmental variable is not defined. Did you source" " 'setup.bash' in this shell?\n"; return std::vector<Workspace>(); } // Split CMAKE_PREFIX_PATH by the ':' path separator delimiter. std::vector<std::string> workspace_candidates; boost::split(workspace_candidates, cmake_prefix_path, boost::is_any_of(":")); // Filter out directories that are missing the Catkin marker file. If the // marker file exists, then we also read its contents to build a list of all // source directories. std::vector<Workspace> workspaces; for (const std::string& workspace_path : workspace_candidates) { if (workspace_path.empty()) continue; const Uri workspace_uri = Uri::createFromPath(workspace_path + "/"); const Uri marker_uri = Uri::createFromRelativeUri( workspace_uri, CATKIN_MARKER); // Skip non-Catkin workspaces by checking for the marker file. We do this // before reading the file because there is no way to differentiate between // "file does not exist" and other types of errors (e.g. permission) // through the std::ifstream API. if (!mDelegate->exists(workspace_uri)) continue; Workspace workspace; workspace.mPath = workspace_path; // Read the list of source packages (if any) from the marker file. const ResourcePtr marker_resource = mDelegate->retrieve(marker_uri); if (marker_resource) { const size_t filesize = marker_resource->getSize(); std::string contents; contents.resize(filesize); marker_resource->read(&contents.front(), filesize, 1); // Split the string into a list of paths by the ';' delimiter. I'm not // sure why this doesn't use the standard path separator delimitor ':'. std::vector<std::string> source_paths; if (!contents.empty()) boost::split(source_paths, contents, boost::is_any_of(";")); for (const std::string& source_path : source_paths) searchForPackages(source_path, workspace.mSourceMap); } else { dtwarn << "[CatkinResourceRetriever::getWorkspaces] Failed reading package" " source directories from the marker file '" << marker_uri.getFilesystemPath() << "'. Resources in the source" " space of this workspace will not resolve.\n"; } workspaces.push_back(workspace); } return workspaces; } Uri CatkinResourceRetriever::resolvePackageUri(const Uri& _uri) const { using boost::filesystem::path; if(!_uri.mScheme || *_uri.mScheme != "package") return Uri(); if(!_uri.mAuthority) { dtwarn << "Failed extracting package name from URI '" << _uri.toString() << ".\n"; return Uri(); } const std::string& packageName = *_uri.mAuthority; std::string relativePath = _uri.mPath.get_value_or(""); // Strip the leading "/", so this path will be interpreted as being relative // to the package directory. if (!relativePath.empty() && relativePath.front() == '/') relativePath = relativePath.substr(1); // Sequentially check each chained workspace. for (const Workspace& workspace : mWorkspaces) { // First check the 'devel' or 'install' space. const path develPath = path(workspace.mPath) / "share" / packageName; const Uri resourceDevelUri = Uri::createFromRelativeUri( Uri::createFromPath(develPath.string() + "/"), relativePath); if (mDelegate->exists(resourceDevelUri)) return resourceDevelUri; // Next, check the source space. const auto it = workspace.mSourceMap.find(packageName); if (it != std::end(workspace.mSourceMap)) { const Uri resourceSourceUri = Uri::createFromRelativeUri( Uri::createFromPath(it->second + "/"), relativePath); if (mDelegate->exists(resourceSourceUri)) return resourceSourceUri; } } return Uri(); } } // namespace util } // namespace aikido <|endoftext|>
<commit_before>// Copyright (c) 2012-2013, Steinwurf ApS // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Steinwurf ApS nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cstdint> #include <ctime> #include <algorithm> #include <fstream> #include <gtest/gtest.h> #include <sak/file_input_stream.hpp> /// Tests reading a file, the file is crated a priori TEST(TestFileInputStream, ReadRandomFile) { { uint32_t file_size = 1000; std::string file_name("test.txt"); std::vector<char> output_buffer(file_size, '\0'); for (uint32_t i = 0; i < file_size; ++i) { output_buffer[i] = (rand() % 255); } std::ofstream output_file(file_name.c_str(), std::ios::out | std::ios::binary); ASSERT_TRUE(output_file.is_open()); output_file.write(&output_buffer[0], file_size); output_file.close(); // Now test we can read it back sak::file_input_stream fs; boost::system::error_code ec; fs.open(file_name, ec); ASSERT_FALSE(ec); ASSERT_EQ(file_size, fs.bytes_available()); uint32_t read_size = 512; std::vector<char> input_buffer; while (fs.bytes_available() > 0) { uint32_t read = std::min(read_size, fs.bytes_available()); ASSERT_TRUE(read <= read_size); std::vector<char> temp(read, '\0'); fs.read(reinterpret_cast<uint8_t*>(&temp[0]), read); input_buffer.insert(input_buffer.end(), temp.begin(), temp.end()); } bool result = std::equal( input_buffer.begin(), input_buffer.end(), output_buffer.begin() ); ASSERT_TRUE(result); } } #if defined(__EXCEPTIONS) /// Tests error handling with exception TEST(TestFileInputStream, ExceptionThrow) { sak::file_input_stream fs; boost::system::error_code ec; std::cout << "Excpetions defined " << std::endl; try { fs.open("strange_file_that_should_not_exist.notfound"); } catch (const boost::system::system_error& error) { ec = error.code(); } EXPECT_EQ(ec, sak::error::failed_open_file); } #endif /// Tests error handling with exception TEST(TestFileInputStream, ExceptionReturn) { sak::file_input_stream fs; boost::system::error_code ec; fs.open("strange_file_that_should_not_exist.notfound", ec); EXPECT_EQ(ec, sak::error::failed_open_file); } // // /// Tests error handling with exception in constructor // TEST(TestFileInputStream, ExceptionThrowConstructor) // { // // // boost::system::error_code ec; // // try // { // sak::file_input_stream fs( // "strange_file_that_should_not_exist.notfound"); // } // catch (const boost::system::system_error& error) // { // ec = error.code(); // } // // EXPECT_EQ(ec, sak::error::failed_open_file); // // } <commit_msg>Trigger build<commit_after>// Copyright (c) 2012-2013, Steinwurf ApS // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Steinwurf ApS nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cstdint> #include <ctime> #include <algorithm> #include <fstream> #include <gtest/gtest.h> #include <sak/file_input_stream.hpp> /// Tests reading a file, the file is crated a priori TEST(TestFileInputStream, ReadRandomFile) { { uint32_t file_size = 1000; std::string file_name("test.txt"); std::vector<char> output_buffer(file_size, '\0'); for (uint32_t i = 0; i < file_size; ++i) { output_buffer[i] = (rand() % 255); } std::ofstream output_file(file_name.c_str(), std::ios::out | std::ios::binary); ASSERT_TRUE(output_file.is_open()); output_file.write(&output_buffer[0], file_size); output_file.close(); // Now test we can read it back sak::file_input_stream fs; boost::system::error_code ec; fs.open(file_name, ec); ASSERT_FALSE(ec); ASSERT_EQ(file_size, fs.bytes_available()); uint32_t read_size = 512; std::vector<char> input_buffer; while (fs.bytes_available() > 0) { uint32_t read = std::min(read_size, fs.bytes_available()); ASSERT_TRUE(read <= read_size); std::vector<char> temp(read, '\0'); fs.read(reinterpret_cast<uint8_t*>(&temp[0]), read); input_buffer.insert(input_buffer.end(), temp.begin(), temp.end()); } bool result = std::equal( input_buffer.begin(), input_buffer.end(), output_buffer.begin() ); ASSERT_TRUE(result); } } #if defined(__EXCEPTIONS) /// Tests error handling with exception TEST(TestFileInputStream, ExceptionThrow) { sak::file_input_stream fs; boost::system::error_code ec; std::cout << "Excpetions defined" << std::endl; try { fs.open("strange_file_that_should_not_exist.notfound"); } catch (const boost::system::system_error& error) { ec = error.code(); } EXPECT_EQ(ec, sak::error::failed_open_file); } #endif /// Tests error handling with exception TEST(TestFileInputStream, ExceptionReturn) { sak::file_input_stream fs; boost::system::error_code ec; fs.open("strange_file_that_should_not_exist.notfound", ec); EXPECT_EQ(ec, sak::error::failed_open_file); } // // /// Tests error handling with exception in constructor // TEST(TestFileInputStream, ExceptionThrowConstructor) // { // // // boost::system::error_code ec; // // try // { // sak::file_input_stream fs( // "strange_file_that_should_not_exist.notfound"); // } // catch (const boost::system::system_error& error) // { // ec = error.code(); // } // // EXPECT_EQ(ec, sak::error::failed_open_file); // // } <|endoftext|>
<commit_before>// // Implements advanced object detection methods // #include <jni.h> #include <vector> #include <stdio.h> #include "opencv2/core.hpp" #include "opencv2/features2d.hpp" #include "opencv2/highgui.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/xfeatures2d.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/flann.hpp" #include "opencv2/line_descriptor/descriptor.hpp" using namespace std; using namespace cv; using namespace cv::xfeatures2d; using namespace cvflann; using namespace cv::line_descriptor; extern "C" { Mat img_object; // DETECTOR // Standard SURF detector Ptr<SURF> detector; // DESCRIPTOR // Our proposed FREAK descriptor // (rotation invariance, scale invariance, pattern radius corresponding to SMALLEST_KP_SIZE, // number of octaves, optional vector containing the selected pairs) // FREAK extractor(true, true, 22, 4, std::vector<int>()); Ptr<FREAK> extractor; std::vector<KeyPoint> keypoints_object; Mat descriptors_object; JNIEXPORT void JNICALL Java_com_lasarobotics_vision_detection_Detection_analyzeObject(JNIEnv* jobject, jlong addrGrayObject) { img_object = *(Mat*)addrGrayObject; if( !img_object.data ) { printf(" --(!) Error reading images "); return; } //-- Step 1: Detect the keypoints using SURF Detector //detect detector = SURF::create(600); detector->detect( img_object, keypoints_object ); //extract extractor = FREAK::create(); extractor->compute( img_object, keypoints_object, descriptors_object); } JNIEXPORT void JNICALL Java_com_lasarobotics_vision_detection_Detection_findObject(JNIEnv* jobject, jlong addrGrayObject, jlong addrGrayScene, jlong addrOutput) { Mat img_scene = *(Mat*)addrGrayScene; Mat img_matches = *(Mat*)addrOutput; if( !img_object.data || !img_scene.data ) { printf(" --(!) Error reading images "); return; } // MATCHER // The standard Hamming distance can be used such as // BruteForceMatcher<Hamming> matcher; // or the proposed cascade of hamming distance using SSSE3 BFMatcher matcher(NORM_HAMMING2); // detect std::vector<KeyPoint> keypoints_scene; detector->detect( img_scene, keypoints_scene ); // extract Mat descriptors_scene; extractor->compute( img_scene, keypoints_scene, descriptors_scene ); if ((descriptors_object.cols != descriptors_scene.cols) || (descriptors_object.type() != descriptors_scene.type())) { return; } // match std::vector<DMatch> matches; matcher.match(descriptors_object, descriptors_scene, matches); double max_dist = 0; double min_dist = 100; //-- Quick calculation of max and min distances between keypoints for( int i = 0; i < descriptors_object.rows; i++ ) { double dist = matches[i].distance; if( dist < min_dist ) min_dist = dist; if( dist > max_dist ) max_dist = dist; } printf("-- Max dist : %f \n", max_dist ); printf("-- Min dist : %f \n", min_dist ); //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist ) std::vector< DMatch > good_matches; for( int i = 0; i < descriptors_object.rows; i++ ) { if( matches[i].distance < 3*min_dist ) { good_matches.push_back( matches[i]); } } //drawMatches( img_object, keypoints_object, img_scene, keypoints_scene, // good_matches, img_matches, Scalar::all(-1), Scalar::all(-1), // vector<char>(), DrawMatchesFlags::DRAW_OVER_OUTIMG); //-- Localize the object std::vector<Point2f> obj; std::vector<Point2f> scene; for( int i = 0; i < good_matches.size(); i++ ) { //-- Get the keypoints from the good matches obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt ); scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt ); } if ((obj.size() < 4) || (scene.size() < 4)) { return; } Mat H = findHomography( obj, scene, RANSAC ); //-- Get the corners from the image_1 ( the object to be "detected" ) std::vector<Point2f> obj_corners(4); obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( img_object.cols, 0 ); obj_corners[2] = cvPoint( img_object.cols, img_object.rows ); obj_corners[3] = cvPoint( 0, img_object.rows ); std::vector<Point2f> scene_corners(4); if(obj_corners.size() != scene_corners.size()) { return; } //if (H.cols() != 3 || H.rows) perspectiveTransform( obj_corners, scene_corners, H); //-- Draw lines between the corners (the mapped object in the scene - image_2 ) line( img_matches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 ); line( img_matches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 ); line( img_matches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 ); line( img_matches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 ); //-- Show detected matches //imshow( "Good Matches & Object detection", img_matches ); //return;*/ } } //extern "C"<commit_msg>Remove another fatal bug<commit_after>// // Implements advanced object detection methods // #include <jni.h> #include <vector> #include <stdio.h> #include "opencv2/core.hpp" #include "opencv2/features2d.hpp" #include "opencv2/highgui.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/xfeatures2d.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/flann.hpp" #include "opencv2/line_descriptor/descriptor.hpp" using namespace std; using namespace cv; using namespace cv::xfeatures2d; using namespace cvflann; using namespace cv::line_descriptor; extern "C" { Mat img_object; // DETECTOR // Standard SURF detector Ptr<SURF> detector; // DESCRIPTOR // Our proposed FREAK descriptor // (rotation invariance, scale invariance, pattern radius corresponding to SMALLEST_KP_SIZE, // number of octaves, optional vector containing the selected pairs) // FREAK extractor(true, true, 22, 4, std::vector<int>()); Ptr<FREAK> extractor; std::vector<KeyPoint> keypoints_object; Mat descriptors_object; JNIEXPORT void JNICALL Java_com_lasarobotics_vision_detection_Detection_analyzeObject(JNIEnv* jobject, jlong addrGrayObject) { img_object = *(Mat*)addrGrayObject; if( !img_object.data ) { printf(" --(!) Error reading images "); return; } //-- Step 1: Detect the keypoints using SURF Detector //detect detector = SURF::create(600); detector->detect( img_object, keypoints_object ); //extract extractor = FREAK::create(); extractor->compute( img_object, keypoints_object, descriptors_object); } JNIEXPORT void JNICALL Java_com_lasarobotics_vision_detection_Detection_findObject(JNIEnv* jobject, jlong addrGrayObject, jlong addrGrayScene, jlong addrOutput) { Mat img_scene = *(Mat*)addrGrayScene; Mat img_matches = *(Mat*)addrOutput; if( !img_object.data || !img_scene.data ) { printf(" --(!) Error reading images "); return; } // MATCHER // The standard Hamming distance can be used such as // BruteForceMatcher<Hamming> matcher; // or the proposed cascade of hamming distance using SSSE3 BFMatcher matcher(NORM_HAMMING2); // detect std::vector<KeyPoint> keypoints_scene; detector->detect( img_scene, keypoints_scene ); // extract Mat descriptors_scene; extractor->compute( img_scene, keypoints_scene, descriptors_scene ); if ((descriptors_object.cols != descriptors_scene.cols) || (descriptors_object.type() != descriptors_scene.type())) { return; } // match std::vector<DMatch> matches; matcher.match(descriptors_object, descriptors_scene, matches); double max_dist = 0; double min_dist = 100; //-- Quick calculation of max and min distances between keypoints for( int i = 0; i < descriptors_object.rows; i++ ) { double dist = matches[i].distance; if( dist < min_dist ) min_dist = dist; if( dist > max_dist ) max_dist = dist; } printf("-- Max dist : %f \n", max_dist ); printf("-- Min dist : %f \n", min_dist ); //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist ) std::vector< DMatch > good_matches; for( int i = 0; i < descriptors_object.rows; i++ ) { if( matches[i].distance < 3*min_dist ) { good_matches.push_back( matches[i]); } } //drawMatches( img_object, keypoints_object, img_scene, keypoints_scene, // good_matches, img_matches, Scalar::all(-1), Scalar::all(-1), // vector<char>(), DrawMatchesFlags::DRAW_OVER_OUTIMG); //-- Localize the object std::vector<Point2f> obj; std::vector<Point2f> scene; for( int i = 0; i < good_matches.size(); i++ ) { //-- Get the keypoints from the good matches obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt ); scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt ); } if ((obj.size() < 4) || (scene.size() < 4)) { return; } Mat H = findHomography( obj, scene, RANSAC ); //-- Get the corners from the image_1 ( the object to be "detected" ) std::vector<Point2f> obj_corners(4); obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( img_object.cols, 0 ); obj_corners[2] = cvPoint( img_object.cols, img_object.rows ); obj_corners[3] = cvPoint( 0, img_object.rows ); std::vector<Point2f> scene_corners(4); if(obj_corners.size() != scene_corners.size()) { return; } if (H.cols!= 3 || H.rows != 3) { return; } perspectiveTransform( obj_corners, scene_corners, H); //-- Draw lines between the corners (the mapped object in the scene - image_2 ) line( img_matches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 ); line( img_matches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 ); line( img_matches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 ); line( img_matches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 ); //-- Show detected matches //imshow( "Good Matches & Object detection", img_matches ); //return;*/ } } //extern "C"<|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #define BOOST_FILESYSTEM_VERSION 2 #include <boost/filesystem/path.hpp> #include <gtest/gtest.h> #include <ros/ros.h> #include <system_util/file_util.h> TEST(FileUtilTests, Uncomplete) { std::string path1; ASSERT_TRUE(ros::param::get("path1", path1)); std::string path2; ASSERT_TRUE(ros::param::get("path2", path2)); std::string path3; ASSERT_TRUE(ros::param::get("path3", path3)); EXPECT_EQ(boost::filesystem::path("./"), system_util::NaiveUncomplete(path1, path1)); EXPECT_EQ(boost::filesystem::path("src"), system_util::NaiveUncomplete(path2, path1)); EXPECT_EQ(boost::filesystem::path("include/system_util"), system_util::NaiveUncomplete(path3, path1)); EXPECT_EQ(boost::filesystem::path("../"), system_util::NaiveUncomplete(path1, path2)); EXPECT_EQ(boost::filesystem::path("../../"), system_util::NaiveUncomplete(path1, path3)); EXPECT_EQ(boost::filesystem::path(""), system_util::NaiveUncomplete(boost::filesystem::path(""), path1)); EXPECT_EQ(boost::filesystem::path(""), system_util::NaiveUncomplete(path1, boost::filesystem::path(""))); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_file_util"); ros::NodeHandle nh; return RUN_ALL_TESTS(); } <commit_msg>fix boost filesystem issue<commit_after>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <boost/filesystem/path.hpp> #include <gtest/gtest.h> #include <ros/ros.h> #include <system_util/file_util.h> TEST(FileUtilTests, Uncomplete) { std::string path1; ASSERT_TRUE(ros::param::get("path1", path1)); std::string path2; ASSERT_TRUE(ros::param::get("path2", path2)); std::string path3; ASSERT_TRUE(ros::param::get("path3", path3)); EXPECT_EQ(boost::filesystem::path("./"), system_util::NaiveUncomplete(path1, path1)); EXPECT_EQ(boost::filesystem::path("src"), system_util::NaiveUncomplete(path2, path1)); EXPECT_EQ(boost::filesystem::path("include/system_util"), system_util::NaiveUncomplete(path3, path1)); EXPECT_EQ(boost::filesystem::path("../"), system_util::NaiveUncomplete(path1, path2)); EXPECT_EQ(boost::filesystem::path("../../"), system_util::NaiveUncomplete(path1, path3)); EXPECT_EQ(boost::filesystem::path(""), system_util::NaiveUncomplete(boost::filesystem::path(""), path1)); EXPECT_EQ(boost::filesystem::path(""), system_util::NaiveUncomplete(path1, boost::filesystem::path(""))); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_file_util"); ros::NodeHandle nh; return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <tamer/driver.hh> #include <tamer/adapter.hh> #include <sys/select.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> namespace tamer { driver driver::main; // using the "self-pipe trick" recommended by select(3) and sfslite. namespace { #define NSIGNALS 32 int sig_pipe[2] = { -1, -1 }; volatile unsigned sig_any_active; volatile unsigned sig_active[NSIGNALS]; volatile int sig_installing = -1; event<> sig_handlers[NSIGNALS]; class sigcancel_rendezvous : public rendezvous<> { public: sigcancel_rendezvous() { } inline void add(tamerpriv::simple_event *e) throw () { _nwaiting++; e->initialize(this, sig_installing); } void complete(uintptr_t rname, bool success) { if ((int) rname != sig_installing && success) { struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(rname, &sa, 0); } rendezvous<>::complete(rname, success); } }; sigcancel_rendezvous sigcancelr; } driver::driver() : _t(0), _nt(0), _fd(0), _nfds(0), _tcap(0), _tgroup(0), _tfree(0), _fdcap(0), _fdgroup(0), _fdfree(0) { expand_timers(); FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); FD_ZERO(&_fdset[fdclose]); set_now(); } driver::~driver() { // destroy all active timers for (int i = 0; i < _nt; i++) _t[i]->~ttimer(); // free timer groups while (_tgroup) { ttimer_group *next = _tgroup->next; delete[] reinterpret_cast<unsigned char *>(_tgroup); _tgroup = next; } delete[] _t; // destroy all active file descriptors while (_fd) { _fd->e.~event(); _fd = _fd->next; } // free file descriptor groups while (_fdgroup) { tfd_group *next = _fdgroup->next; delete[] reinterpret_cast<unsigned char *>(_fdgroup); _fdgroup = next; } } void driver::expand_timers() { int ncap = (_tcap ? _tcap * 2 : 16); ttimer_group *ngroup = reinterpret_cast<ttimer_group *>(new unsigned char[sizeof(ttimer_group) + sizeof(ttimer) * (ncap - 1)]); ngroup->next = _tgroup; _tgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].u.next = _tfree; _tfree = &ngroup->t[i]; } ttimer **t = new ttimer *[ncap]; memcpy(t, _t, sizeof(ttimer *) * _nt); delete[] _t; _t = t; _tcap = ncap; } void driver::timer_reheapify_from(int pos, ttimer *t, bool /*will_delete*/) { int npos; while (pos > 0 && (npos = (pos-1) >> 1, timercmp(&_t[npos]->expiry, &t->expiry, >))) { _t[pos] = _t[npos]; _t[npos]->u.schedpos = pos; pos = npos; } while (1) { ttimer *smallest = t; npos = 2*pos + 1; if (npos < _nt && !timercmp(&_t[npos]->expiry, &smallest->expiry, >)) smallest = _t[npos]; if (npos + 1 < _nt && !timercmp(&_t[npos+1]->expiry, &smallest->expiry, >)) smallest = _t[npos+1], npos++; smallest->u.schedpos = pos; _t[pos] = smallest; if (smallest == t) break; pos = npos; } #if 0 if (_t + 1 < tend || !will_delete) _timer_expiry = tbegin[0]->expiry; else _timer_expiry = Timestamp(); #endif } #if 0 void driver::check_timers() const { fprintf(stderr, "---"); for (int k = 0; k < _nt; k++) fprintf(stderr, " %p/%d.%06d", _t[k], _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); for (int i = 0; i < _nt / 2; i++) for (int j = 2*i + 1; j < 2*i + 3; j++) if (j < _nt && timercmp(&_t[i]->expiry, &_t[j]->expiry, >)) { fprintf(stderr, "***"); for (int k = 0; k < _nt; k++) fprintf(stderr, (k == i || k == j ? " **%d.%06d**" : " %d.%06d"), _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); assert(0); } } #endif void driver::expand_fds() { int ncap = (_fdcap ? _fdcap * 2 : 16); tfd_group *ngroup = reinterpret_cast<tfd_group *>(new unsigned char[sizeof(tfd_group) + sizeof(tfd) * (ncap - 1)]); ngroup->next = _fdgroup; _fdgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].next = _fdfree; _fdfree = &ngroup->t[i]; } } void driver::at_fd(int fd, int action, const event<> &trigger) { if (!_fdfree) expand_fds(); if (fd >= FD_SETSIZE) throw tamer::tamer_error("file descriptor too large"); if (trigger) { tfd *t = _fdfree; _fdfree = t->next; t->next = _fd; _fd = t; t->fd = fd; t->action = action; (void) new(static_cast<void *>(&t->e)) event<>(trigger); FD_SET(fd, &_fdset[action]); if (fd >= _nfds) _nfds = fd + 1; if (action <= fdwrite) t->e.at_cancel(make_event(_fdcancelr)); } } void driver::kill_fd(int fd) { assert(fd >= 0); if (fd < _nfds && (FD_ISSET(fd, &_fdset[fdread]) || FD_ISSET(fd, &_fdset[fdwrite]) || FD_ISSET(fd, &_fdset[fdclose]))) { FD_CLR(fd, &_fdset[fdread]); FD_CLR(fd, &_fdset[fdwrite]); FD_CLR(fd, &_fdset[fdclose]); tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->fd == fd) { if (t->action == fdclose) t->e.trigger(); t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } } void driver::at_delay(double delay, const event<> &e) { if (delay <= 0) at_asap(e); else { timeval tv = now; long ldelay = (long) delay; tv.tv_sec += ldelay; tv.tv_usec += (long) ((delay - ldelay) * 1000000 + 0.5); if (tv.tv_usec >= 1000000) { tv.tv_sec++; tv.tv_usec -= 1000000; } at_time(tv, e); } } extern "C" { static void tame_signal_handler(int signal) { sig_any_active = sig_active[signal] = 1; // ensure select wakes up, even if we get a signal in between setting the // timeout and calling select! write(sig_pipe[1], "", 1); // block signal until we trigger the event, giving the unblocked // rendezvous a chance to maybe install another handler sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, signal); sigprocmask(SIG_BLOCK, &sigset, NULL); } } void driver::at_signal(int signal, const event<> &trigger) { assert(signal < NSIGNALS); if (!trigger) return; if (sig_pipe[0] < 0) { pipe(sig_pipe); fcntl(sig_pipe[0], F_SETFL, O_NONBLOCK); fcntl(sig_pipe[0], F_SETFD, FD_CLOEXEC); fcntl(sig_pipe[1], F_SETFD, FD_CLOEXEC); } if (sig_handlers[signal]) sig_handlers[signal] = distribute(sig_handlers[signal], trigger); else { sig_installing = signal; sig_handlers[signal] = trigger; sig_handlers[signal].at_cancel(make_event(sigcancelr)); struct sigaction sa; sa.sa_handler = tame_signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(signal, &sa, 0); sig_installing = -1; } } bool driver::empty() const { if (_nt != 0 || _nfds != 0 || _asap.size() != 0 || sig_any_active || tamerpriv::abstract_rendezvous::unblocked) return false; for (int i = 0; i < NSIGNALS; i++) if (sig_handlers[i]) return false; return true; } void driver::once() { // get rid of initial cancelled timers ttimer *t; while (_nt > 0 && (t = _t[0], !t->trigger)) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->~ttimer(); t->u.next = _tfree; _tfree = t; } // determine timeout struct timeval to, *toptr; if (_asap.size() || (_nt > 0 && !timercmp(&_t[0]->expiry, &now, >)) || sig_any_active) { timerclear(&to); toptr = &to; } else if (_nt == 0) toptr = 0; else { timersub(&_t[0]->expiry, &now, &to); toptr = &to; } // get rid of canceled descriptors, if any if (_fdcancelr.nready()) { while (_fdcancelr.join()) /* nada */; FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); FD_ZERO(&_fdset[fdclose]); _nfds = 0; tfd **pprev = &_fd, *t; while ((t = *pprev)) if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else { FD_SET(t->fd, &_fdset[t->action]); if (t->fd >= _nfds) _nfds = t->fd + 1; pprev = &t->next; } } // select! fd_set fds[2]; fds[fdread] = _fdset[fdread]; fds[fdwrite] = _fdset[fdwrite]; int nfds = _nfds; if (sig_pipe[0] >= 0) { FD_SET(sig_pipe[0], &fds[fdread]); if (sig_pipe[0] > nfds) nfds = sig_pipe[0] + 1; } nfds = select(nfds, &fds[fdread], &fds[fdwrite], 0, toptr); // run signals if (sig_any_active) { sig_any_active = 0; sigset_t sigs_unblock; sigemptyset(&sigs_unblock); // check signals for (int sig = 0; sig < NSIGNALS; sig++) if (sig_active[sig]) { sig_active[sig] = 0; sig_handlers[sig].trigger(); sigaddset(&sigs_unblock, sig); } // run closures activated by signals (plus maybe some others) while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); // now that the signal responders have potentially reinstalled signal // handlers, unblock the signals sigprocmask(SIG_UNBLOCK, &sigs_unblock, 0); // kill crap data written to pipe char crap[64]; while (read(sig_pipe[0], crap, 64) > 0) /* do nothing */; } // run asaps while (event<> *e = _asap.front()) { e->trigger(); _asap.pop_front(); } // run file descriptors if (nfds >= 0) { tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->action <= fdwrite && FD_ISSET(t->fd, &fds[t->action])) { FD_CLR(t->fd, &_fdset[t->action]); t->e.trigger(); t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } // run the timers that worked set_now(); while (_nt > 0 && (t = _t[0], !timercmp(&t->expiry, &now, >))) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->trigger.trigger(); t->~ttimer(); t->u.next = _tfree; _tfree = t; } // run active closures while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); } void driver::loop() { while (1) once(); } } <commit_msg>little nit (trying to discover why performance drops)<commit_after>#include <tamer/driver.hh> #include <tamer/adapter.hh> #include <sys/select.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> namespace tamer { driver driver::main; // using the "self-pipe trick" recommended by select(3) and sfslite. namespace { #define NSIGNALS 32 int sig_pipe[2] = { -1, -1 }; volatile unsigned sig_any_active; volatile unsigned sig_active[NSIGNALS]; volatile int sig_installing = -1; event<> sig_handlers[NSIGNALS]; class sigcancel_rendezvous : public rendezvous<> { public: sigcancel_rendezvous() { } inline void add(tamerpriv::simple_event *e) throw () { _nwaiting++; e->initialize(this, sig_installing); } void complete(uintptr_t rname, bool success) { if ((int) rname != sig_installing && success) { struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(rname, &sa, 0); } rendezvous<>::complete(rname, success); } }; sigcancel_rendezvous sigcancelr; } driver::driver() : _t(0), _nt(0), _fd(0), _nfds(0), _tcap(0), _tgroup(0), _tfree(0), _fdcap(0), _fdgroup(0), _fdfree(0) { expand_timers(); FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); FD_ZERO(&_fdset[fdclose]); set_now(); } driver::~driver() { // destroy all active timers for (int i = 0; i < _nt; i++) _t[i]->~ttimer(); // free timer groups while (_tgroup) { ttimer_group *next = _tgroup->next; delete[] reinterpret_cast<unsigned char *>(_tgroup); _tgroup = next; } delete[] _t; // destroy all active file descriptors while (_fd) { _fd->e.~event(); _fd = _fd->next; } // free file descriptor groups while (_fdgroup) { tfd_group *next = _fdgroup->next; delete[] reinterpret_cast<unsigned char *>(_fdgroup); _fdgroup = next; } } void driver::expand_timers() { int ncap = (_tcap ? _tcap * 2 : 16); ttimer_group *ngroup = reinterpret_cast<ttimer_group *>(new unsigned char[sizeof(ttimer_group) + sizeof(ttimer) * (ncap - 1)]); ngroup->next = _tgroup; _tgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].u.next = _tfree; _tfree = &ngroup->t[i]; } ttimer **t = new ttimer *[ncap]; memcpy(t, _t, sizeof(ttimer *) * _nt); delete[] _t; _t = t; _tcap = ncap; } void driver::timer_reheapify_from(int pos, ttimer *t, bool /*will_delete*/) { int npos; while (pos > 0 && (npos = (pos-1) >> 1, timercmp(&_t[npos]->expiry, &t->expiry, >))) { _t[pos] = _t[npos]; _t[npos]->u.schedpos = pos; pos = npos; } while (1) { ttimer *smallest = t; npos = 2*pos + 1; if (npos < _nt && !timercmp(&_t[npos]->expiry, &smallest->expiry, >)) smallest = _t[npos]; if (npos + 1 < _nt && !timercmp(&_t[npos+1]->expiry, &smallest->expiry, >)) smallest = _t[npos+1], npos++; smallest->u.schedpos = pos; _t[pos] = smallest; if (smallest == t) break; pos = npos; } #if 0 if (_t + 1 < tend || !will_delete) _timer_expiry = tbegin[0]->expiry; else _timer_expiry = Timestamp(); #endif } #if 0 void driver::check_timers() const { fprintf(stderr, "---"); for (int k = 0; k < _nt; k++) fprintf(stderr, " %p/%d.%06d", _t[k], _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); for (int i = 0; i < _nt / 2; i++) for (int j = 2*i + 1; j < 2*i + 3; j++) if (j < _nt && timercmp(&_t[i]->expiry, &_t[j]->expiry, >)) { fprintf(stderr, "***"); for (int k = 0; k < _nt; k++) fprintf(stderr, (k == i || k == j ? " **%d.%06d**" : " %d.%06d"), _t[k]->expiry.tv_sec, _t[k]->expiry.tv_usec); fprintf(stderr, "\n"); assert(0); } } #endif void driver::expand_fds() { int ncap = (_fdcap ? _fdcap * 2 : 16); tfd_group *ngroup = reinterpret_cast<tfd_group *>(new unsigned char[sizeof(tfd_group) + sizeof(tfd) * (ncap - 1)]); ngroup->next = _fdgroup; _fdgroup = ngroup; for (int i = 0; i < ncap; i++) { ngroup->t[i].next = _fdfree; _fdfree = &ngroup->t[i]; } } void driver::at_fd(int fd, int action, const event<> &trigger) { if (!_fdfree) expand_fds(); if (fd >= FD_SETSIZE) throw tamer::tamer_error("file descriptor too large"); if (trigger) { tfd *t = _fdfree; _fdfree = t->next; t->next = _fd; _fd = t; t->fd = fd; t->action = action; (void) new(static_cast<void *>(&t->e)) event<>(trigger); FD_SET(fd, &_fdset[action]); if (fd >= _nfds) _nfds = fd + 1; if (action <= fdwrite) t->e.at_cancel(make_event(_fdcancelr)); } } void driver::kill_fd(int fd) { assert(fd >= 0); if (fd < _nfds && (FD_ISSET(fd, &_fdset[fdread]) || FD_ISSET(fd, &_fdset[fdwrite]) || FD_ISSET(fd, &_fdset[fdclose]))) { FD_CLR(fd, &_fdset[fdread]); FD_CLR(fd, &_fdset[fdwrite]); FD_CLR(fd, &_fdset[fdclose]); tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->fd == fd) { if (t->action == fdclose) t->e.trigger(); t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } } void driver::at_delay(double delay, const event<> &e) { if (delay <= 0) at_asap(e); else { timeval tv = now; long ldelay = (long) delay; tv.tv_sec += ldelay; tv.tv_usec += (long) ((delay - ldelay) * 1000000 + 0.5); if (tv.tv_usec >= 1000000) { tv.tv_sec++; tv.tv_usec -= 1000000; } at_time(tv, e); } } extern "C" { static void tame_signal_handler(int signal) { sig_any_active = sig_active[signal] = 1; // ensure select wakes up, even if we get a signal in between setting the // timeout and calling select! write(sig_pipe[1], "", 1); // block signal until we trigger the event, giving the unblocked // rendezvous a chance to maybe install another handler sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, signal); sigprocmask(SIG_BLOCK, &sigset, NULL); } } void driver::at_signal(int signal, const event<> &trigger) { assert(signal < NSIGNALS); if (!trigger) return; if (sig_pipe[0] < 0) { pipe(sig_pipe); fcntl(sig_pipe[0], F_SETFL, O_NONBLOCK); fcntl(sig_pipe[0], F_SETFD, FD_CLOEXEC); fcntl(sig_pipe[1], F_SETFD, FD_CLOEXEC); } if (sig_handlers[signal]) sig_handlers[signal] = distribute(sig_handlers[signal], trigger); else { sig_installing = signal; sig_handlers[signal] = trigger; sig_handlers[signal].at_cancel(make_event(sigcancelr)); struct sigaction sa; sa.sa_handler = tame_signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; sigaction(signal, &sa, 0); sig_installing = -1; } } bool driver::empty() const { if (_nt != 0 || _nfds != 0 || _asap.size() != 0 || sig_any_active || tamerpriv::abstract_rendezvous::unblocked) return false; for (int i = 0; i < NSIGNALS; i++) if (sig_handlers[i]) return false; return true; } void driver::once() { // get rid of initial cancelled timers ttimer *t; while (_nt > 0 && (t = _t[0], !t->trigger)) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->~ttimer(); t->u.next = _tfree; _tfree = t; } // determine timeout struct timeval to, *toptr; if (_asap.size() || (_nt > 0 && !timercmp(&_t[0]->expiry, &now, >)) || sig_any_active) { timerclear(&to); toptr = &to; } else if (_nt == 0) toptr = 0; else { timersub(&_t[0]->expiry, &now, &to); toptr = &to; } // get rid of canceled descriptors, if any if (_fdcancelr.nready()) { while (_fdcancelr.join()) /* nada */; FD_ZERO(&_fdset[fdread]); FD_ZERO(&_fdset[fdwrite]); FD_ZERO(&_fdset[fdclose]); _nfds = 0; tfd **pprev = &_fd, *t; while ((t = *pprev)) if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else { FD_SET(t->fd, &_fdset[t->action]); if (t->fd >= _nfds) _nfds = t->fd + 1; pprev = &t->next; } } // select! fd_set fds[2]; fds[fdread] = _fdset[fdread]; fds[fdwrite] = _fdset[fdwrite]; int nfds = _nfds; if (sig_pipe[0] >= 0) { FD_SET(sig_pipe[0], &fds[fdread]); if (sig_pipe[0] > nfds) nfds = sig_pipe[0] + 1; } nfds = select(nfds, &fds[fdread], &fds[fdwrite], 0, toptr); // run signals if (sig_any_active) { sig_any_active = 0; sigset_t sigs_unblock; sigemptyset(&sigs_unblock); // check signals for (int sig = 0; sig < NSIGNALS; sig++) if (sig_active[sig]) { sig_active[sig] = 0; sig_handlers[sig].trigger(); sigaddset(&sigs_unblock, sig); } // run closures activated by signals (plus maybe some others) while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); // now that the signal responders have potentially reinstalled signal // handlers, unblock the signals sigprocmask(SIG_UNBLOCK, &sigs_unblock, 0); // kill crap data written to pipe char crap[64]; while (read(sig_pipe[0], crap, 64) > 0) /* do nothing */; } // run asaps while (event<> *e = _asap.front()) { e->trigger(); _asap.pop_front(); } // run file descriptors if (nfds > 0) { tfd **pprev = &_fd, *t; while ((t = *pprev)) if (t->action <= fdwrite && FD_ISSET(t->fd, &fds[t->action])) { FD_CLR(t->fd, &_fdset[t->action]); t->e.trigger(); t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else if (!t->e) { t->e.~event(); *pprev = t->next; t->next = _fdfree; _fdfree = t; } else pprev = &t->next; } // run the timers that worked set_now(); while (_nt > 0 && (t = _t[0], !timercmp(&t->expiry, &now, >))) { timer_reheapify_from(0, _t[_nt - 1], true); _nt--; t->trigger.trigger(); t->~ttimer(); t->u.next = _tfree; _tfree = t; } // run active closures while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked) r->run(); #if 0 { tfd *t = _fd; while (t) { fprintf(stderr, "%d.%d ", t->fd, t->action); t = t->next; } if (_fd) fprintf(stderr, "\n"); } #endif } void driver::loop() { while (1) once(); } } <|endoftext|>
<commit_before>#pragma once //mandala #include "types.hpp" namespace mandala { namespace details { template<typename Scalar, typename Enable = void> struct line2_t; template<typename Scalar> struct line2_t<Scalar, typename std::enable_if<std::is_arithmetic<Scalar>::value>::type> { typedef Scalar scalar_type; typedef line2_t<scalar_type> type; typedef glm::detail::tvec2<scalar_type> value_type; typedef line2_t<float32_t> real_type; value_type start; value_type end; real_type::value_type direction() const { return glm::normalize((real_type::value_type)end - (real_type::value_type)start); } float32_t length() const { return glm::length((real_type::value_type)end - (real_type::value_type)start); } type operator-(const value_type& t) const { type sum; sum.start = start - t; sum.end = end - t; return sum; } type& operator-=(const value_type& t) { *this = *this - t; return *this; } type operator+(const value_type& t) const { type sum; sum.start = start + t; sum.end = end + t; return sum; } type& operator+=(const value_type& t) { *this = *this + t; return *this; } }; template<typename Scalar, typename Real = void, typename Enable = void> struct line3_t; template<typename Scalar> struct line3_t<Scalar, typename std::enable_if<std::is_arithmetic<Scalar>::value>::type> { typedef Scalar scalar_type; typedef line3_t<scalar_type> type; typedef glm::detail::tvec3<scalar_type> value_type; typedef line3_t<float32_t> real_type; value_type start; value_type end; real_type::value_type direction() const { return glm::normalize((real_type::value_type)end - (real_type::value_type)start); } float32_t length() const { return glm::length((real_type::value_type)end - (real_type::value_type)start); } type operator-(const value_type& t) const { type sum; sum.start = start - t; sum.end = end - t; return sum; } type& operator-=(const value_type& t) { *this = *this - t; return *this; } type operator+(const value_type& t) const { type_t sum; sum.start = start + t; sum.end = end + t; return sum; } type& operator+=(const value_type& t) { *this = *this + t; return *this; } }; } typedef details::line2_t<int8_t> line2_i8_t; typedef details::line2_t<int16_t> line2_i16_t; typedef details::line2_t<int32_t> line2_i32_t; typedef details::line2_t<int64_t> line2_i64_t; typedef details::line2_t<float32_t> line2_f32_t; typedef details::line2_t<float64_t> line2_f64_t; typedef line2_f32_t line2_t; typedef details::line3_t<int8_t> line3_i8_t; typedef details::line3_t<int16_t> line3_i16_t; typedef details::line3_t<int32_t> line3_i32_t; typedef details::line3_t<int64_t> line3_i64_t; typedef details::line3_t<float32_t> line3_f32_t; typedef details::line3_t<float64_t> line3_f64_t; typedef line3_f32_t line3_t; } <commit_msg>improvements to some of the base math classes (less verbose code etc)<commit_after>#pragma once //mandala #include "types.hpp" namespace mandala { namespace details { template<typename Scalar, typename Enable = void> struct line2_t; template<typename Scalar> struct line2_t<Scalar, typename std::enable_if<std::is_arithmetic<Scalar>::value>::type> { typedef Scalar scalar_type; typedef line2_t<scalar_type> type; typedef glm::detail::tvec2<scalar_type> value_type; typedef line2_t<float32_t> real_type; value_type start; value_type end; line2_t() = default; line2_t(const value_type& start, const value_type& end) : start(start), end(end) { } real_type::value_type direction() const { return glm::normalize((real_type::value_type)end - (real_type::value_type)start); } float32_t length() const { return glm::length((real_type::value_type)end - (real_type::value_type)start); } type operator-(const value_type& t) const { type sum; sum.start = start - t; sum.end = end - t; return sum; } type& operator-=(const value_type& t) { *this = *this - t; return *this; } type operator+(const value_type& t) const { type sum; sum.start = start + t; sum.end = end + t; return sum; } type& operator+=(const value_type& t) { *this = *this + t; return *this; } }; template<typename Scalar, typename Real = void, typename Enable = void> struct line3_t; template<typename Scalar> struct line3_t<Scalar, typename std::enable_if<std::is_arithmetic<Scalar>::value>::type> { typedef Scalar scalar_type; typedef line3_t<scalar_type> type; typedef glm::detail::tvec3<scalar_type> value_type; typedef line3_t<float32_t> real_type; value_type start; value_type end; line3_t() = default; line3_t(const value_type& start, const value_type& end) : start(start), end(end) { } real_type::value_type direction() const { return glm::normalize((real_type::value_type)end - (real_type::value_type)start); } float32_t length() const { return glm::length((real_type::value_type)end - (real_type::value_type)start); } type operator-(const value_type& t) const { type sum; sum.start = start - t; sum.end = end - t; return sum; } type& operator-=(const value_type& t) { *this = *this - t; return *this; } type operator+(const value_type& t) const { type_t sum; sum.start = start + t; sum.end = end + t; return sum; } type& operator+=(const value_type& t) { *this = *this + t; return *this; } }; } typedef details::line2_t<int8_t> line2_i8_t; typedef details::line2_t<int16_t> line2_i16_t; typedef details::line2_t<int32_t> line2_i32_t; typedef details::line2_t<int64_t> line2_i64_t; typedef details::line2_t<float32_t> line2_f32_t; typedef details::line2_t<float64_t> line2_f64_t; typedef line2_f32_t line2_t; typedef details::line3_t<int8_t> line3_i8_t; typedef details::line3_t<int16_t> line3_i16_t; typedef details::line3_t<int32_t> line3_i32_t; typedef details::line3_t<int64_t> line3_i64_t; typedef details::line3_t<float32_t> line3_f32_t; typedef details::line3_t<float64_t> line3_f64_t; typedef line3_f32_t line3_t; } <|endoftext|>
<commit_before>#pragma once #include "../coding/reader.hpp" #include "../geometry/point2d.hpp" #include "../geometry/rect2d.hpp" #include "../std/string.hpp" #include "../std/noncopyable.hpp" #include "../std/iostream.hpp" class Bookmark { m2::PointD m_org; string m_name; string m_type; ///< Now it stores bookmark color (category style). double m_scale; ///< Viewport scale. -1.0 - is a default value (no scale set). public: Bookmark() {} Bookmark(m2::PointD const & org, string const & name, string const & type) : m_org(org), m_name(name), m_type(type), m_scale(-1.0) { } m2::PointD const & GetOrg() const { return m_org; } string const & GetName() const { return m_name; } /// @return Now its a bookmark color. string const & GetType() const { return m_type; } m2::RectD GetViewport() const { return m2::RectD(m_org, m_org); } double GetScale() const { return m_scale; } void SetScale(double scale) { m_scale = scale; } }; namespace bookmark_impl { class KMLParser; } class BookmarkCategory : private noncopyable { string m_name; vector<Bookmark *> m_bookmarks; bool m_visible; /// Stores file name from which category was loaded string m_file; friend class bookmark_impl::KMLParser; void AddBookmarkImpl(Bookmark const & bm, double scale); public: BookmarkCategory(string const & name) : m_name(name), m_visible(true) {} ~BookmarkCategory(); void ClearBookmarks(); /// @name Theese functions are called from Framework only. //@{ void AddBookmark(Bookmark const & bm, double scale); void ReplaceBookmark(size_t index, Bookmark const & bm, double scale); //@} void SetVisible(bool isVisible) { m_visible = isVisible; } bool IsVisible() const { return m_visible; } void SetName(string const & name) { m_name = name; } string GetName() const { return m_name; } string GetFileName() const { return m_file; } inline size_t GetBookmarksCount() const { return m_bookmarks.size(); } Bookmark const * GetBookmark(size_t index) const; /// @param[in] distance in metres between orgs /// @returns -1 or index of found bookmark int GetBookmark(m2::PointD const org, double const squareDistance) const; void DeleteBookmark(size_t index); /// @name Theese fuctions are public for unit tests only. /// You don't need to call them from client code. //@{ void LoadFromKML(ReaderPtr<Reader> const & reader); void SaveToKML(ostream & s); /// Uses the same file name from which was loaded, or /// creates unique file name on first save and uses it every time. bool SaveToKMLFile(); /// @return 0 in the case of error static BookmarkCategory * CreateFromKMLFile(string const & file); /// Get valid file name from input (remove illegal symbols). static string GetValidFileName(string const & name); /// Get unique file name from path and valid file name. static string GenerateUniqueFileName(const string & path, string const & name); //@} }; /// <category index, bookmark index> typedef pair<int, int> BookmarkAndCategory; inline BookmarkAndCategory MakeEmptyBookmarkAndCategory() { return BookmarkAndCategory(int(-1), int(-1)); } inline bool IsValid(BookmarkAndCategory const & bmc) { return (bmc.first >= 0 && bmc.second >= 0); } <commit_msg>[bookmarks] Changed return values to references<commit_after>#pragma once #include "../coding/reader.hpp" #include "../geometry/point2d.hpp" #include "../geometry/rect2d.hpp" #include "../std/string.hpp" #include "../std/noncopyable.hpp" #include "../std/iostream.hpp" class Bookmark { m2::PointD m_org; string m_name; string m_type; ///< Now it stores bookmark color (category style). double m_scale; ///< Viewport scale. -1.0 - is a default value (no scale set). public: Bookmark() {} Bookmark(m2::PointD const & org, string const & name, string const & type) : m_org(org), m_name(name), m_type(type), m_scale(-1.0) { } m2::PointD const & GetOrg() const { return m_org; } string const & GetName() const { return m_name; } /// @return Now its a bookmark color. string const & GetType() const { return m_type; } m2::RectD GetViewport() const { return m2::RectD(m_org, m_org); } double GetScale() const { return m_scale; } void SetScale(double scale) { m_scale = scale; } }; namespace bookmark_impl { class KMLParser; } class BookmarkCategory : private noncopyable { string m_name; vector<Bookmark *> m_bookmarks; bool m_visible; /// Stores file name from which category was loaded string m_file; friend class bookmark_impl::KMLParser; void AddBookmarkImpl(Bookmark const & bm, double scale); public: BookmarkCategory(string const & name) : m_name(name), m_visible(true) {} ~BookmarkCategory(); void ClearBookmarks(); /// @name Theese functions are called from Framework only. //@{ void AddBookmark(Bookmark const & bm, double scale); void ReplaceBookmark(size_t index, Bookmark const & bm, double scale); //@} void SetVisible(bool isVisible) { m_visible = isVisible; } bool IsVisible() const { return m_visible; } void SetName(string const & name) { m_name = name; } string const & GetName() const { return m_name; } string const & GetFileName() const { return m_file; } inline size_t GetBookmarksCount() const { return m_bookmarks.size(); } Bookmark const * GetBookmark(size_t index) const; /// @param[in] distance in metres between orgs /// @returns -1 or index of found bookmark int GetBookmark(m2::PointD const org, double const squareDistance) const; void DeleteBookmark(size_t index); /// @name Theese fuctions are public for unit tests only. /// You don't need to call them from client code. //@{ void LoadFromKML(ReaderPtr<Reader> const & reader); void SaveToKML(ostream & s); /// Uses the same file name from which was loaded, or /// creates unique file name on first save and uses it every time. bool SaveToKMLFile(); /// @return 0 in the case of error static BookmarkCategory * CreateFromKMLFile(string const & file); /// Get valid file name from input (remove illegal symbols). static string GetValidFileName(string const & name); /// Get unique file name from path and valid file name. static string GenerateUniqueFileName(const string & path, string const & name); //@} }; /// <category index, bookmark index> typedef pair<int, int> BookmarkAndCategory; inline BookmarkAndCategory MakeEmptyBookmarkAndCategory() { return BookmarkAndCategory(int(-1), int(-1)); } inline bool IsValid(BookmarkAndCategory const & bmc) { return (bmc.first >= 0 && bmc.second >= 0); } <|endoftext|>
<commit_before> #include "LoggerTest.h" #include "capu/util/ConsoleLogAppender.h" #include "capu/util/Logger.h" #include "capu/container/String.h" #include "capu/util/LogMessage.h" namespace capu { LoggerTest::LoggerTest() : defaultLogger(appender) , CAPU_CONTEXT(defaultLogger.createContext("capu.Logger")) , LOGGER_CONTEXT(defaultLogger.createContext("capu.OtherContext")) , HELLO_CAPU_CONTEXT(defaultLogger.createContext("Hello.Capu")) { Logger::SetDefaultLogger(defaultLogger); Logger::SetLogLevel(LL_ALL); } LoggerTest::~LoggerTest() { } void LoggerTest::logWithDefaultLogger() { LOG_TRACE(CAPU_CONTEXT , "Trace message " << 5 ); LOG_DEBUG(LOGGER_CONTEXT , "Debug message " << 42.0f ); LOG_INFO(CAPU_CONTEXT , "Info message " << 42 ); LOG_WARN(HELLO_CAPU_CONTEXT , "Warn message " << 42 ); LOG_ERROR(LOGGER_CONTEXT , "Error message " << 42u ); LOG_FATAL(HELLO_CAPU_CONTEXT , "Fatal message " << 42u ); } void LoggerTest::logWithLocalLogger(Logger& logger) { LOG_TRACE_EXT(logger, CAPU_CONTEXT , "Trace message " << 5 ); LOG_DEBUG_EXT(logger, LOGGER_CONTEXT , "Debug message " << 42.0f ); LOG_INFO_EXT (logger, CAPU_CONTEXT , "Info message " << 42 ); LOG_WARN_EXT (logger, HELLO_CAPU_CONTEXT , "Warn message " << 42 ); LOG_ERROR_EXT(logger, LOGGER_CONTEXT , "Error message " << 42u ); LOG_FATAL_EXT(logger, HELLO_CAPU_CONTEXT , "Fatal message " << 42u ); } TEST_F(LoggerTest, LogWithDefaultLogger) { testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogWithLocalLogger) { Logger localLogger(appender); localLogger.setLogLevel(LL_ALL); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithLocalLogger(localLogger); } TEST_F(LoggerTest, LogFatal) { Logger::SetLogLevel(LL_FATAL); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogError) { Logger::SetLogLevel(LL_ERROR); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogWarn) { Logger::SetLogLevel(LL_WARN); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogInfo) { Logger::SetLogLevel(LL_INFO); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogDebug) { Logger::SetLogLevel(LL_DEBUG); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogTrace) { Logger::SetLogLevel(LL_TRACE); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogOnlyOneContext) { { CAPU_CONTEXT.setEnabled(false); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { LOGGER_CONTEXT.setEnabled(false); CAPU_CONTEXT.setEnabled(true); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { CAPU_CONTEXT.setEnabled(false); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { HELLO_CAPU_CONTEXT.setEnabled(false); logWithDefaultLogger(); } } TEST_F(LoggerTest, EnableContextByPattern) { { Logger::SetEnabled(false, "capu"); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { Logger::SetEnabled(true, "capu.Logger"); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { Logger::SetEnabled(false, "Hello.Capu"); Logger::SetLogLevel(LL_INFO); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); logWithDefaultLogger(); } } TEST_F(LoggerTest, AddAppender) { MockLogAppender appender2; Logger::AddAppender(appender2); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, AddAppenderTwice) { Logger::AddAppender(appender); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, RemoveAppender) { MockLogAppender appender2; Logger::AddAppender(appender2); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); Logger::RemoveAppender(appender2); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } } <commit_msg>Add rudimentary test to LogContext set & get userdata<commit_after> #include "LoggerTest.h" #include "capu/util/ConsoleLogAppender.h" #include "capu/util/Logger.h" #include "capu/container/String.h" #include "capu/util/LogMessage.h" namespace capu { LoggerTest::LoggerTest() : defaultLogger(appender) , CAPU_CONTEXT(defaultLogger.createContext("capu.Logger")) , LOGGER_CONTEXT(defaultLogger.createContext("capu.OtherContext")) , HELLO_CAPU_CONTEXT(defaultLogger.createContext("Hello.Capu")) { Logger::SetDefaultLogger(defaultLogger); Logger::SetLogLevel(LL_ALL); } LoggerTest::~LoggerTest() { } void LoggerTest::logWithDefaultLogger() { LOG_TRACE(CAPU_CONTEXT , "Trace message " << 5 ); LOG_DEBUG(LOGGER_CONTEXT , "Debug message " << 42.0f ); LOG_INFO(CAPU_CONTEXT , "Info message " << 42 ); LOG_WARN(HELLO_CAPU_CONTEXT , "Warn message " << 42 ); LOG_ERROR(LOGGER_CONTEXT , "Error message " << 42u ); LOG_FATAL(HELLO_CAPU_CONTEXT , "Fatal message " << 42u ); } void LoggerTest::logWithLocalLogger(Logger& logger) { LOG_TRACE_EXT(logger, CAPU_CONTEXT , "Trace message " << 5 ); LOG_DEBUG_EXT(logger, LOGGER_CONTEXT , "Debug message " << 42.0f ); LOG_INFO_EXT (logger, CAPU_CONTEXT , "Info message " << 42 ); LOG_WARN_EXT (logger, HELLO_CAPU_CONTEXT , "Warn message " << 42 ); LOG_ERROR_EXT(logger, LOGGER_CONTEXT , "Error message " << 42u ); LOG_FATAL_EXT(logger, HELLO_CAPU_CONTEXT , "Fatal message " << 42u ); } TEST_F(LoggerTest, LogWithDefaultLogger) { testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogWithLocalLogger) { Logger localLogger(appender); localLogger.setLogLevel(LL_ALL); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithLocalLogger(localLogger); } TEST_F(LoggerTest, LogFatal) { Logger::SetLogLevel(LL_FATAL); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogError) { Logger::SetLogLevel(LL_ERROR); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogWarn) { Logger::SetLogLevel(LL_WARN); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogInfo) { Logger::SetLogLevel(LL_INFO); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogDebug) { Logger::SetLogLevel(LL_DEBUG); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogTrace) { Logger::SetLogLevel(LL_TRACE); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, LogOnlyOneContext) { { CAPU_CONTEXT.setEnabled(false); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { LOGGER_CONTEXT.setEnabled(false); CAPU_CONTEXT.setEnabled(true); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { CAPU_CONTEXT.setEnabled(false); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { HELLO_CAPU_CONTEXT.setEnabled(false); logWithDefaultLogger(); } } TEST_F(LoggerTest, EnableContextByPattern) { { Logger::SetEnabled(false, "capu"); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { Logger::SetEnabled(true, "capu.Logger"); testing::InSequence seq; EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } { Logger::SetEnabled(false, "Hello.Capu"); Logger::SetLogLevel(LL_INFO); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); logWithDefaultLogger(); } } TEST_F(LoggerTest, AddAppender) { MockLogAppender appender2; Logger::AddAppender(appender2); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, AddAppenderTwice) { Logger::AddAppender(appender); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST_F(LoggerTest, RemoveAppender) { MockLogAppender appender2; Logger::AddAppender(appender2); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender2, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); Logger::RemoveAppender(appender2); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_TRACE))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_DEBUG))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_INFO))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_WARN))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_ERROR))); EXPECT_CALL(appender, log(testing::Property(&LogMessage::getLogLevel, LL_FATAL))); logWithDefaultLogger(); } TEST(LogContextTest, SetAndGetUserData) { LogContext context("LogContext name"); void* someUserData = (void*)0x123; context.setUserData(someUserData); EXPECT_EQ(someUserData, context.getUserData()); } } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Hookflash Inc. / Hookflash 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: 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 <ortc/internal/ortc_ORTC.h> #include <ortc/internal/ortc_Tracing.h> #include <openpeer/services/IHelper.h> #include <openpeer/services/IMessageQueueManager.h> #include <zsLib/Log.h> #include <zsLib/XML.h> namespace ortc { ZS_DECLARE_SUBSYSTEM(ortclib) } namespace ortc { namespace internal { ZS_DECLARE_TYPEDEF_PTR(openpeer::services::IHelper, UseServicesHelper) ZS_DECLARE_TYPEDEF_PTR(openpeer::services::IMessageQueueManager, UseMessageQueueManager) void initSubsystems(); //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark IORTCForInternal #pragma mark //------------------------------------------------------------------------- void IORTCForInternal::overrideQueueDelegate(IMessageQueuePtr queue) { return (ORTC::singleton())->overrideQueueDelegate(queue); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueDelegate() { return (ORTC::singleton())->queueDelegate(); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueORTC() { return (ORTC::singleton())->queueORTC(); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueBlockingMediaStartStopThread() { return (ORTC::singleton())->queueBlockingMediaStartStopThread(); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueCertificateGeneration() { return (ORTC::singleton())->queueCertificateGeneration(); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark ORTC #pragma mark //------------------------------------------------------------------------- ORTC::ORTC(const make_private &) : SharedRecursiveLock(SharedRecursiveLock::create()) { EventWriteOrtcCreate(__func__, mID); initSubsystems(); UseServicesHelper::setup(); zsLib::setup(); ZS_LOG_DETAIL(log("created")) } //------------------------------------------------------------------------- ORTC::~ORTC() { mThisWeak.reset(); ZS_LOG_DETAIL(log("destroyed")) EventWriteOrtcDestroy(__func__, mID); } //------------------------------------------------------------------------- void ORTC::init() { } //------------------------------------------------------------------------- ORTCPtr ORTC::convert(IORTCPtr object) { return ZS_DYNAMIC_PTR_CAST(ORTC, object); } //------------------------------------------------------------------------- ORTCPtr ORTC::create() { ORTCPtr pThis(make_shared<ORTC>(make_private{})); pThis->mThisWeak = pThis; pThis->init(); return pThis; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark ORTC => IORTC #pragma mark //------------------------------------------------------------------------- ORTCPtr ORTC::singleton() { AutoRecursiveLock lock(*UseServicesHelper::getGlobalLock()); static SingletonLazySharedPtr<ORTC> singleton(ORTC::create()); ORTCPtr result = singleton.singleton(); if (!result) { ZS_LOG_WARNING(Detail, slog("singleton gone")) } return result; } //------------------------------------------------------------------------- void ORTC::setup(IMessageQueuePtr defaultDelegateMessageQueue) { AutoRecursiveLock lock(mLock); if (defaultDelegateMessageQueue) { mDelegateQueue = defaultDelegateMessageQueue; } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark Stack => IORTCForInternal #pragma mark //------------------------------------------------------------------------- void ORTC::overrideQueueDelegate(IMessageQueuePtr queue) { AutoRecursiveLock lock(*this); mDelegateQueue = queue; } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueDelegate() const { AutoRecursiveLock lock(*this); if (!mDelegateQueue) { mDelegateQueue = UseMessageQueueManager::getMessageQueueForGUIThread(); } return mDelegateQueue; } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueORTC() const { return UseMessageQueueManager::getThreadPoolQueue(ORTC_QUEUE_MAIN_THREAD_NAME); } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueBlockingMediaStartStopThread() const { AutoRecursiveLock lock(*this); if (!mBlockingMediaStartStopThread) { mBlockingMediaStartStopThread = UseMessageQueueManager::getMessageQueue(ORTC_QUEUE_BLOCKING_MEDIA_STARTUP_THREAD_NAME); } return mBlockingMediaStartStopThread; } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueCertificateGeneration() const { AutoRecursiveLock lock(*this); if (!mCertificateGeneration) { mCertificateGeneration = UseMessageQueueManager::getMessageQueue(ORTC_QUEUE_CERTIFICATE_GENERATION_NAME); } return mCertificateGeneration; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark Stack => (internal) #pragma mark //------------------------------------------------------------------------- Log::Params ORTC::log(const char *message) const { ElementPtr objectEl = Element::create("ortc::ORTC"); UseServicesHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //------------------------------------------------------------------------- Log::Params ORTC::slog(const char *message) { ElementPtr objectEl = Element::create("ortc::ORTC"); return Log::Params(message, objectEl); } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark #pragma mark IORTC #pragma mark //--------------------------------------------------------------------------- void IORTC::setup(IMessageQueuePtr defaultDelegateMessageQueue) { auto singleton = internal::ORTC::singleton(); if (!singleton) return; singleton->setup(defaultDelegateMessageQueue); } } <commit_msg>- missing call to start ETW stats for ortc-lib<commit_after>/* Copyright (c) 2014, Hookflash Inc. / Hookflash 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: 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 <ortc/internal/ortc_ORTC.h> #include <ortc/internal/ortc_Tracing.h> #include <openpeer/services/IHelper.h> #include <openpeer/services/IMessageQueueManager.h> #include <zsLib/Log.h> #include <zsLib/XML.h> namespace ortc { ZS_DECLARE_SUBSYSTEM(ortclib) } namespace ortc { namespace internal { ZS_DECLARE_TYPEDEF_PTR(openpeer::services::IHelper, UseServicesHelper) ZS_DECLARE_TYPEDEF_PTR(openpeer::services::IMessageQueueManager, UseMessageQueueManager) void initSubsystems(); //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark IORTCForInternal #pragma mark //------------------------------------------------------------------------- void IORTCForInternal::overrideQueueDelegate(IMessageQueuePtr queue) { return (ORTC::singleton())->overrideQueueDelegate(queue); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueDelegate() { return (ORTC::singleton())->queueDelegate(); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueORTC() { return (ORTC::singleton())->queueORTC(); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueBlockingMediaStartStopThread() { return (ORTC::singleton())->queueBlockingMediaStartStopThread(); } //------------------------------------------------------------------------- IMessageQueuePtr IORTCForInternal::queueCertificateGeneration() { return (ORTC::singleton())->queueCertificateGeneration(); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark ORTC #pragma mark //------------------------------------------------------------------------- ORTC::ORTC(const make_private &) : SharedRecursiveLock(SharedRecursiveLock::create()) { EventRegisterOrtcLib(); EventWriteOrtcCreate(__func__, mID); initSubsystems(); UseServicesHelper::setup(); zsLib::setup(); ZS_LOG_DETAIL(log("created")) } //------------------------------------------------------------------------- ORTC::~ORTC() { mThisWeak.reset(); ZS_LOG_DETAIL(log("destroyed")) EventWriteOrtcDestroy(__func__, mID); EventUnregisterOrtcLib(); } //------------------------------------------------------------------------- void ORTC::init() { } //------------------------------------------------------------------------- ORTCPtr ORTC::convert(IORTCPtr object) { return ZS_DYNAMIC_PTR_CAST(ORTC, object); } //------------------------------------------------------------------------- ORTCPtr ORTC::create() { ORTCPtr pThis(make_shared<ORTC>(make_private{})); pThis->mThisWeak = pThis; pThis->init(); return pThis; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark ORTC => IORTC #pragma mark //------------------------------------------------------------------------- ORTCPtr ORTC::singleton() { AutoRecursiveLock lock(*UseServicesHelper::getGlobalLock()); static SingletonLazySharedPtr<ORTC> singleton(ORTC::create()); ORTCPtr result = singleton.singleton(); if (!result) { ZS_LOG_WARNING(Detail, slog("singleton gone")) } return result; } //------------------------------------------------------------------------- void ORTC::setup(IMessageQueuePtr defaultDelegateMessageQueue) { AutoRecursiveLock lock(mLock); if (defaultDelegateMessageQueue) { mDelegateQueue = defaultDelegateMessageQueue; } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark Stack => IORTCForInternal #pragma mark //------------------------------------------------------------------------- void ORTC::overrideQueueDelegate(IMessageQueuePtr queue) { AutoRecursiveLock lock(*this); mDelegateQueue = queue; } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueDelegate() const { AutoRecursiveLock lock(*this); if (!mDelegateQueue) { mDelegateQueue = UseMessageQueueManager::getMessageQueueForGUIThread(); } return mDelegateQueue; } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueORTC() const { return UseMessageQueueManager::getThreadPoolQueue(ORTC_QUEUE_MAIN_THREAD_NAME); } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueBlockingMediaStartStopThread() const { AutoRecursiveLock lock(*this); if (!mBlockingMediaStartStopThread) { mBlockingMediaStartStopThread = UseMessageQueueManager::getMessageQueue(ORTC_QUEUE_BLOCKING_MEDIA_STARTUP_THREAD_NAME); } return mBlockingMediaStartStopThread; } //------------------------------------------------------------------------- IMessageQueuePtr ORTC::queueCertificateGeneration() const { AutoRecursiveLock lock(*this); if (!mCertificateGeneration) { mCertificateGeneration = UseMessageQueueManager::getMessageQueue(ORTC_QUEUE_CERTIFICATE_GENERATION_NAME); } return mCertificateGeneration; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark Stack => (internal) #pragma mark //------------------------------------------------------------------------- Log::Params ORTC::log(const char *message) const { ElementPtr objectEl = Element::create("ortc::ORTC"); UseServicesHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //------------------------------------------------------------------------- Log::Params ORTC::slog(const char *message) { ElementPtr objectEl = Element::create("ortc::ORTC"); return Log::Params(message, objectEl); } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark #pragma mark IORTC #pragma mark //--------------------------------------------------------------------------- void IORTC::setup(IMessageQueuePtr defaultDelegateMessageQueue) { auto singleton = internal::ORTC::singleton(); if (!singleton) return; singleton->setup(defaultDelegateMessageQueue); } } <|endoftext|>
<commit_before><commit_msg>improve error reporting in FZ interpreter<commit_after><|endoftext|>
<commit_before>/* * Copyright 2008 Chis Dan Ionut * Copyright 2008 Google Inc. * Copyright 2006 Nintendo Co., Ltd. * * 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 <es.h> #include <es/types.h> #include <es/handle.h> #include <es/base/IStream.h> #include <es/base/IProcess.h> #include <es/naming/IContext.h> #include <es/device/ICursor.h> #define BITS_PER_PIXEL 32 #define BPP (BITS_PER_PIXEL / 8) u8 pixels[1024 * 768 * BPP]; using namespace es; extern ICurrentProcess* System(); void fill(IStream* fb, u8 r, u8 g, u8 b) { for (long offset = 0; offset < 1024 * 768 * BPP; offset += 1024 * 768) { for (long j = offset; j < 1024 * 768; j += BPP) { pixels[j] = b; pixels[j + 1] = g; pixels[j + 2] = r; } fb->write(pixels, 1024 * 768, offset); } } void fill(void* fb, u8 r, u8 g, u8 b) { u32* fbp = static_cast<u32*>(fb); u32 color = (r << 16) | (g << 8) | b; for (int y = 0; y < 768; ++y) { for (int x = 0; x < 1024; ++x) { *fbp++ = color; } } } void pattern(IStream* fb) { long offset; for (offset = 0; offset < 1024 * 256 * BPP; offset += BPP) { pixels[offset] = 255; pixels[offset + 1] = 0; pixels[offset + 2] = 0; } fb->write(pixels, 1024 * 256 * BPP, 0); for (; offset < 1024 * 512 * BPP; offset += BPP) { pixels[offset] = 0; pixels[offset + 1] = 255; pixels[offset + 2] = 0; } fb->write(pixels + 1024 * 256 * BPP, 1024 * 256 * BPP, 1024 * 256 * BPP); for (; offset < 1024 * 768 * BPP; offset += BPP) { pixels[offset] = 0; pixels[offset + 1] = 0; pixels[offset + 2] = 255; } fb->write(pixels + 1024 * 512 * BPP, 1024 * 256 * BPP, 1024 * 512 * BPP); } int main() { Handle<IContext> root = System()->getRoot(); Handle<IStream> mouse(root->lookup("device/mouse")); Handle<ICursor> cursor(root->lookup("device/cursor")); Handle<IStream> framebuffer(root->lookup("device/framebuffer")); Handle<IPageable> pageable(framebuffer); void* mapping = System()->map(0, framebuffer->getSize(), ICurrentProcess::PROT_READ | ICurrentProcess::PROT_WRITE, ICurrentProcess::MAP_SHARED, pageable, 0); fill(mapping, 255, 0, 0); #ifndef __es__ esSleep(10000000); #endif fill(mapping, 0, 255, 0); #ifndef __es__ esSleep(10000000); #endif fill(mapping, 0, 0, 255); #ifndef __es__ esSleep(10000000); #endif fill(mapping, 255, 255, 255); #ifndef __es__ esSleep(10000000); #endif pattern(framebuffer); #ifndef __es__ esSleep(10000000); #endif cursor->show(); for (int y = 0; y < 768; ++y) { cursor->setPosition(512, y); #ifndef __es__ esSleep(10000); #endif } for (int x = 0; x < 1024; ++x) { cursor->setPosition(x, 768 / 2); #ifndef __es__ esSleep(10000); #endif } for (int y = 0; y < 768; ++y) { cursor->setPosition(1023, y); #ifndef __es__ esSleep(10000); #endif } for (int x = 0; x < 1024; ++x) { cursor->setPosition(x, 767); #ifndef __es__ esSleep(10000); #endif } System()->unmap(mapping, framebuffer->getSize()); esReport("done.\n"); // for testing return 0; } <commit_msg>(main) : Clean up.<commit_after>/* * Copyright 2008 Chis Dan Ionut * Copyright 2008 Google Inc. * Copyright 2006 Nintendo Co., Ltd. * * 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 <es.h> #include <es/types.h> #include <es/handle.h> #include <es/base/IStream.h> #include <es/base/IProcess.h> #include <es/naming/IContext.h> #include <es/device/ICursor.h> #define BITS_PER_PIXEL 32 #define BPP (BITS_PER_PIXEL / 8) u8 pixels[1024 * 768 * BPP]; using namespace es; extern ICurrentProcess* System(); void fill(IStream* fb, u8 r, u8 g, u8 b) { for (long offset = 0; offset < 1024 * 768 * BPP; offset += 1024 * 768) { for (long j = offset; j < 1024 * 768; j += BPP) { pixels[j] = b; pixels[j + 1] = g; pixels[j + 2] = r; } fb->write(pixels, 1024 * 768, offset); } } void fill(void* fb, u8 r, u8 g, u8 b) { u32* fbp = static_cast<u32*>(fb); u32 color = (r << 16) | (g << 8) | b; for (int y = 0; y < 768; ++y) { for (int x = 0; x < 1024; ++x) { *fbp++ = color; } } } void pattern(IStream* fb) { long offset; for (offset = 0; offset < 1024 * 256 * BPP; offset += BPP) { pixels[offset] = 255; pixels[offset + 1] = 0; pixels[offset + 2] = 0; } fb->write(pixels, 1024 * 256 * BPP, 0); for (; offset < 1024 * 512 * BPP; offset += BPP) { pixels[offset] = 0; pixels[offset + 1] = 255; pixels[offset + 2] = 0; } fb->write(pixels + 1024 * 256 * BPP, 1024 * 256 * BPP, 1024 * 256 * BPP); for (; offset < 1024 * 768 * BPP; offset += BPP) { pixels[offset] = 0; pixels[offset + 1] = 0; pixels[offset + 2] = 255; } fb->write(pixels + 1024 * 512 * BPP, 1024 * 256 * BPP, 1024 * 512 * BPP); } int main() { Handle<IContext> root = System()->getRoot(); Handle<IStream> mouse(root->lookup("device/mouse")); Handle<ICursor> cursor(root->lookup("device/cursor")); Handle<IStream> framebuffer(root->lookup("device/framebuffer")); void* mapping = System()->map(0, framebuffer->getSize(), ICurrentProcess::PROT_READ | ICurrentProcess::PROT_WRITE, ICurrentProcess::MAP_SHARED, Handle<IPageable>(framebuffer), 0); fill(mapping, 255, 0, 0); #ifndef __es__ esSleep(10000000); #endif fill(mapping, 0, 255, 0); #ifndef __es__ esSleep(10000000); #endif fill(mapping, 0, 0, 255); #ifndef __es__ esSleep(10000000); #endif fill(mapping, 255, 255, 255); #ifndef __es__ esSleep(10000000); #endif pattern(framebuffer); #ifndef __es__ esSleep(10000000); #endif cursor->show(); for (int y = 0; y < 768; ++y) { cursor->setPosition(512, y); #ifndef __es__ esSleep(10000); #endif } for (int x = 0; x < 1024; ++x) { cursor->setPosition(x, 768 / 2); #ifndef __es__ esSleep(10000); #endif } for (int y = 0; y < 768; ++y) { cursor->setPosition(1023, y); #ifndef __es__ esSleep(10000); #endif } for (int x = 0; x < 1024; ++x) { cursor->setPosition(x, 767); #ifndef __es__ esSleep(10000); #endif } System()->unmap(mapping, framebuffer->getSize()); esReport("done.\n"); // for testing return 0; } <|endoftext|>
<commit_before><commit_msg>[tracking] Review fixes.<commit_after><|endoftext|>
<commit_before>#include "server.h" #include <chrono> #include <condition_variable> #include <cstdio> #include <mutex> #include <sstream> #include <thread> #include "mongoose.h" #define SERVER_PORT "8080" std::mutex shutdown_mutex; std::mutex server_mutex; std::condition_variable server_cv; static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c); std::string base64_decode(std::string const& encoded_string); static int lowercase(const char *s); static int mg_strncasecmp(const char *s1, const char *s2, size_t len); static int hello(struct mg_connection* conn) { auto response = std::string{"Hello world!"}; mg_send_status(conn, 200); mg_send_header(conn, "content-type", "text/html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int basicAuth(struct mg_connection* conn) { auto response = std::string{"Hello world!"}; const char* requested_auth; auto auth = std::string{"Basic"}; std::string auth_string; if ((requested_auth = mg_get_header(conn, "Authorization")) == NULL || mg_strncasecmp(requested_auth, auth.data(), auth.length()) != 0) { return MG_FALSE; } auth_string = {requested_auth}; auto basic_token = auth_string.find(' ') + 1; auth_string = auth_string.substr(basic_token, auth_string.length() - basic_token); auth_string = base64_decode(auth_string); auto colon = auth_string.find(':'); auto username = auth_string.substr(0, colon); auto password = auth_string.substr(colon + 1, auth_string.length() - colon - 1); if (username == "user" && password == "password") { return MG_TRUE; } return MG_FALSE; } static int digestAuth(struct mg_connection* conn) { int result = MG_FALSE; { FILE *fp; if ((fp = fopen("digest.txt", "w")) != NULL) { fprintf(fp, "user:mydomain.com:0cf722ef3dd136b48da83758c5d855f8"); fclose(fp); } } { FILE *fp; if ((fp = fopen("digest.txt", "r")) != NULL) { result = mg_authorize_digest(conn, fp); fclose(fp); } } return result; } static int basicJson(struct mg_connection* conn) { auto response = std::string{"[\n" " {\n" " \"first_key\": \"first_value\",\n" " \"second_key\": \"second_value\"\n" " }\n" "]"}; mg_send_status(conn, 200); auto raw_header = mg_get_header(conn, "Content-type"); std::string header; if (raw_header != NULL) { header = raw_header; } if (!header.empty() && header == "application/json") { mg_send_header(conn, "content-type", "application/json"); } else { mg_send_header(conn, "content-type", "application/octet-stream"); } mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int headerReflect(struct mg_connection* conn) { auto response = std::string{"Header reflect"}; mg_send_status(conn, 200); mg_send_header(conn, "content-type", "text/html"); auto num_headers = conn->num_headers; auto headers = conn->http_headers; for (int i = 0; i < num_headers; ++i) { auto name = headers[i].name; if (std::string{"User-Agent"} != name && std::string{"Host"} != name && std::string{"Accept"} != name) { mg_send_header(conn, name, headers[i].value); } } mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int temporaryRedirect(struct mg_connection* conn) { auto response = std::string{"Found"}; mg_send_status(conn, 302); mg_send_header(conn, "Location", "hello.html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int permanentRedirect(struct mg_connection* conn) { auto response = std::string{"Moved Permanently"}; mg_send_status(conn, 301); mg_send_header(conn, "Location", "hello.html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int twoRedirects(struct mg_connection* conn) { auto response = std::string{"Moved Permanently"}; mg_send_status(conn, 301); mg_send_header(conn, "Location", "permanent_redirect.html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int urlPost(struct mg_connection* conn) { mg_send_status(conn, 201); mg_send_header(conn, "content-type", "application/json"); char x[100]; char y[100]; mg_get_var(conn, "x", x, sizeof(x)); mg_get_var(conn, "y", y, sizeof(y)); auto x_string = std::string{x}; auto y_string = std::string{y}; if (y_string.empty()) { auto response = std::string{"{\n" " \"x\": " + x_string + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } else { std::ostringstream s; s << (atoi(x) + atoi(y)); auto response = std::string{"{\n" " \"x\": " + x_string + ",\n" " \"y\": " + y_string + ",\n" " \"sum\": " + s.str() + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } return MG_TRUE; } static int formPost(struct mg_connection* conn) { auto content = conn->content; auto content_len = conn->content_len; std::map<std::string, std::string> forms; while (true) { char* data = new char[10000]; int data_len; char name[100]; char filename[100]; content += mg_parse_multipart(content, content_len, name, sizeof(name), filename, sizeof(filename), (const char**) &data, &data_len); if (strlen(data) == 0) { delete[] data; break; } forms[name] = std::string{data, (unsigned long) data_len}; } mg_send_status(conn, 201); mg_send_header(conn, "content-type", "application/json"); if (forms.find("y") == forms.end()) { auto response = std::string{"{\n" " \"x\": " + forms["x"] + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } else { std::ostringstream s; s << (atoi(forms["x"].data()) + atoi(forms["y"].data())); auto response = std::string{"{\n" " \"x\": " + forms["x"] + ",\n" " \"y\": " + forms["y"] + ",\n" " \"sum\": " + s.str() + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } return MG_TRUE; } static int evHandler(struct mg_connection* conn, enum mg_event ev) { switch (ev) { case MG_AUTH: if (Url{conn->uri} == "/basic_auth.html") { return basicAuth(conn); } else if (Url{conn->uri} == "/digest_auth.html") { return digestAuth(conn); } return MG_TRUE; case MG_REQUEST: if (Url{conn->uri} == "/hello.html") { return hello(conn); } else if (Url{conn->uri} == "/basic_auth.html") { return headerReflect(conn); } else if (Url{conn->uri} == "/digest_auth.html") { return headerReflect(conn); } else if (Url{conn->uri} == "/basic.json") { return basicJson(conn); } else if (Url{conn->uri} == "/header_reflect.html") { return headerReflect(conn); } else if (Url{conn->uri} == "/temporary_redirect.html") { return temporaryRedirect(conn); } else if (Url{conn->uri} == "/permanent_redirect.html") { return permanentRedirect(conn); } else if (Url{conn->uri} == "/two_redirects.html") { return twoRedirects(conn); } else if (Url{conn->uri} == "/url_post.html") { return urlPost(conn); } else if (Url{conn->uri} == "/form_post.html") { return formPost(conn); } return MG_FALSE; default: return MG_FALSE; } } void runServer(struct mg_server* server) { { std::lock_guard<std::mutex> server_lock(server_mutex); mg_set_option(server, "listening_port", SERVER_PORT); server_cv.notify_one(); } do { mg_poll_server(server, 1000); } while (!shutdown_mutex.try_lock()); std::lock_guard<std::mutex> server_lock(server_mutex); mg_destroy_server(&server); server_cv.notify_one(); } void Server::SetUp() { shutdown_mutex.lock(); struct mg_server* server; server = mg_create_server(NULL, evHandler); std::unique_lock<std::mutex> server_lock(server_mutex); std::thread(runServer, server).detach(); server_cv.wait(server_lock); } void Server::TearDown() { std::unique_lock<std::mutex> server_lock(server_mutex); shutdown_mutex.unlock(); server_cv.wait(server_lock); } Url Server::GetBaseUrl() { return Url{"http://127.0.0.1:"}.append(SERVER_PORT); } static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) { char_array_4[i] = base64_chars.find(char_array_4[i]); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) { ret += char_array_3[i]; } i = 0; } } if (i) { for (j = i; j <4; j++) { char_array_4[j] = 0; } for (j = 0; j <4; j++) { char_array_4[j] = base64_chars.find(char_array_4[j]); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) { ret += char_array_3[j]; } } return ret; } static int lowercase(const char *s) { return tolower(* (const unsigned char *) s); } static int mg_strncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) { do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); } return diff; } <commit_msg>Add cookie response to server class References #2<commit_after>#include "server.h" #include <chrono> #include <condition_variable> #include <cstdio> #include <mutex> #include <sstream> #include <thread> #include "mongoose.h" #include <time.h> #define SERVER_PORT "8080" std::mutex shutdown_mutex; std::mutex server_mutex; std::condition_variable server_cv; static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c); std::string base64_decode(std::string const& encoded_string); static int lowercase(const char *s); static int mg_strncasecmp(const char *s1, const char *s2, size_t len); static int hello(struct mg_connection* conn) { auto response = std::string{"Hello world!"}; mg_send_status(conn, 200); mg_send_header(conn, "content-type", "text/html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int basicCookies(struct mg_connection* conn) { auto response = std::string{"Hello world!"}; mg_send_status(conn, 200); mg_send_header(conn, "content-type", "text/html"); time_t t = time(NULL) + 5; // Valid for 1 hour char expire[100], expire_epoch[100]; snprintf(expire_epoch, sizeof(expire_epoch), "%lu", (unsigned long) t); strftime(expire, sizeof(expire), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t)); std::string cookie{"cookie=chocolate; expires=\"" + std::string{expire} + "\"; http-only;"}; std::string cookie2{"icecream=vanilla; expires=\"" + std::string{expire} + "\"; http-only;"}; mg_send_header(conn, "Set-Cookie", cookie.data()); mg_send_header(conn, "Set-Cookie", cookie2.data()); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int basicAuth(struct mg_connection* conn) { auto response = std::string{"Hello world!"}; const char* requested_auth; auto auth = std::string{"Basic"}; std::string auth_string; if ((requested_auth = mg_get_header(conn, "Authorization")) == NULL || mg_strncasecmp(requested_auth, auth.data(), auth.length()) != 0) { return MG_FALSE; } auth_string = {requested_auth}; auto basic_token = auth_string.find(' ') + 1; auth_string = auth_string.substr(basic_token, auth_string.length() - basic_token); auth_string = base64_decode(auth_string); auto colon = auth_string.find(':'); auto username = auth_string.substr(0, colon); auto password = auth_string.substr(colon + 1, auth_string.length() - colon - 1); if (username == "user" && password == "password") { return MG_TRUE; } return MG_FALSE; } static int digestAuth(struct mg_connection* conn) { int result = MG_FALSE; { FILE *fp; if ((fp = fopen("digest.txt", "w")) != NULL) { fprintf(fp, "user:mydomain.com:0cf722ef3dd136b48da83758c5d855f8"); fclose(fp); } } { FILE *fp; if ((fp = fopen("digest.txt", "r")) != NULL) { result = mg_authorize_digest(conn, fp); fclose(fp); } } return result; } static int basicJson(struct mg_connection* conn) { auto response = std::string{"[\n" " {\n" " \"first_key\": \"first_value\",\n" " \"second_key\": \"second_value\"\n" " }\n" "]"}; mg_send_status(conn, 200); auto raw_header = mg_get_header(conn, "Content-type"); std::string header; if (raw_header != NULL) { header = raw_header; } if (!header.empty() && header == "application/json") { mg_send_header(conn, "content-type", "application/json"); } else { mg_send_header(conn, "content-type", "application/octet-stream"); } mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int headerReflect(struct mg_connection* conn) { auto response = std::string{"Header reflect"}; mg_send_status(conn, 200); mg_send_header(conn, "content-type", "text/html"); auto num_headers = conn->num_headers; auto headers = conn->http_headers; for (int i = 0; i < num_headers; ++i) { auto name = headers[i].name; if (std::string{"User-Agent"} != name && std::string{"Host"} != name && std::string{"Accept"} != name) { mg_send_header(conn, name, headers[i].value); } } mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int temporaryRedirect(struct mg_connection* conn) { auto response = std::string{"Found"}; mg_send_status(conn, 302); mg_send_header(conn, "Location", "hello.html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int permanentRedirect(struct mg_connection* conn) { auto response = std::string{"Moved Permanently"}; mg_send_status(conn, 301); mg_send_header(conn, "Location", "hello.html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int twoRedirects(struct mg_connection* conn) { auto response = std::string{"Moved Permanently"}; mg_send_status(conn, 301); mg_send_header(conn, "Location", "permanent_redirect.html"); mg_send_data(conn, response.data(), response.length()); return MG_TRUE; } static int urlPost(struct mg_connection* conn) { mg_send_status(conn, 201); mg_send_header(conn, "content-type", "application/json"); char x[100]; char y[100]; mg_get_var(conn, "x", x, sizeof(x)); mg_get_var(conn, "y", y, sizeof(y)); auto x_string = std::string{x}; auto y_string = std::string{y}; if (y_string.empty()) { auto response = std::string{"{\n" " \"x\": " + x_string + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } else { std::ostringstream s; s << (atoi(x) + atoi(y)); auto response = std::string{"{\n" " \"x\": " + x_string + ",\n" " \"y\": " + y_string + ",\n" " \"sum\": " + s.str() + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } return MG_TRUE; } static int formPost(struct mg_connection* conn) { auto content = conn->content; auto content_len = conn->content_len; std::map<std::string, std::string> forms; while (true) { char* data = new char[10000]; int data_len; char name[100]; char filename[100]; content += mg_parse_multipart(content, content_len, name, sizeof(name), filename, sizeof(filename), (const char**) &data, &data_len); if (strlen(data) == 0) { delete[] data; break; } forms[name] = std::string{data, (unsigned long) data_len}; } mg_send_status(conn, 201); mg_send_header(conn, "content-type", "application/json"); if (forms.find("y") == forms.end()) { auto response = std::string{"{\n" " \"x\": " + forms["x"] + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } else { std::ostringstream s; s << (atoi(forms["x"].data()) + atoi(forms["y"].data())); auto response = std::string{"{\n" " \"x\": " + forms["x"] + ",\n" " \"y\": " + forms["y"] + ",\n" " \"sum\": " + s.str() + "\n" "}"}; mg_send_data(conn, response.data(), response.length()); } return MG_TRUE; } static int evHandler(struct mg_connection* conn, enum mg_event ev) { switch (ev) { case MG_AUTH: if (Url{conn->uri} == "/basic_auth.html") { return basicAuth(conn); } else if (Url{conn->uri} == "/digest_auth.html") { return digestAuth(conn); } return MG_TRUE; case MG_REQUEST: if (Url{conn->uri} == "/hello.html") { return hello(conn); } else if (Url{conn->uri} == "/basic_cookies.html") { return basicCookies(conn); } else if (Url{conn->uri} == "/basic_auth.html") { return headerReflect(conn); } else if (Url{conn->uri} == "/digest_auth.html") { return headerReflect(conn); } else if (Url{conn->uri} == "/basic.json") { return basicJson(conn); } else if (Url{conn->uri} == "/header_reflect.html") { return headerReflect(conn); } else if (Url{conn->uri} == "/temporary_redirect.html") { return temporaryRedirect(conn); } else if (Url{conn->uri} == "/permanent_redirect.html") { return permanentRedirect(conn); } else if (Url{conn->uri} == "/two_redirects.html") { return twoRedirects(conn); } else if (Url{conn->uri} == "/url_post.html") { return urlPost(conn); } else if (Url{conn->uri} == "/form_post.html") { return formPost(conn); } return MG_FALSE; default: return MG_FALSE; } } void runServer(struct mg_server* server) { { std::lock_guard<std::mutex> server_lock(server_mutex); mg_set_option(server, "listening_port", SERVER_PORT); server_cv.notify_one(); } do { mg_poll_server(server, 1000); } while (!shutdown_mutex.try_lock()); std::lock_guard<std::mutex> server_lock(server_mutex); mg_destroy_server(&server); server_cv.notify_one(); } void Server::SetUp() { shutdown_mutex.lock(); struct mg_server* server; server = mg_create_server(NULL, evHandler); std::unique_lock<std::mutex> server_lock(server_mutex); std::thread(runServer, server).detach(); server_cv.wait(server_lock); } void Server::TearDown() { std::unique_lock<std::mutex> server_lock(server_mutex); shutdown_mutex.unlock(); server_cv.wait(server_lock); } Url Server::GetBaseUrl() { return Url{"http://127.0.0.1:"}.append(SERVER_PORT); } static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) { char_array_4[i] = base64_chars.find(char_array_4[i]); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) { ret += char_array_3[i]; } i = 0; } } if (i) { for (j = i; j <4; j++) { char_array_4[j] = 0; } for (j = 0; j <4; j++) { char_array_4[j] = base64_chars.find(char_array_4[j]); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) { ret += char_array_3[j]; } } return ret; } static int lowercase(const char *s) { return tolower(* (const unsigned char *) s); } static int mg_strncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) { do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); } return diff; } <|endoftext|>
<commit_before>#ifndef __AMEDIA_FILE_HPP__ # define __AMEDIA_FILE_HPP__ #include <functional> #include <Utils/File.hpp> #include <cereal/cereal.hpp> #include <cereal/types/map.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/string.hpp> #include <cereal/types/complex.hpp> #include <cereal/types/base_class.hpp> #include <cereal/types/memory.hpp> #include <cereal/archives/binary.hpp> #include <cereal/archives/json.hpp> #include <cereal/archives/xml.hpp> #include <cereal/archives/portable_binary.hpp> #include <MediaFiles/AssetsManager.hpp> struct AMediaFile { public: File path; std::string name; static AssetsManager *_manager; protected: std::size_t _childs; enum MEDIA_TYPE { UNKNOWN = 0 , OBJ = 1 , TEXTURE = 2 , MATERIAL = 3 , CUBEMAP = 4 , COLLISION_SHAPE_STATIC = 5 }; MEDIA_TYPE _type; public: AMediaFile() : _childs(0) , _type(UNKNOWN) { } virtual ~AMediaFile(){} AMediaFile(const AMediaFile &o) : _childs(0) { _type = o._type; name = o.name; name += "_copy"; auto tmpPath = o.path.getFolder() + o.path.getShortFileName(); tmpPath += "_copy.cpd"; path = File(tmpPath); } AMediaFile &operator=(const AMediaFile &o) { if (&o != this) { _type = o._type; name = o.name; name += "_copy"; } return *this; } template <typename Archive> void serialize(std::ofstream &s) { Archive ar(s); ar(_type); _serialize(ar); } template <typename Archive> static std::shared_ptr<AMediaFile> loadFromFile(const File &file) { if (file.getExtension() == "bullet") return loadBulletFile(file); assert(file.exists() == true && "File does not exist."); std::shared_ptr<AMediaFile> res{ nullptr }; res = _manager->get(file.getShortFileName()); if (res != nullptr) return res; MEDIA_TYPE serializedFileType = UNKNOWN; std::ifstream ifs(file.getFullName(), std::ios::binary); Archive ar(ifs); ar(serializedFileType); switch (serializedFileType) { case OBJ: res = std::make_shared<ObjFile>(); ar(static_cast<ObjFile&>(*res.get())); break; case MATERIAL: res = std::make_shared<MaterialFile>(); ar(static_cast<MaterialFile&>(*res.get())); break; case TEXTURE: res = std::make_shared<TextureFile>(); ar(static_cast<TextureFile&>(*res.get())); break; case CUBEMAP: res = std::make_shared<CubeMapFile>(); ar(static_cast<CubeMapFile&>(*res.get())); break; default: break; } assert(res != nullptr && "Unknown MediaFile type."); assert(_manager != nullptr && "Media Manager is not set."); res->path = file.getFullName(); res->name = file.getShortFileName(); _manager->add(res); return res; } static std::shared_ptr<AMediaFile> loadBulletFile(const File &f); static void loadFromList(const File &file); static std::shared_ptr<AMediaFile> get(const std::string &name); template <class T> static std::shared_ptr<T> get(const std::string &name) { return std::static_pointer_cast<T>(_manager->get(name)); } template <class T> static std::shared_ptr<T> create(const std::string &name = "", std::shared_ptr<AMediaFile> copyFrom = nullptr) { if (!name.empty()) { auto o = std::static_pointer_cast<T>(_manager->get(name)); if (o != nullptr) return o; } std::shared_ptr<T> n{ nullptr }; if (copyFrom != nullptr) n = std::make_shared<T>(*std::static_pointer_cast<const T>(copyFrom).get()); else n = std::make_shared<T>(); if (!name.empty()) n->name = name; _manager->add(n); return n; } static void saveToFile(const std::string &media, const std::string &path) { auto &e = get<AMediaFile>(media); assert(e != nullptr && "Media does not exists"); std::string filePath = path + e->name + ".cpd"; std::ofstream ofs(filePath, std::ios::binary); assert(ofs.is_open() && "Cannot open file for save"); e->path = File(path + e->name + ".cpd"); e->serialize<cereal::BinaryOutputArchive>(ofs); } static void setManager(AssetsManager *manager) { _manager = manager; } inline std::size_t getChilds() const { return _childs; } inline void incrementChilds() { ++_childs; } inline std::size_t getType() const { return _type; } protected: virtual void _serialize(cereal::JSONOutputArchive &ar) = 0; virtual void _serialize(cereal::BinaryOutputArchive &ar) = 0; virtual void _serialize(cereal::XMLOutputArchive &ar) = 0; virtual void _serialize(cereal::PortableBinaryOutputArchive &ar) = 0; }; #endif //__AMEDIA_FILE_HPP__<commit_msg>Dirty hack opened in AMedia serialize that can save time for the moment on bullet serialization<commit_after>#ifndef __AMEDIA_FILE_HPP__ # define __AMEDIA_FILE_HPP__ #include <functional> #include <Utils/File.hpp> #include <cereal/cereal.hpp> #include <cereal/types/map.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/string.hpp> #include <cereal/types/complex.hpp> #include <cereal/types/base_class.hpp> #include <cereal/types/memory.hpp> #include <cereal/archives/binary.hpp> #include <cereal/archives/json.hpp> #include <cereal/archives/xml.hpp> #include <cereal/archives/portable_binary.hpp> #include <MediaFiles/AssetsManager.hpp> struct AMediaFile { public: File path; std::string name; static AssetsManager *_manager; protected: std::size_t _childs; enum MEDIA_TYPE { UNKNOWN = 0 , OBJ = 1 , TEXTURE = 2 , MATERIAL = 3 , CUBEMAP = 4 , COLLISION_SHAPE_STATIC = 5 }; MEDIA_TYPE _type; public: AMediaFile() : _childs(0) , _type(UNKNOWN) { } virtual ~AMediaFile(){} AMediaFile(const AMediaFile &o) : _childs(0) { _type = o._type; name = o.name; name += "_copy"; auto tmpPath = o.path.getFolder() + o.path.getShortFileName(); tmpPath += "_copy.cpd"; path = File(tmpPath); } AMediaFile &operator=(const AMediaFile &o) { if (&o != this) { _type = o._type; name = o.name; name += "_copy"; } return *this; } template <typename Archive> void serialize(std::ofstream &s) { if (_type == COLLISION_SHAPE_STATIC) { std::cout << "lol" << std::endl; } else { Archive ar(s); ar(_type); _serialize(ar); } } template <typename Archive> static std::shared_ptr<AMediaFile> loadFromFile(const File &file) { if (file.getExtension() == "bullet") return loadBulletFile(file); assert(file.exists() == true && "File does not exist."); std::shared_ptr<AMediaFile> res{ nullptr }; res = _manager->get(file.getShortFileName()); if (res != nullptr) return res; MEDIA_TYPE serializedFileType = UNKNOWN; std::ifstream ifs(file.getFullName(), std::ios::binary); Archive ar(ifs); ar(serializedFileType); switch (serializedFileType) { case OBJ: res = std::make_shared<ObjFile>(); ar(static_cast<ObjFile&>(*res.get())); break; case MATERIAL: res = std::make_shared<MaterialFile>(); ar(static_cast<MaterialFile&>(*res.get())); break; case TEXTURE: res = std::make_shared<TextureFile>(); ar(static_cast<TextureFile&>(*res.get())); break; case CUBEMAP: res = std::make_shared<CubeMapFile>(); ar(static_cast<CubeMapFile&>(*res.get())); break; default: break; } assert(res != nullptr && "Unknown MediaFile type."); assert(_manager != nullptr && "Media Manager is not set."); res->path = file.getFullName(); res->name = file.getShortFileName(); _manager->add(res); return res; } static std::shared_ptr<AMediaFile> loadBulletFile(const File &f); static void loadFromList(const File &file); static std::shared_ptr<AMediaFile> get(const std::string &name); template <class T> static std::shared_ptr<T> get(const std::string &name) { return std::static_pointer_cast<T>(_manager->get(name)); } template <class T> static std::shared_ptr<T> create(const std::string &name = "", std::shared_ptr<AMediaFile> copyFrom = nullptr) { if (!name.empty()) { auto o = std::static_pointer_cast<T>(_manager->get(name)); if (o != nullptr) return o; } std::shared_ptr<T> n{ nullptr }; if (copyFrom != nullptr) n = std::make_shared<T>(*std::static_pointer_cast<const T>(copyFrom).get()); else n = std::make_shared<T>(); if (!name.empty()) n->name = name; _manager->add(n); return n; } static void saveToFile(const std::string &media, const std::string &path) { auto &e = get<AMediaFile>(media); assert(e != nullptr && "Media does not exists"); std::string filePath = path + e->name + ".cpd"; std::ofstream ofs(filePath, std::ios::binary); assert(ofs.is_open() && "Cannot open file for save"); e->path = File(path + e->name + ".cpd"); e->serialize<cereal::BinaryOutputArchive>(ofs); } static void setManager(AssetsManager *manager) { _manager = manager; } inline std::size_t getChilds() const { return _childs; } inline void incrementChilds() { ++_childs; } inline std::size_t getType() const { return _type; } protected: virtual void _serialize(cereal::JSONOutputArchive &ar) = 0; virtual void _serialize(cereal::BinaryOutputArchive &ar) = 0; virtual void _serialize(cereal::XMLOutputArchive &ar) = 0; virtual void _serialize(cereal::PortableBinaryOutputArchive &ar) = 0; }; #endif //__AMEDIA_FILE_HPP__<|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <[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. */ #include <Corrade/TestSuite/Tester.h> #include "Magnum/Math/TypeTraits.h" #include "Magnum/Math/Constants.h" namespace Magnum { namespace Math { namespace Test { struct TypeTraitsTest: Corrade::TestSuite::Tester { explicit TypeTraitsTest(); void name(); template<class T> void equalsIntegral(); template<class T> void equalsFloatingPoint0(); template<class T> void equalsFloatingPoint1(); template<class T> void equalsFloatingPointLarge(); template<class T> void equalsFloatingPointInfinity(); template<class T> void equalsFloatingPointNaN(); template<class T> void equalsZeroIntegral(); template<class T> void equalsZeroFloatingPoint(); template<class T> void equalsZeroFloatingPointSmall(); template<class T> void equalsZeroFloatingPointLarge(); }; namespace { enum: std::size_t { EqualsZeroDataCount = 3 }; struct { const char* name; Float a, aStep; Double b, bStep; long double c, cStep; Float get(Float) const { return a; } Float getStep(Float) const { return aStep; } Double get(Double) const { return b; } Double getStep(Double) const { return bStep; } long double get(long double) const { return c; } long double getStep(long double) const { return cStep; } } EqualsZeroData[EqualsZeroDataCount] = { {"", -3.141592653589793f, 5.0e-5f, -3.141592653589793, 5.0e-14, -3.141592653589793l, 5.0e-17l}, {"small", 1.0e-6f, 5.0e-6f, -1.0e-15, 5.0e-15, 1.0e-18l, 5.0e-18l}, {"large", 12345.0f, 0.2f, 12345678901234.0, 0.2, -12345678901234567.0l, 0.2l}, }; } TypeTraitsTest::TypeTraitsTest() { addTests<TypeTraitsTest>({ &TypeTraitsTest::name, &TypeTraitsTest::equalsIntegral<UnsignedByte>, &TypeTraitsTest::equalsIntegral<Byte>, &TypeTraitsTest::equalsIntegral<UnsignedShort>, &TypeTraitsTest::equalsIntegral<Short>, &TypeTraitsTest::equalsIntegral<UnsignedInt>, &TypeTraitsTest::equalsIntegral<Int>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsIntegral<UnsignedLong>, &TypeTraitsTest::equalsIntegral<Long>, #endif &TypeTraitsTest::equalsFloatingPoint0<Float>, &TypeTraitsTest::equalsFloatingPoint0<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsFloatingPoint0<long double>, #endif &TypeTraitsTest::equalsFloatingPoint1<Float>, &TypeTraitsTest::equalsFloatingPoint1<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsFloatingPoint1<long double>, #endif &TypeTraitsTest::equalsFloatingPointLarge<Float>, &TypeTraitsTest::equalsFloatingPointLarge<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsFloatingPointLarge<long double>, #endif &TypeTraitsTest::equalsFloatingPointInfinity<Float>, &TypeTraitsTest::equalsFloatingPointInfinity<Double>, &TypeTraitsTest::equalsFloatingPointNaN<Float>, &TypeTraitsTest::equalsFloatingPointNaN<Double>, &TypeTraitsTest::equalsZeroIntegral<UnsignedByte>, &TypeTraitsTest::equalsZeroIntegral<Byte>, &TypeTraitsTest::equalsZeroIntegral<UnsignedShort>, &TypeTraitsTest::equalsZeroIntegral<Short>, &TypeTraitsTest::equalsZeroIntegral<UnsignedInt>, &TypeTraitsTest::equalsZeroIntegral<Int>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsZeroIntegral<UnsignedLong>, &TypeTraitsTest::equalsZeroIntegral<Long>, #endif }); addInstancedTests<TypeTraitsTest>({ &TypeTraitsTest::equalsZeroFloatingPoint<Float>, &TypeTraitsTest::equalsZeroFloatingPoint<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsZeroFloatingPoint<long double> #endif }, EqualsZeroDataCount); } void TypeTraitsTest::name() { CORRADE_COMPARE(TypeTraits<UnsignedShort>::name(), "UnsignedShort"); CORRADE_COMPARE(TypeTraits<Float>::name(), "Float"); } template<class T> void TypeTraitsTest::equalsIntegral() { setTestCaseName(std::string{"equalsIntegral<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(1, 1)); CORRADE_VERIFY(!TypeTraits<T>::equals(1, -1)); CORRADE_VERIFY(!TypeTraits<T>::equals(1, 1+TypeTraits<T>::epsilon())); } template<class T> void TypeTraitsTest::equalsFloatingPoint0() { setTestCaseName(std::string{"equalsFloatingPoint0<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(T(0)+TypeTraits<T>::epsilon()/T(2), T(0))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(0)+TypeTraits<T>::epsilon()*T(2), T(0))); } template<class T> void TypeTraitsTest::equalsFloatingPoint1() { setTestCaseName(std::string{"equalsFloatingPoint1<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(T(1)+TypeTraits<T>::epsilon()/T(2), T(1))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(1)+TypeTraits<T>::epsilon()*T(3), T(1))); } template<class T> void TypeTraitsTest::equalsFloatingPointLarge() { setTestCaseName(std::string{"equalsFloatingPointLarge<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(T(25)+TypeTraits<T>::epsilon()*T(2), T(25))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(25)+TypeTraits<T>::epsilon()*T(75), T(25))); } template<class T> void TypeTraitsTest::equalsFloatingPointInfinity() { setTestCaseName(std::string{"equalsFloatingPointInfinity<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(Constants<T>::inf(), Constants<T>::inf())); } template<class T> void TypeTraitsTest::equalsFloatingPointNaN() { setTestCaseName(std::string{"equalsFloatingPointNaN<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(!TypeTraits<T>::equals(Constants<T>::nan(), Constants<T>::nan())); } namespace { /* Argh! Why there is no standard std::abs() for unsigned types? */ template<class T, class U = typename std::enable_if<std::is_unsigned<T>::value>::type> T abs(T value) { return value; } template<class T, class U = T, class V = typename std::enable_if<!std::is_unsigned<T>::value>::type> T abs(T value) { return std::abs(value); } } template<class T> void TypeTraitsTest::equalsZeroIntegral() { setTestCaseName(std::string{"equalsZeroIntegral<"} + TypeTraits<T>::name() + ">"); const T a(-123); const T b(-123); const T magnitude = std::max(abs(a), abs(b)); CORRADE_VERIFY(TypeTraits<T>::equals(a, b)); CORRADE_VERIFY(TypeTraits<T>::equalsZero(a - b, magnitude)); CORRADE_VERIFY(!TypeTraits<T>::equalsZero(a - b + TypeTraits<T>::epsilon(), magnitude)); } template<class T> void TypeTraitsTest::equalsZeroFloatingPoint() { setTestCaseName(std::string{"equalsZeroFloatingPoint<"} + TypeTraits<T>::name() + ">"); setTestCaseDescription(EqualsZeroData[testCaseInstanceId()].name); const T a = EqualsZeroData[testCaseInstanceId()].get(T{}); const T b = EqualsZeroData[testCaseInstanceId()].get(T{}); const T step = EqualsZeroData[testCaseInstanceId()].getStep(T{}); const T magnitude = std::max(abs(a), abs(b)); CORRADE_VERIFY(TypeTraits<T>::equals(a + step/T(2.0), b)); CORRADE_VERIFY(TypeTraits<T>::equalsZero(a + step/T(2.0) - b, magnitude)); CORRADE_VERIFY(!TypeTraits<T>::equals(a - step*T(2.0), b)); CORRADE_VERIFY(!TypeTraits<T>::equalsZero(a - step*T(2.0) - b, magnitude)); } }}} CORRADE_TEST_MAIN(Magnum::Math::Test::TypeTraitsTest) <commit_msg>Math: conditionally include <algorithm> for std::max() in MSVC.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <[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. */ #include <Corrade/TestSuite/Tester.h> #ifdef _MSC_VER #include <algorithm> /* std::max() */ #endif #include "Magnum/Math/TypeTraits.h" #include "Magnum/Math/Constants.h" namespace Magnum { namespace Math { namespace Test { struct TypeTraitsTest: Corrade::TestSuite::Tester { explicit TypeTraitsTest(); void name(); template<class T> void equalsIntegral(); template<class T> void equalsFloatingPoint0(); template<class T> void equalsFloatingPoint1(); template<class T> void equalsFloatingPointLarge(); template<class T> void equalsFloatingPointInfinity(); template<class T> void equalsFloatingPointNaN(); template<class T> void equalsZeroIntegral(); template<class T> void equalsZeroFloatingPoint(); template<class T> void equalsZeroFloatingPointSmall(); template<class T> void equalsZeroFloatingPointLarge(); }; namespace { enum: std::size_t { EqualsZeroDataCount = 3 }; struct { const char* name; Float a, aStep; Double b, bStep; long double c, cStep; Float get(Float) const { return a; } Float getStep(Float) const { return aStep; } Double get(Double) const { return b; } Double getStep(Double) const { return bStep; } long double get(long double) const { return c; } long double getStep(long double) const { return cStep; } } EqualsZeroData[EqualsZeroDataCount] = { {"", -3.141592653589793f, 5.0e-5f, -3.141592653589793, 5.0e-14, -3.141592653589793l, 5.0e-17l}, {"small", 1.0e-6f, 5.0e-6f, -1.0e-15, 5.0e-15, 1.0e-18l, 5.0e-18l}, {"large", 12345.0f, 0.2f, 12345678901234.0, 0.2, -12345678901234567.0l, 0.2l}, }; } TypeTraitsTest::TypeTraitsTest() { addTests<TypeTraitsTest>({ &TypeTraitsTest::name, &TypeTraitsTest::equalsIntegral<UnsignedByte>, &TypeTraitsTest::equalsIntegral<Byte>, &TypeTraitsTest::equalsIntegral<UnsignedShort>, &TypeTraitsTest::equalsIntegral<Short>, &TypeTraitsTest::equalsIntegral<UnsignedInt>, &TypeTraitsTest::equalsIntegral<Int>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsIntegral<UnsignedLong>, &TypeTraitsTest::equalsIntegral<Long>, #endif &TypeTraitsTest::equalsFloatingPoint0<Float>, &TypeTraitsTest::equalsFloatingPoint0<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsFloatingPoint0<long double>, #endif &TypeTraitsTest::equalsFloatingPoint1<Float>, &TypeTraitsTest::equalsFloatingPoint1<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsFloatingPoint1<long double>, #endif &TypeTraitsTest::equalsFloatingPointLarge<Float>, &TypeTraitsTest::equalsFloatingPointLarge<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsFloatingPointLarge<long double>, #endif &TypeTraitsTest::equalsFloatingPointInfinity<Float>, &TypeTraitsTest::equalsFloatingPointInfinity<Double>, &TypeTraitsTest::equalsFloatingPointNaN<Float>, &TypeTraitsTest::equalsFloatingPointNaN<Double>, &TypeTraitsTest::equalsZeroIntegral<UnsignedByte>, &TypeTraitsTest::equalsZeroIntegral<Byte>, &TypeTraitsTest::equalsZeroIntegral<UnsignedShort>, &TypeTraitsTest::equalsZeroIntegral<Short>, &TypeTraitsTest::equalsZeroIntegral<UnsignedInt>, &TypeTraitsTest::equalsZeroIntegral<Int>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsZeroIntegral<UnsignedLong>, &TypeTraitsTest::equalsZeroIntegral<Long>, #endif }); addInstancedTests<TypeTraitsTest>({ &TypeTraitsTest::equalsZeroFloatingPoint<Float>, &TypeTraitsTest::equalsZeroFloatingPoint<Double>, #ifndef CORRADE_TARGET_EMSCRIPTEN &TypeTraitsTest::equalsZeroFloatingPoint<long double> #endif }, EqualsZeroDataCount); } void TypeTraitsTest::name() { CORRADE_COMPARE(TypeTraits<UnsignedShort>::name(), "UnsignedShort"); CORRADE_COMPARE(TypeTraits<Float>::name(), "Float"); } template<class T> void TypeTraitsTest::equalsIntegral() { setTestCaseName(std::string{"equalsIntegral<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(1, 1)); CORRADE_VERIFY(!TypeTraits<T>::equals(1, -1)); CORRADE_VERIFY(!TypeTraits<T>::equals(1, 1+TypeTraits<T>::epsilon())); } template<class T> void TypeTraitsTest::equalsFloatingPoint0() { setTestCaseName(std::string{"equalsFloatingPoint0<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(T(0)+TypeTraits<T>::epsilon()/T(2), T(0))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(0)+TypeTraits<T>::epsilon()*T(2), T(0))); } template<class T> void TypeTraitsTest::equalsFloatingPoint1() { setTestCaseName(std::string{"equalsFloatingPoint1<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(T(1)+TypeTraits<T>::epsilon()/T(2), T(1))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(1)+TypeTraits<T>::epsilon()*T(3), T(1))); } template<class T> void TypeTraitsTest::equalsFloatingPointLarge() { setTestCaseName(std::string{"equalsFloatingPointLarge<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(T(25)+TypeTraits<T>::epsilon()*T(2), T(25))); CORRADE_VERIFY(!TypeTraits<T>::equals(T(25)+TypeTraits<T>::epsilon()*T(75), T(25))); } template<class T> void TypeTraitsTest::equalsFloatingPointInfinity() { setTestCaseName(std::string{"equalsFloatingPointInfinity<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(TypeTraits<T>::equals(Constants<T>::inf(), Constants<T>::inf())); } template<class T> void TypeTraitsTest::equalsFloatingPointNaN() { setTestCaseName(std::string{"equalsFloatingPointNaN<"} + TypeTraits<T>::name() + ">"); CORRADE_VERIFY(!TypeTraits<T>::equals(Constants<T>::nan(), Constants<T>::nan())); } namespace { /* Argh! Why there is no standard std::abs() for unsigned types? */ template<class T, class U = typename std::enable_if<std::is_unsigned<T>::value>::type> T abs(T value) { return value; } template<class T, class U = T, class V = typename std::enable_if<!std::is_unsigned<T>::value>::type> T abs(T value) { return std::abs(value); } } template<class T> void TypeTraitsTest::equalsZeroIntegral() { setTestCaseName(std::string{"equalsZeroIntegral<"} + TypeTraits<T>::name() + ">"); const T a(-123); const T b(-123); const T magnitude = std::max(abs(a), abs(b)); CORRADE_VERIFY(TypeTraits<T>::equals(a, b)); CORRADE_VERIFY(TypeTraits<T>::equalsZero(a - b, magnitude)); CORRADE_VERIFY(!TypeTraits<T>::equalsZero(a - b + TypeTraits<T>::epsilon(), magnitude)); } template<class T> void TypeTraitsTest::equalsZeroFloatingPoint() { setTestCaseName(std::string{"equalsZeroFloatingPoint<"} + TypeTraits<T>::name() + ">"); setTestCaseDescription(EqualsZeroData[testCaseInstanceId()].name); const T a = EqualsZeroData[testCaseInstanceId()].get(T{}); const T b = EqualsZeroData[testCaseInstanceId()].get(T{}); const T step = EqualsZeroData[testCaseInstanceId()].getStep(T{}); const T magnitude = std::max(abs(a), abs(b)); CORRADE_VERIFY(TypeTraits<T>::equals(a + step/T(2.0), b)); CORRADE_VERIFY(TypeTraits<T>::equalsZero(a + step/T(2.0) - b, magnitude)); CORRADE_VERIFY(!TypeTraits<T>::equals(a - step*T(2.0), b)); CORRADE_VERIFY(!TypeTraits<T>::equalsZero(a - step*T(2.0) - b, magnitude)); } }}} CORRADE_TEST_MAIN(Magnum::Math::Test::TypeTraitsTest) <|endoftext|>
<commit_before> #include "PCH-rpgcraft.h" #include "imgui-console.h" ImGuiConsole g_console; int ImGuiConsole::TextEditCallback(ImGuiTextEditCallbackData* data) { //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); switch (data->EventFlag) { case ImGuiInputTextFlags_CallbackCompletion: { // Example of TEXT COMPLETION // Locate beginning of current word const char* word_end = data->Buf + data->CursorPos; const char* word_start = word_end; while (word_start > data->Buf) { const char c = word_start[-1]; if (c == ' ' || c == '\t' || c == ',' || c == ';') break; word_start--; } #if 0 // Build a list of candidates ImVector<const char*> candidates; for (int i = 0; i < Commands.Size; i++) if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) candidates.push_back(Commands[i]); if (candidates.Size == 0) { // No match AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); } else if (candidates.Size == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } else { // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" int match_len = (int)(word_end - word_start); for (;;) { int c = 0; bool all_candidates_matches = true; for (int i = 0; i < candidates.Size && all_candidates_matches; i++) if (i == 0) c = toupper(candidates[i][match_len]); else if (c == 0 || c != toupper(candidates[i][match_len])) all_candidates_matches = false; if (!all_candidates_matches) break; match_len++; } if (match_len > 0) { data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); } // List matches AddLog("Possible matches:\n"); for (int i = 0; i < candidates.Size; i++) AddLog("- %s\n", candidates[i]); } #endif } break; case ImGuiInputTextFlags_CallbackHistory: { // Example of HISTORY const int prev_history_pos = HistoryPos; if (data->EventKey == ImGuiKey_UpArrow) { if (HistoryPos == -1) HistoryPos = History.Size - 1; else if (HistoryPos > 0) HistoryPos--; } else if (data->EventKey == ImGuiKey_DownArrow) { if (HistoryPos != -1) if (++HistoryPos >= History.Size) HistoryPos = -1; } // A better implementation would preserve the data on the current input line along with cursor position. if (prev_history_pos != HistoryPos) { data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); data->BufDirty = true; } } break; } return 0; } static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } void ImGuiConsole::ClearLog() { Buf.clear(); LineOffsets.clear(); ScrollToBottom = true; } void ImGuiConsole::AddLog(const char* fmt, ...) { int old_size = Buf.size(); va_list args; va_start(args, fmt); Buf.appendv(fmt, args); va_end(args); for (int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size); ScrollToBottom = true; } void ImGuiConsole::ExecCommand(const char* command_line) { AddLog("# %s\n", command_line); // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. HistoryPos = -1; for (int i = History.Size-1; i >= 0; i--) { if (Stricmp(History[i], command_line) == 0) { free(History[i]); History.erase(History.begin() + i); break; } } History.push_back(_strdup(command_line)); } void ImGuiConsole::AppendToCurrentFrame() { // TODO: display items starting from the bottom if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); ImGui::SameLine(); filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); ImGui::PopStyleVar(); ImGui::Separator(); ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()*2), false, ImGuiWindowFlags_HorizontalScrollbar); if (ImGui::BeginPopupContextWindow()) { copy_to_clipboard |= ImGui::Selectable("Copy"); if (ImGui::Selectable("Clear")) { ClearLog(); } ImGui::EndPopup(); } ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); // Here is sample code to use the frontend clipper to improve performance on huge consoles. // This method is mutually exclusive to being used with on-the-fly filters -- the filter would // need to be calculated in a prior step: determine # of elements, and build index table to all // lines that are "filtered in". The index table would provide fast random access. // // ImGuiListClipper clipper(Items.Size); // while (clipper.Step()) { // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { if (filter.IsActive()) { const char* buf_begin = Buf.begin(); const char* line = buf_begin; for (int line_no = 0; line != NULL; line_no++) { const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; if (filter.PassFilter(line, line_end)) { ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text. if (strstr(line, "[error]")) { col = ImColor(1.0f,0.4f,0.4f,1.0f); } elif (strncmp(line, "# ", 2) == 0) { col = ImColor(1.0f,0.78f,0.58f,1.0f); } ImGui::PushStyleColor(ImGuiCol_Text, col); ImGui::TextUnformatted(line, line_end); ImGui::PopStyleColor(); } line = line_end && line_end[1] ? line_end + 1 : NULL; } } else { ImGui::TextUnformatted(Buf.begin()); } if (copy_to_clipboard) ImGui::LogFinish(); if (ScrollToBottom) ImGui::SetScrollHere(); ImGui::PopStyleVar(); ImGui::EndChild(); ImGui::Separator(); // console command line if (ImGui::InputText("Input", InputBuf, bulkof(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, [](ImGuiTextEditCallbackData* data) { return ((ImGuiConsole*)data->UserData)->TextEditCallback(data); }, this) ) { char* input_end = InputBuf+strlen(InputBuf); while (input_end > InputBuf && input_end[-1] == ' ') { input_end--; } *input_end = 0; if (InputBuf[0]) ExecCommand(InputBuf); strcpy(InputBuf, ""); } ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); // Demonstrate keeping auto focus on the input box if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget } void ImGuiConsole::DrawFrame() { ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver); if (ImGui::Begin("Console")) { AppendToCurrentFrame(); } ImGui::End(); } <commit_msg>whitespace<commit_after> #include "PCH-rpgcraft.h" #include "imgui-console.h" ImGuiConsole g_console; int ImGuiConsole::TextEditCallback(ImGuiTextEditCallbackData* data) { //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); switch (data->EventFlag) { case ImGuiInputTextFlags_CallbackCompletion: { // Example of TEXT COMPLETION // Locate beginning of current word const char* word_end = data->Buf + data->CursorPos; const char* word_start = word_end; while (word_start > data->Buf) { const char c = word_start[-1]; if (c == ' ' || c == '\t' || c == ',' || c == ';') break; word_start--; } #if 0 // Build a list of candidates ImVector<const char*> candidates; for (int i = 0; i < Commands.Size; i++) if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) candidates.push_back(Commands[i]); if (candidates.Size == 0) { // No match AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); } else if (candidates.Size == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } else { // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" int match_len = (int)(word_end - word_start); for (;;) { int c = 0; bool all_candidates_matches = true; for (int i = 0; i < candidates.Size && all_candidates_matches; i++) if (i == 0) c = toupper(candidates[i][match_len]); else if (c == 0 || c != toupper(candidates[i][match_len])) all_candidates_matches = false; if (!all_candidates_matches) break; match_len++; } if (match_len > 0) { data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); } // List matches AddLog("Possible matches:\n"); for (int i = 0; i < candidates.Size; i++) AddLog("- %s\n", candidates[i]); } #endif } break; case ImGuiInputTextFlags_CallbackHistory: { // Example of HISTORY const int prev_history_pos = HistoryPos; if (data->EventKey == ImGuiKey_UpArrow) { if (HistoryPos == -1) HistoryPos = History.Size - 1; else if (HistoryPos > 0) HistoryPos--; } else if (data->EventKey == ImGuiKey_DownArrow) { if (HistoryPos != -1) if (++HistoryPos >= History.Size) HistoryPos = -1; } // A better implementation would preserve the data on the current input line along with cursor position. if (prev_history_pos != HistoryPos) { data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); data->BufDirty = true; } } break; } return 0; } static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } void ImGuiConsole::ClearLog() { Buf.clear(); LineOffsets.clear(); ScrollToBottom = true; } void ImGuiConsole::AddLog(const char* fmt, ...) { int old_size = Buf.size(); va_list args; va_start(args, fmt); Buf.appendv(fmt, args); va_end(args); for (int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size); ScrollToBottom = true; } void ImGuiConsole::ExecCommand(const char* command_line) { AddLog("# %s\n", command_line); // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. HistoryPos = -1; for (int i = History.Size-1; i >= 0; i--) { if (Stricmp(History[i], command_line) == 0) { free(History[i]); History.erase(History.begin() + i); break; } } History.push_back(_strdup(command_line)); } void ImGuiConsole::AppendToCurrentFrame() { // TODO: display items starting from the bottom if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); ImGui::SameLine(); filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); ImGui::PopStyleVar(); ImGui::Separator(); ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()*2), false, ImGuiWindowFlags_HorizontalScrollbar); if (ImGui::BeginPopupContextWindow()) { copy_to_clipboard |= ImGui::Selectable("Copy"); if (ImGui::Selectable("Clear")) { ClearLog(); } ImGui::EndPopup(); } ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); // Here is sample code to use the frontend clipper to improve performance on huge consoles. // This method is mutually exclusive to being used with on-the-fly filters -- the filter would // need to be calculated in a prior step: determine # of elements, and build index table to all // lines that are "filtered in". The index table would provide fast random access. // // ImGuiListClipper clipper(Items.Size); // while (clipper.Step()) { // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { if (filter.IsActive()) { const char* buf_begin = Buf.begin(); const char* line = buf_begin; for (int line_no = 0; line != NULL; line_no++) { const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; if (filter.PassFilter(line, line_end)) { ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text. if (strstr(line, "[error]")) { col = ImColor(1.0f,0.4f,0.4f,1.0f); } elif (strncmp(line, "# ", 2) == 0) { col = ImColor(1.0f,0.78f,0.58f,1.0f); } ImGui::PushStyleColor(ImGuiCol_Text, col); ImGui::TextUnformatted(line, line_end); ImGui::PopStyleColor(); } line = line_end && line_end[1] ? line_end + 1 : NULL; } } else { ImGui::TextUnformatted(Buf.begin()); } if (copy_to_clipboard) ImGui::LogFinish(); if (ScrollToBottom) ImGui::SetScrollHere(); ImGui::PopStyleVar(); ImGui::EndChild(); ImGui::Separator(); // console command line if (ImGui::InputText("Input", InputBuf, bulkof(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, [](ImGuiTextEditCallbackData* data) { return ((ImGuiConsole*)data->UserData)->TextEditCallback(data); }, this) ) { char* input_end = InputBuf+strlen(InputBuf); while (input_end > InputBuf && input_end[-1] == ' ') { input_end--; } *input_end = 0; if (InputBuf[0]) ExecCommand(InputBuf); strcpy(InputBuf, ""); } ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); // Demonstrate keeping auto focus on the input box if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget } void ImGuiConsole::DrawFrame() { ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver); if (ImGui::Begin("Console")) { AppendToCurrentFrame(); } ImGui::End(); } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QApplication> // CTK includes #include "ctkColorPickerButton.h" // STD includes #include <cstdlib> #include <iostream> //----------------------------------------------------------------------------- int ctkColorPickerButtonTest1(int argc, char * argv [] ) { QApplication app(argc, argv); ctkColorPickerButton ctkObject; return EXIT_SUCCESS; } <commit_msg>Add test to ctkColorPickerButton<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QApplication> #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkColorPickerButton.h" // STD includes #include <cstdlib> #include <iostream> //----------------------------------------------------------------------------- int ctkColorPickerButtonTest1(int argc, char * argv [] ) { QApplication app(argc, argv); QWidget topLevel; ctkColorPickerButton colorPicker1; ctkColorPickerButton colorPicker2("Select a color"); ctkColorPickerButton colorPicker3(Qt::red,"text"); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(&colorPicker1); layout->addWidget(&colorPicker2); layout->addWidget(&colorPicker3); topLevel.setLayout(layout); if (!colorPicker1.text().isEmpty() || colorPicker2.text() != "Select a color" || colorPicker3.text() != "text") { std::cerr << "ctkColorPickerButton::ctkColorPickerButton wrong default text" << colorPicker1.text().toStdString() << " " << colorPicker2.text().toStdString() << " " << colorPicker3.text().toStdString() << std::endl; return EXIT_FAILURE; } if (colorPicker1.color() != Qt::black || colorPicker2.color() != Qt::black || colorPicker3.color() != Qt::red) { std::cerr << "ctkColorPickerButton::ctkColorPickerButton wrong default color" << std::endl; return EXIT_FAILURE; } colorPicker3.setDisplayColorName(false); if (colorPicker3.displayColorName() || colorPicker3.text() != "text") { std::cerr << "ctkColorPickerButton::setDisplayColorName failed" << std::endl; return EXIT_FAILURE; } colorPicker1.setColor(QColor::fromRgbF(1., 0., 0.5)); if (colorPicker1.color() != QColor::fromRgbF(1., 0., 0.5)) { std::cerr << "ctkColorPickerButton::setColor failed" << std::endl; return EXIT_FAILURE; } colorPicker2.setShowAlpha(true); if (!colorPicker2.showAlpha()) { std::cerr << "ctkColorPickerButton::setShowAlpha failed" << std::endl; return EXIT_FAILURE; } topLevel.show(); if (argc < 2 || QString(argv[1]) != "-I" ) { QTimer::singleShot(300, &app, SLOT(quit())); } QTimer::singleShot(100, &colorPicker2, SLOT(changeColor())); return app.exec(); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbBandMathImageFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbObjectList.h" namespace otb { namespace Wrapper { class BandMath : public Application { public: /** Standard class typedefs. */ typedef BandMath Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(BandMath, otb::Application); typedef otb::MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType, FloatImageType::PixelType> ExtractROIFilterType; typedef otb::ObjectList<ExtractROIFilterType> ExtractROIFilterListType; typedef otb::BandMathImageFilter<FloatImageType> BandMathImageFilterType; private: void DoInit() ITK_OVERRIDE { SetName("BandMath"); SetDescription("Perform a mathematical operation on monoband images"); SetDocName("Band Math"); SetDocLongDescription("This application performs a mathematical operation on monoband images." "Mathematical formula interpretation is done via MuParser libraries.\n" "For MuParser version superior to 2.0 uses '&&' and '||' logical operators, and ternary operator 'boolean_expression ? if_true : if_false'\n" "For older version of MuParser (prior to v2) use 'and' and 'or' logical operators, and ternary operator 'if(; ; )'.\n" "The list of features and operators is available on MuParser website: http://muparser.sourceforge.net/\n" ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag("Util"); AddParameter(ParameterType_InputImageList, "il", "Input image list"); SetParameterDescription("il", "Image list to perform computation on."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image."); AddRAMParameter(); AddParameter(ParameterType_String, "exp", "Expression"); SetParameterDescription("exp", "The mathematical expression to apply. \nUse im1b1 for the first band, im1b2 for the second one..."); // Doc example parameter settings SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"); SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif"); SetDocExampleParameterValue("exp", "\"cos(im1b1) > cos(im2b1) ? im3b1 : im3b2 \""); } void DoUpdateParameters() ITK_OVERRIDE { // Check if the expression is correctly set if (HasValue("il")) { LiveCheck(); } } void LiveCheck() { // Initialize a bandMath Filter first m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); unsigned int nbInputs = inList->Size(); unsigned int imageId = 0, bandId = 0; for (unsigned int i = 0; i < nbInputs; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } otb::Parser::Pointer dummyParser = otb::Parser::New(); std::vector<double> dummyVars; std::string success = "The expression is Valid"; SetParameterDescription("exp", success); std::ostringstream failure; if (HasValue("exp")) { // Setup the dummy parser for (unsigned int i = 0; i < bandId; i++) { dummyVars.push_back(1.); dummyParser->DefineVar(m_Filter->GetNthInputName(i), &(dummyVars.at(i))); } dummyParser->SetExpr(GetParameterString("exp")); // Check the expression try { dummyParser->Eval(); } catch(itk::ExceptionObject& err) { // Change the parameter description to be able to have the // parser errors in the tooltip SetParameterDescription("exp", err.GetDescription()); } } } void DoExecute() ITK_OVERRIDE { // Get the input image list FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); // checking the input images list validity const unsigned int nbImages = inList->Size(); if (nbImages == 0) { itkExceptionMacro("No input Image set...; please set at least one input image"); } m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); unsigned int bandId = 0; unsigned int imageId = 0; for (unsigned int i = 0; i < nbImages; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); otbAppLogINFO( << "Image #" << i + 1 << " has " << currentImage->GetNumberOfComponentsPerPixel() << " components" << std::endl ); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } m_Filter->SetExpression(GetParameterString("exp")); // Set the output image SetParameterOutputImage("out", m_Filter->GetOutput()); } ExtractROIFilterType::Pointer m_ExtractROIFilter; ExtractROIFilterListType::Pointer m_ChannelExtractorList; BandMathImageFilterType::Pointer m_Filter; }; } // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::BandMath) <commit_msg>DOC: remove extra space from BandMath expression example<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbBandMathImageFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbObjectList.h" namespace otb { namespace Wrapper { class BandMath : public Application { public: /** Standard class typedefs. */ typedef BandMath Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(BandMath, otb::Application); typedef otb::MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType, FloatImageType::PixelType> ExtractROIFilterType; typedef otb::ObjectList<ExtractROIFilterType> ExtractROIFilterListType; typedef otb::BandMathImageFilter<FloatImageType> BandMathImageFilterType; private: void DoInit() ITK_OVERRIDE { SetName("BandMath"); SetDescription("Perform a mathematical operation on monoband images"); SetDocName("Band Math"); SetDocLongDescription("This application performs a mathematical operation on monoband images." "Mathematical formula interpretation is done via MuParser libraries.\n" "For MuParser version superior to 2.0 uses '&&' and '||' logical operators, and ternary operator 'boolean_expression ? if_true : if_false'\n" "For older version of MuParser (prior to v2) use 'and' and 'or' logical operators, and ternary operator 'if(; ; )'.\n" "The list of features and operators is available on MuParser website: http://muparser.sourceforge.net/\n" ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag("Util"); AddParameter(ParameterType_InputImageList, "il", "Input image list"); SetParameterDescription("il", "Image list to perform computation on."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image."); AddRAMParameter(); AddParameter(ParameterType_String, "exp", "Expression"); SetParameterDescription("exp", "The mathematical expression to apply. \nUse im1b1 for the first band, im1b2 for the second one..."); // Doc example parameter settings SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"); SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif"); SetDocExampleParameterValue("exp", "\"cos(im1b1) > cos(im2b1) ? im3b1 : im3b2\""); } void DoUpdateParameters() ITK_OVERRIDE { // Check if the expression is correctly set if (HasValue("il")) { LiveCheck(); } } void LiveCheck() { // Initialize a bandMath Filter first m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); unsigned int nbInputs = inList->Size(); unsigned int imageId = 0, bandId = 0; for (unsigned int i = 0; i < nbInputs; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } otb::Parser::Pointer dummyParser = otb::Parser::New(); std::vector<double> dummyVars; std::string success = "The expression is Valid"; SetParameterDescription("exp", success); std::ostringstream failure; if (HasValue("exp")) { // Setup the dummy parser for (unsigned int i = 0; i < bandId; i++) { dummyVars.push_back(1.); dummyParser->DefineVar(m_Filter->GetNthInputName(i), &(dummyVars.at(i))); } dummyParser->SetExpr(GetParameterString("exp")); // Check the expression try { dummyParser->Eval(); } catch(itk::ExceptionObject& err) { // Change the parameter description to be able to have the // parser errors in the tooltip SetParameterDescription("exp", err.GetDescription()); } } } void DoExecute() ITK_OVERRIDE { // Get the input image list FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); // checking the input images list validity const unsigned int nbImages = inList->Size(); if (nbImages == 0) { itkExceptionMacro("No input Image set...; please set at least one input image"); } m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); unsigned int bandId = 0; unsigned int imageId = 0; for (unsigned int i = 0; i < nbImages; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); otbAppLogINFO( << "Image #" << i + 1 << " has " << currentImage->GetNumberOfComponentsPerPixel() << " components" << std::endl ); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } m_Filter->SetExpression(GetParameterString("exp")); // Set the output image SetParameterOutputImage("out", m_Filter->GetOutput()); } ExtractROIFilterType::Pointer m_ExtractROIFilter; ExtractROIFilterListType::Pointer m_ChannelExtractorList; BandMathImageFilterType::Pointer m_Filter; }; } // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::BandMath) <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbRPCTransformBase_hxx #define otbRPCTransformBase_hxx #include "otbRPCTransformBase.h" namespace otb { template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> bool RPCTransformBase<TScalarType, NInputDimensions, NOutputDimensions>::SetMetadata(const ImageMetadata& imd) { if (!imd.Has(MDGeom::RPC)) return false; try { Projection::RPCParam newParam = boost::any_cast<Projection::RPCParam>(imd[MDGeom::RPC]); this->m_RPCParam.reset(&newParam); } catch (boost::bad_any_cast) { return false; } GDALRPCTransformer newTrans = GDALRPCTransformer( m_RPCParam->LineOffset, m_RPCParam->SampleOffset, m_RPCParam->LatOffset, m_RPCParam->LonOffset, m_RPCParam->HeightOffset, m_RPCParam->LineScale, m_RPCParam->SampleScale, m_RPCParam->LatScale, m_RPCParam->LonScale, m_RPCParam->HeightScale, m_RPCParam->LineNum, m_RPCParam->LineDen, m_RPCParam->SampleNum, m_RPCParam->SampleDen); this->m_Transformer.reset(&newTrans); return true; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> bool RPCTransformBase<TScalarType, NInputDimensions, NOutputDimensions>::IsValidSensorModel() const { return m_Transformer != nullptr; } /** * PrintSelf method */ template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> void RPCTransformBase<TScalarType, NInputDimensions, NOutputDimensions>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "RPC Model: " << this->m_RPCParam.get() << std::endl; } } #endif <commit_msg>BUG: Use make_unique to instantiate unique_ptrs<commit_after>/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbRPCTransformBase_hxx #define otbRPCTransformBase_hxx #include "otbRPCTransformBase.h" namespace otb { template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> bool RPCTransformBase<TScalarType, NInputDimensions, NOutputDimensions>::SetMetadata(const ImageMetadata& imd) { if (!imd.Has(MDGeom::RPC)) return false; try { Projection::RPCParam newParam = boost::any_cast<Projection::RPCParam>(imd[MDGeom::RPC]); this->m_RPCParam = std::make_unique<Projection::RPCParam>(newParam); } catch (boost::bad_any_cast) { return false; } this->m_Transformer = std::make_unique<GDALRPCTransformer>( m_RPCParam->LineOffset, m_RPCParam->SampleOffset, m_RPCParam->LatOffset, m_RPCParam->LonOffset, m_RPCParam->HeightOffset, m_RPCParam->LineScale, m_RPCParam->SampleScale, m_RPCParam->LatScale, m_RPCParam->LonScale, m_RPCParam->HeightScale, m_RPCParam->LineNum, m_RPCParam->LineDen, m_RPCParam->SampleNum, m_RPCParam->SampleDen); return true; } template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> bool RPCTransformBase<TScalarType, NInputDimensions, NOutputDimensions>::IsValidSensorModel() const { return m_Transformer != nullptr; } /** * PrintSelf method */ template <class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions> void RPCTransformBase<TScalarType, NInputDimensions, NOutputDimensions>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "RPC Model: " << this->m_RPCParam.get() << std::endl; } } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-15 11:12:36 +0100 (Mo, 15 Mrz 2010) $ Version: $Revision: 21745 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkTestingMacros.h" #include "mitkPlanarPolygon.h" #include "mitkPlaneGeometry.h" class mitkPlanarPolygonTestClass { public: static void TestPlanarPolygonPlacement( mitk::PlanarPolygon::Pointer planarPolygon ) { // Test for correct minimum number of control points in cross-mode MITK_TEST_CONDITION( planarPolygon->GetMinimumNumberOfControlPoints() == 2, "Minimum number of control points" ); // Test for correct maximum number of control points in cross-mode MITK_TEST_CONDITION( planarPolygon->GetMaximumNumberOfControlPoints() == 1000, "Maximum number of control points" ); // Initial placement of PlanarPolygon mitk::Point2D p0; p0[0] = 00.0; p0[1] = 0.0; planarPolygon->PlaceFigure( p0 ); // Add second control point mitk::Point2D p1; p1[0] = 50.0; p1[1] = 00.0; planarPolygon->SetControlPoint(1, p1 ); // Add third control point mitk::Point2D p2; p2[0] = 50.0; p2[1] = 50.0; planarPolygon->AddControlPoint( p2 ); // Add fourth control point mitk::Point2D p3; p3[0] = 0.0; p3[1] = 50.0; planarPolygon->AddControlPoint( p3 ); // Test for number of control points MITK_TEST_CONDITION( planarPolygon->GetNumberOfControlPoints() == 4, "Number of control points after placement" ); // Test if PlanarFigure is closed MITK_TEST_CONDITION( planarPolygon->IsClosed(), "planar polygon should not be closed, yet, right?" ); planarPolygon->SetClosed(true); MITK_TEST_CONDITION( planarPolygon->IsClosed(), "planar polygon should be closed after function call, right?" ); // Test for number of polylines const mitk::PlanarFigure::VertexContainerType* polyLine0 = planarPolygon->GetPolyLine( 0 ); MITK_TEST_CONDITION( planarPolygon->GetPolyLinesSize() == 1, "Number of polylines after placement" ); // Get polylines and check if the generated coordinates are OK const mitk::Point2D& pp0 = polyLine0->ElementAt( 0 ); const mitk::Point2D& pp1 = polyLine0->ElementAt( 1 ); MITK_TEST_CONDITION( ((pp0 == p0) && (pp1 == p1)) || ((pp0 == p1) && (pp1 == p0)), "Correct polyline 1" ); // Test for number of measurement features planarPolygon->EvaluateFeatures(); MITK_TEST_CONDITION( planarPolygon->GetNumberOfFeatures() == 2, "Number of measurement features" ); // Test for correct feature evaluation double length0 = 4 * 50.0; // circumference MITK_TEST_CONDITION( fabs( planarPolygon->GetQuantity( 0 ) - length0) < mitk::eps, "Size of longest diameter" ); double length1 = 50.0 * 50.0 ; // area MITK_TEST_CONDITION( fabs( planarPolygon->GetQuantity( 1 ) - length1) < mitk::eps, "Size of short axis diameter" ); } static void TestplanarPolygonPlacementConstrained(mitk::PlanarPolygon::Pointer planarPolygon) { // ************************************************************************** // Place first control point out of bounds (to the left of the image bounds) mitk::Point2D p0; p0[0] = -20.0; p0[1] = 20.0; planarPolygon->PlaceFigure( p0 ); // Test if constraint has been applied correctly mitk::Point2D cp0 = planarPolygon->GetControlPoint( 0 ); MITK_TEST_CONDITION( (fabs(cp0[0]) < mitk::eps) && (fabs(cp0[1] - 20.0) < mitk::eps), "Point1 placed and constrained correctly" ); // ************************************************************************** // Add second control point out of bounds (to the top of the image bounds) mitk::Point2D p1; p1[0] = 80.0; p1[1] = 120.0; planarPolygon->SetCurrentControlPoint( p1 ); // Test if constraint has been applied correctly mitk::Point2D cp1 = planarPolygon->GetControlPoint( 1 ); MITK_TEST_CONDITION( (fabs(cp1[0] - 80.0) < mitk::eps) && (fabs(cp1[1] - 100.0) < mitk::eps), "Point2 placed and constrained correctly" ); // ************************************************************************** // Add third control point out of bounds (outside of channel defined by first line) mitk::Point2D p2; p2[0] = 100.0; p2[1] = 100.0; planarPolygon->AddControlPoint( p2 ); // Test if constraint has been applied correctly (100.0, 100.0) must be projected to (90.0, 90.0) mitk::Point2D cp2 = planarPolygon->GetControlPoint( 2 ); MITK_TEST_CONDITION( (fabs(cp2[0] - 90.0) < mitk::eps) && (fabs(cp2[1] - 90.0) < mitk::eps), "Point3 placed and constrained correctly" ); // Move third control point (within channel defined by first line) p2[0] = 40.0; p2[1] = 20.0; planarPolygon->SetControlPoint( 2, p2 ); // Test if point is still at this position (no constrained should be applied) cp2 = planarPolygon->GetControlPoint( 2 ); MITK_TEST_CONDITION( (fabs(cp2[0] - 40.0) < mitk::eps) && (fabs(cp2[1] - 20.0) < mitk::eps), "Point3 moved correctly" ); // ************************************************************************** // Add fourth control point out of bounds (outside of line defined by first line and third point) mitk::Point2D p3; p3[0] = 20.0; p3[1] = 60.0; planarPolygon->AddControlPoint( p3 ); // Test if constraint has been applied correctly (20.0, 60.0) must be projected to (10.0, 50.0) mitk::Point2D cp3 = planarPolygon->GetControlPoint( 3 ); MITK_TEST_CONDITION( (fabs(cp3[0] - 10.0) < mitk::eps) && (fabs(cp3[1] - 50.0) < mitk::eps), "Point4 placed and constrained correctly" ); } }; /** * mitkplanarPolygonTest tests the methods and behavior of mitk::PlanarPolygon with sub-tests: * * 1. Instantiation and basic tests, including feature evaluation * */ int mitkPlanarPolygonTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("planarPolygon") // create PlaneGeometry on which to place the planarPolygon mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New(); planeGeometry->InitializeStandardPlane( 100.0, 100.0 ); // ************************************************************************** // 1. Instantiation and basic tests, including feature evaluation mitk::PlanarPolygon::Pointer planarPolygon = mitk::PlanarPolygon::New(); planarPolygon->SetGeometry2D( planeGeometry ); // first test: did this work? MITK_TEST_CONDITION_REQUIRED( planarPolygon.IsNotNull(), "Testing instantiation" ); // Test placement of planarPolygon by control points mitkPlanarPolygonTestClass::TestPlanarPolygonPlacement( planarPolygon ); // always end with this! MITK_TEST_END() } <commit_msg>ENH (#3580): removed TestplanarPolygonPlacementConstrained, as it's useless<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-15 11:12:36 +0100 (Mo, 15 Mrz 2010) $ Version: $Revision: 21745 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkTestingMacros.h" #include "mitkPlanarPolygon.h" #include "mitkPlaneGeometry.h" class mitkPlanarPolygonTestClass { public: static void TestPlanarPolygonPlacement( mitk::PlanarPolygon::Pointer planarPolygon ) { // Test for correct minimum number of control points in cross-mode MITK_TEST_CONDITION( planarPolygon->GetMinimumNumberOfControlPoints() == 2, "Minimum number of control points" ); // Test for correct maximum number of control points in cross-mode MITK_TEST_CONDITION( planarPolygon->GetMaximumNumberOfControlPoints() == 1000, "Maximum number of control points" ); // Initial placement of PlanarPolygon mitk::Point2D p0; p0[0] = 00.0; p0[1] = 0.0; planarPolygon->PlaceFigure( p0 ); // Add second control point mitk::Point2D p1; p1[0] = 50.0; p1[1] = 00.0; planarPolygon->SetControlPoint(1, p1 ); // Add third control point mitk::Point2D p2; p2[0] = 50.0; p2[1] = 50.0; planarPolygon->AddControlPoint( p2 ); // Add fourth control point mitk::Point2D p3; p3[0] = 0.0; p3[1] = 50.0; planarPolygon->AddControlPoint( p3 ); // Test for number of control points MITK_TEST_CONDITION( planarPolygon->GetNumberOfControlPoints() == 4, "Number of control points after placement" ); // Test if PlanarFigure is closed MITK_TEST_CONDITION( planarPolygon->IsClosed(), "planar polygon should not be closed, yet, right?" ); planarPolygon->SetClosed(true); MITK_TEST_CONDITION( planarPolygon->IsClosed(), "planar polygon should be closed after function call, right?" ); // Test for number of polylines const mitk::PlanarFigure::VertexContainerType* polyLine0 = planarPolygon->GetPolyLine( 0 ); MITK_TEST_CONDITION( planarPolygon->GetPolyLinesSize() == 1, "Number of polylines after placement" ); // Get polylines and check if the generated coordinates are OK const mitk::Point2D& pp0 = polyLine0->ElementAt( 0 ); const mitk::Point2D& pp1 = polyLine0->ElementAt( 1 ); MITK_TEST_CONDITION( ((pp0 == p0) && (pp1 == p1)) || ((pp0 == p1) && (pp1 == p0)), "Correct polyline 1" ); // Test for number of measurement features planarPolygon->EvaluateFeatures(); MITK_TEST_CONDITION( planarPolygon->GetNumberOfFeatures() == 2, "Number of measurement features" ); // Test for correct feature evaluation double length0 = 4 * 50.0; // circumference MITK_TEST_CONDITION( fabs( planarPolygon->GetQuantity( 0 ) - length0) < mitk::eps, "Size of longest diameter" ); double length1 = 50.0 * 50.0 ; // area MITK_TEST_CONDITION( fabs( planarPolygon->GetQuantity( 1 ) - length1) < mitk::eps, "Size of short axis diameter" ); } /** * mitkplanarPolygonTest tests the methods and behavior of mitk::PlanarPolygon with sub-tests: * * 1. Instantiation and basic tests, including feature evaluation * */ int mitkPlanarPolygonTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("planarPolygon") // create PlaneGeometry on which to place the planarPolygon mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New(); planeGeometry->InitializeStandardPlane( 100.0, 100.0 ); // ************************************************************************** // 1. Instantiation and basic tests, including feature evaluation mitk::PlanarPolygon::Pointer planarPolygon = mitk::PlanarPolygon::New(); planarPolygon->SetGeometry2D( planeGeometry ); // first test: did this work? MITK_TEST_CONDITION_REQUIRED( planarPolygon.IsNotNull(), "Testing instantiation" ); // Test placement of planarPolygon by control points mitkPlanarPolygonTestClass::TestPlanarPolygonPlacement( planarPolygon ); // always end with this! MITK_TEST_END() } <|endoftext|>
<commit_before>AliAnalysisTaskSEHFTenderQnVectors* AddTaskHFTenderQnVectors(TString taskname = "HFTenderQnVectors", TString outputSuffix = "", int harmonic = 2, int normmethod = AliHFQnVectorHandler::kQoverM, int calibType = AliHFQnVectorHandler::kQnCalib, TString AODBfileName = "") { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AliAnalysisTaskSEHFSystPID", "No analysis manager found."); return 0; } if (!mgr->GetInputEventHandler()) { ::Error("AliAnalysisTaskSEHFSystPID", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if(type.Contains("ESD")){ ::Error("AliAnalysisTaskSEHFSystPID", "This task requires to run on AOD"); return NULL; } //========= Add task for standard analysis to the ANALYSIS manager ==== AliAnalysisTaskSEHFTenderQnVectors *task = new AliAnalysisTaskSEHFTenderQnVectors(taskname.Data(),harmonic,calibType,AODBfileName); task->SetNormalisationMethod(normmethod); mgr->AddTask(task); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWGHF_D2H_QnVectorTender"; //define input container AliAnalysisDataContainer *cinput = mgr->CreateContainer("cinputQnVectorTender",TChain::Class(),AliAnalysisManager::kInputContainer); //define output containers AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("coutputQnVectorTender%s",outputSuffix.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); //connect containers mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, coutput); return task; }<commit_msg>Modify input container name<commit_after>AliAnalysisTaskSEHFTenderQnVectors* AddTaskHFTenderQnVectors(TString taskname = "HFTenderQnVectors", TString outputSuffix = "", int harmonic = 2, int normmethod = AliHFQnVectorHandler::kQoverM, int calibType = AliHFQnVectorHandler::kQnCalib, TString AODBfileName = "") { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AliAnalysisTaskSEHFSystPID", "No analysis manager found."); return 0; } if (!mgr->GetInputEventHandler()) { ::Error("AliAnalysisTaskSEHFSystPID", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if(type.Contains("ESD")){ ::Error("AliAnalysisTaskSEHFSystPID", "This task requires to run on AOD"); return NULL; } //========= Add task for standard analysis to the ANALYSIS manager ==== AliAnalysisTaskSEHFTenderQnVectors *task = new AliAnalysisTaskSEHFTenderQnVectors(taskname.Data(),harmonic,calibType,AODBfileName); task->SetNormalisationMethod(normmethod); mgr->AddTask(task); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWGHF_D2H_QnVectorTender"; //define input container AliAnalysisDataContainer *cinput = mgr->CreateContainer(Form("cinputQnVectorTender%s",outputSuffix.Data()),TChain::Class(),AliAnalysisManager::kInputContainer); //define output containers AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("coutputQnVectorTender%s",outputSuffix.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); //connect containers mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, coutput); return task; }<|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2009-2013 Matthias Kretz <[email protected]> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <iostream> #include <cstring> using namespace Vc; template<typename Vec> void alignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (int i = 0; i < Count; i += Vec::Size) { x.store(&array[i]); } for (int i = 0; i < Count; ++i) { COMPARE(array[i], xValue); } // make sure store can be used with parameters that auto-convert to T* x.store(array); if (std::is_integral<T>::value && std::is_unsigned<T>::value) { // ensure that over-/underflowed values are stored correctly. Vec v = Vec::Zero() - Vec::One(); // underflow v.store(array); for (size_t i = 0; i < Vec::Size; ++i) { COMPARE(array[i], v[i]); } v = std::numeric_limits<T>::max() + Vec::One(); // overflow v.store(array); for (size_t i = 0; i < Vec::Size; ++i) { COMPARE(array[i], v[i]); } } } template<typename Vec> void unalignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (size_t i = 1; i < Count - Vec::Size + 1; i += Vec::Size) { x.store(&array[i], Unaligned); } for (size_t i = 1; i < Count - Vec::Size + 1; ++i) { COMPARE(array[i], xValue); } } template<typename Vec> void streamingAndAlignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (int i = 0; i < Count; i += Vec::Size) { x.store(&array[i], Streaming | Aligned); } for (int i = 0; i < Count; ++i) { COMPARE(array[i], xValue); } } template<typename Vec> void streamingAndUnalignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (size_t i = 1; i < Count - Vec::Size + 1; i += Vec::Size) { x.store(&array[i], Streaming | Unaligned); } for (size_t i = 1; i < Count - Vec::Size + 1; ++i) { COMPARE(array[i], xValue); } } template<typename Vec> void maskedStore() { typedef typename Vec::EntryType T; typedef typename Vec::Mask M; M mask; { typedef typename Vec::IndexType I; const I tmp(IndexesFromZero); const typename I::Mask k = (tmp & I(One)) > 0; mask = M(k); } const int count = 256 * 1024 / sizeof(T); Vc::Memory<Vec> array(count); array.setZero(); const T nullValue = 0; const T setValue = 170; const Vec x(setValue); for (int i = 0; i < count; i += Vec::Size) { x.store(&array[i], mask, Vc::Aligned); } for (int i = 1; i < count; i += 2) { COMPARE(array[i], setValue) << ", i: " << i << ", count: " << count << ", mask: " << mask << ", array:\n" << array; } for (int i = 0; i < count; i += 2) { COMPARE(array[i], nullValue) << ", i: " << i << ", count: " << count << ", mask: " << mask << ", array:\n" << array; } } void testmain() { testAllTypes(alignedStore); testAllTypes(unalignedStore); testAllTypes(streamingAndAlignedStore); testAllTypes(streamingAndUnalignedStore); if (float_v::Size > 1) { runTest(maskedStore<int_v>); runTest(maskedStore<uint_v>); runTest(maskedStore<float_v>); runTest(maskedStore<double_v>); runTest(maskedStore<short_v>); runTest(maskedStore<ushort_v>); } } <commit_msg>make them aligned stores<commit_after>/* This file is part of the Vc library. Copyright (C) 2009-2013 Matthias Kretz <[email protected]> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <iostream> #include <cstring> using namespace Vc; template<typename Vec> void alignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (int i = 0; i < Count; i += Vec::Size) { x.store(&array[i], Vc::Aligned); } for (int i = 0; i < Count; ++i) { COMPARE(array[i], xValue); } // make sure store can be used with parameters that auto-convert to T* x.store(array, Vc::Aligned); if (std::is_integral<T>::value && std::is_unsigned<T>::value) { // ensure that over-/underflowed values are stored correctly. Vec v = Vec::Zero() - Vec::One(); // underflow v.store(array, Vc::Aligned); for (size_t i = 0; i < Vec::Size; ++i) { COMPARE(array[i], v[i]); } v = std::numeric_limits<T>::max() + Vec::One(); // overflow v.store(array, Vc::Aligned); for (size_t i = 0; i < Vec::Size; ++i) { COMPARE(array[i], v[i]); } } } template<typename Vec> void unalignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (size_t i = 1; i < Count - Vec::Size + 1; i += Vec::Size) { x.store(&array[i], Unaligned); } for (size_t i = 1; i < Count - Vec::Size + 1; ++i) { COMPARE(array[i], xValue); } } template<typename Vec> void streamingAndAlignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (int i = 0; i < Count; i += Vec::Size) { x.store(&array[i], Streaming | Aligned); } for (int i = 0; i < Count; ++i) { COMPARE(array[i], xValue); } } template<typename Vec> void streamingAndUnalignedStore() { typedef typename Vec::EntryType T; enum { Count = 256 * 1024 / sizeof(T) }; Memory<Vec, Count> array; // do the memset to make sure the array doesn't have the old data from a previous call which // would mask a real problem std::memset(array, 0xff, Count * sizeof(T)); T xValue = 1; const Vec x(xValue); for (size_t i = 1; i < Count - Vec::Size + 1; i += Vec::Size) { x.store(&array[i], Streaming | Unaligned); } for (size_t i = 1; i < Count - Vec::Size + 1; ++i) { COMPARE(array[i], xValue); } } template<typename Vec> void maskedStore() { typedef typename Vec::EntryType T; typedef typename Vec::Mask M; M mask; { typedef typename Vec::IndexType I; const I tmp(IndexesFromZero); const typename I::Mask k = (tmp & I(One)) > 0; mask = M(k); } const int count = 256 * 1024 / sizeof(T); Vc::Memory<Vec> array(count); array.setZero(); const T nullValue = 0; const T setValue = 170; const Vec x(setValue); for (int i = 0; i < count; i += Vec::Size) { x.store(&array[i], mask, Vc::Aligned); } for (int i = 1; i < count; i += 2) { COMPARE(array[i], setValue) << ", i: " << i << ", count: " << count << ", mask: " << mask << ", array:\n" << array; } for (int i = 0; i < count; i += 2) { COMPARE(array[i], nullValue) << ", i: " << i << ", count: " << count << ", mask: " << mask << ", array:\n" << array; } } void testmain() { testAllTypes(alignedStore); testAllTypes(unalignedStore); testAllTypes(streamingAndAlignedStore); testAllTypes(streamingAndUnalignedStore); if (float_v::Size > 1) { runTest(maskedStore<int_v>); runTest(maskedStore<uint_v>); runTest(maskedStore<float_v>); runTest(maskedStore<double_v>); runTest(maskedStore<short_v>); runTest(maskedStore<ushort_v>); } } <|endoftext|>
<commit_before>/* FirePick.cpp https://github.com/firepick1/FirePick/wiki Copyright (C) 2013 Karl Lew, <[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 <stdio.h> #include <time.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include "FirePick.h" #include "FireLog.h" #include "FirePiCam.h" #include <opencv/cv.h> #include <opencv/highgui.h> #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #define STATUS_BUFFER_SIZE 1024 char status_buffer[STATUS_BUFFER_SIZE]; static void circles_MSER(cv::Mat &matGray, cv::Mat &matRGB){ int threshold_value = 64; int delta = 5; int minArea = 400; // 60; int maxArea = 600; //14400; double maxVariation = 0.25; double minDiversity = 0.2; int max_evolution = 200; double area_threshold = 1.01; double min_margin = .003; int edge_blur_size = 5; cv::vector<cv::vector<cv::Point> > contours; cv::Mat mask; //threshold( matGray, matGray, threshold_value, 255, cv::THRESH_TOZERO ); //matGray.convertTo(matGray, -1, 2, 0); // contrast cv::MSER(delta, minArea, maxArea, maxVariation, minDiversity, max_evolution, area_threshold, min_margin, edge_blur_size)(matGray, contours, mask); int nBlobs = (int) contours.size(); cv::Scalar mark(255,0,255); LOGINFO1("circles_MSER %d blobs", nBlobs); for( int i = 0; i < nBlobs; i++) { cv::vector<cv::Point> pts = contours[i]; int nPts = pts.size(); int red = (i & 1) ? 128 : 192; int green = (i & 4) ? 128 : 192; int blue = (i & 2) ? 128 : 192; int minX = 0x7fff; int maxX = 0; int minY = 0x7fff; int maxY = 0; float avgX = 0; float avgY = 0; for (int j = 0; j < nPts; j++) { if (pts[j].x < minX) { minX = pts[j].x; } if (pts[j].y < minY) { minY = pts[j].y; } if (pts[j].x > maxX) { maxX = pts[j].x; } if (pts[j].y > maxY) { maxY = pts[j].y; } avgX += pts[j].x; avgY += pts[j].y; } avgX = avgX / nPts; avgY = avgY / nPts; LOGINFO3("circles_MSER (%d,%d) %d pts", (int)(avgX * 10+.5), (int)(avgY*10 +.5), nPts); if (maxX - minX < 40 && maxY - minY < 40) { red = 255; green = 0; blue = 255; } for (int j = 0; j < nPts; j++) { matRGB.at<cv::Vec3b>(pts[j])[0] = red; matRGB.at<cv::Vec3b>(pts[j])[1] = green; matRGB.at<cv::Vec3b>(pts[j])[2] = blue; } } //circle( matRGB, cv::Point(400,100), 50, mark, 3, 8, 0 ); } static void circles_Hough(cv::Mat matGray){ //GaussianBlur( matGray, matGray, cv::Size(9, 9), 2, 2 ); int threshold_value = 64; int max_BINARY_value = 255; //matGray.convertTo(matGray, -1, .5, 0); // contrast //threshold( matGray, matGray, threshold_value, max_BINARY_value, cv::THRESH_BINARY ); cv::vector<cv::Vec3f> circles; HoughCircles(matGray, circles, CV_HOUGH_GRADIENT, 2, 16, 200, 100, 4, 65 ); for( size_t i = 0; i < circles.size(); i++ ) { int x = cvRound(circles[i][0]); int y = cvRound(circles[i][1]); int radius = cvRound(circles[i][2]); cv::Point center(x, y); LOGINFO3("firepick_circles (%d,%d,%d)", x, y, radius); circle( matGray, center, 3, cv::Scalar(0,255,0), -1, 8, 0 ); // draw the circle center circle( matGray, center, radius, cv::Scalar(0,0,255), 3, 8, 0 ); // draw the circle outline } } const void* firepick_circles(JPG *pJPG) { CvMat* cvJpg = cvCreateMatHeader(1, pJPG->length, CV_8UC1); cvSetData(cvJpg, pJPG->pData, pJPG->length); IplImage *pCvImg = cvDecodeImage(cvJpg, CV_LOAD_IMAGE_COLOR); cv::Mat matRGB(pCvImg); cv::Mat matGray; cvtColor(matRGB, matGray, CV_RGB2GRAY); //circles_Hough(matGray); circles_MSER(matGray, matRGB); imwrite("/home/pi/camcv.bmp", matRGB); cvReleaseMatHeader(&cvJpg); return pJPG; } const char* firepick_status() { time_t current_time = time(NULL); char timebuf[70]; strcpy(timebuf, ctime(&current_time)); timebuf[strlen(timebuf)-1] = 0; const char *errorOrWarn = firelog_lastMessage(FIRELOG_WARN); if (strlen(errorOrWarn)) { return errorOrWarn; } sprintf(status_buffer, "{\n" " 'timestamp':'%s'\n" " 'message':'FirePick OK!',\n" " 'version':'FireFuse version %d.%d'\n" "}\n", timebuf, FireFuse_VERSION_MAJOR, FireFuse_VERSION_MINOR); return status_buffer; } int firepick_camera_daemon(JPG *pJPG) { int status = firepicam_create(0, NULL); LOGINFO1("firepick_camera_daemon start -> %d", status); for (;;) { JPG_Buffer buffer; buffer.pData = NULL; buffer.length = 0; status = firepicam_acquireImage(&buffer); pJPG->pData = buffer.pData; pJPG->length = buffer.length; } LOGINFO1("firepick_camera_daemon exit -> %d", status); firepicam_destroy(status); } <commit_msg>diversity-adjusted-for-small-radius<commit_after>/* FirePick.cpp https://github.com/firepick1/FirePick/wiki Copyright (C) 2013 Karl Lew, <[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 <stdio.h> #include <time.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include "FirePick.h" #include "FireLog.h" #include "FirePiCam.h" #include <opencv/cv.h> #include <opencv/highgui.h> #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #define STATUS_BUFFER_SIZE 1024 char status_buffer[STATUS_BUFFER_SIZE]; static void circles_MSER(cv::Mat &matGray, cv::Mat &matRGB){ int threshold_value = 64; int delta = 5; int minArea = 400; // 60; int maxArea = 620; //14400; double maxVariation = 0.25; double minDiversity = 0.3; // 0.2; int max_evolution = 200; double area_threshold = 1.01; double min_margin = .003; int edge_blur_size = 5; cv::vector<cv::vector<cv::Point> > contours; cv::Mat mask; //threshold( matGray, matGray, threshold_value, 255, cv::THRESH_TOZERO ); //matGray.convertTo(matGray, -1, 2, 0); // contrast cv::MSER(delta, minArea, maxArea, maxVariation, minDiversity, max_evolution, area_threshold, min_margin, edge_blur_size)(matGray, contours, mask); int nBlobs = (int) contours.size(); cv::Scalar mark(255,0,255); LOGINFO1("circles_MSER %d blobs", nBlobs); for( int i = 0; i < nBlobs; i++) { cv::vector<cv::Point> pts = contours[i]; int nPts = pts.size(); int red = (i & 1) ? 0 : 255; int green = (i & 2) ? 128 : 255 ; int blue = (i & 1) ? 255 : 0; int minX = 0x7fff; int maxX = 0; int minY = 0x7fff; int maxY = 0; float avgX = 0; float avgY = 0; for (int j = 0; j < nPts; j++) { if (pts[j].x < minX) { minX = pts[j].x; } if (pts[j].y < minY) { minY = pts[j].y; } if (pts[j].x > maxX) { maxX = pts[j].x; } if (pts[j].y > maxY) { maxY = pts[j].y; } avgX += pts[j].x; avgY += pts[j].y; } avgX = avgX / nPts; avgY = avgY / nPts; if (maxX - minX < 30 && maxY - minY < 30) { red = 255; green = 0; blue = 255; LOGINFO3("circles_MSER (%d,%d) %d pts MATCH", (int)(avgX * 10+.5), (int)(avgY*10 +.5), nPts); } else { LOGINFO3("circles_MSER (%d,%d) %d pts (other)", (int)(avgX * 10+.5), (int)(avgY*10 +.5), nPts); } for (int j = 0; j < nPts; j++) { matRGB.at<cv::Vec3b>(pts[j])[0] = red; matRGB.at<cv::Vec3b>(pts[j])[1] = green; matRGB.at<cv::Vec3b>(pts[j])[2] = blue; } } } static void circles_Hough(cv::Mat matGray){ //GaussianBlur( matGray, matGray, cv::Size(9, 9), 2, 2 ); int threshold_value = 64; int max_BINARY_value = 255; //matGray.convertTo(matGray, -1, .5, 0); // contrast //threshold( matGray, matGray, threshold_value, max_BINARY_value, cv::THRESH_BINARY ); cv::vector<cv::Vec3f> circles; HoughCircles(matGray, circles, CV_HOUGH_GRADIENT, 2, 16, 200, 100, 4, 65 ); for( size_t i = 0; i < circles.size(); i++ ) { int x = cvRound(circles[i][0]); int y = cvRound(circles[i][1]); int radius = cvRound(circles[i][2]); cv::Point center(x, y); LOGINFO3("firepick_circles (%d,%d,%d)", x, y, radius); circle( matGray, center, 3, cv::Scalar(0,255,0), -1, 8, 0 ); // draw the circle center circle( matGray, center, radius, cv::Scalar(0,0,255), 3, 8, 0 ); // draw the circle outline } } const void* firepick_circles(JPG *pJPG) { CvMat* cvJpg = cvCreateMatHeader(1, pJPG->length, CV_8UC1); cvSetData(cvJpg, pJPG->pData, pJPG->length); IplImage *pCvImg = cvDecodeImage(cvJpg, CV_LOAD_IMAGE_COLOR); cv::Mat matRGB(pCvImg); cv::Mat matGray; cvtColor(matRGB, matGray, CV_RGB2GRAY); //circles_Hough(matGray); circles_MSER(matGray, matRGB); imwrite("/home/pi/camcv.bmp", matRGB); cvReleaseMatHeader(&cvJpg); return pJPG; } const char* firepick_status() { time_t current_time = time(NULL); char timebuf[70]; strcpy(timebuf, ctime(&current_time)); timebuf[strlen(timebuf)-1] = 0; const char *errorOrWarn = firelog_lastMessage(FIRELOG_WARN); if (strlen(errorOrWarn)) { return errorOrWarn; } sprintf(status_buffer, "{\n" " 'timestamp':'%s'\n" " 'message':'FirePick OK!',\n" " 'version':'FireFuse version %d.%d'\n" "}\n", timebuf, FireFuse_VERSION_MAJOR, FireFuse_VERSION_MINOR); return status_buffer; } int firepick_camera_daemon(JPG *pJPG) { int status = firepicam_create(0, NULL); LOGINFO1("firepick_camera_daemon start -> %d", status); for (;;) { JPG_Buffer buffer; buffer.pData = NULL; buffer.length = 0; status = firepicam_acquireImage(&buffer); pJPG->pData = buffer.pData; pJPG->length = buffer.length; } LOGINFO1("firepick_camera_daemon exit -> %d", status); firepicam_destroy(status); } <|endoftext|>
<commit_before>#include "SpriteComponent.h" #include "../../Logger.h" #include "../../Assets/TextureManager.h" #include "../TransformComponent.h" #include "../../Graphics/SpriteBatch.h" #include "../../Objects/Object.h" #include "SpritesheetComponent.h" #include "TextComponent.h" namespace star { SpriteComponent::SpriteComponent( const tstring& filepath, const tstring& spriteName, uint32 widthSegments, uint32 heightSegments ) : BaseComponent() , m_WidthSegments(widthSegments) , m_HeightSegments(heightSegments) , m_CurrentWidthSegment(0) , m_CurrentHeightSegment(0) , m_FilePath(filepath) , m_SpriteName(spriteName) , m_SpriteInfo(nullptr) { m_SpriteInfo = new SpriteInfo(); } void SpriteComponent::InitializeComponent() { if(m_pParentObject->HasComponent<SpritesheetComponent>(this) || m_pParentObject->HasComponent<TextComponent>(this)) { Logger::GetInstance()->Log(false, _T("Object '") + m_pParentObject->GetName() + _T("': Can't add a SpriteComponent when already \ having a Spritesheet- or TextComponent.")); m_pParentObject->RemoveComponent(this); } else { TextureManager::GetInstance()->LoadTexture( m_FilePath.GetAssetsPath(), m_SpriteName ); m_Dimensions.x = TextureManager::GetInstance()-> GetTextureDimensions(m_SpriteName).x / m_WidthSegments; m_Dimensions.y = TextureManager::GetInstance()-> GetTextureDimensions(m_SpriteName).y / m_HeightSegments; GetTransform()->SetDimensionsSafe(m_Dimensions); CreateUVCoords(); FillSpriteInfo(); } } void SpriteComponent::FillSpriteInfo() { m_SpriteInfo->textureID = TextureManager::GetInstance()->GetTextureID(m_SpriteName); m_SpriteInfo->vertices = vec2(m_Dimensions.x, m_Dimensions.y); } SpriteComponent::~SpriteComponent() { delete m_SpriteInfo; } void SpriteComponent::CreateUVCoords() { float32 startX = float32(m_CurrentWidthSegment) / float32(m_WidthSegments); float32 endX = 1.0f / m_WidthSegments; float32 startY = float32(m_CurrentHeightSegment) / float32(m_HeightSegments); float32 endY = 1.0f / m_HeightSegments; SetUVCoords(vec4(startX, startY, endX, endY)); } void SpriteComponent::SetUVCoords(const vec4& coords) { m_SpriteInfo->uvCoords = coords; } void SpriteComponent::Draw() { m_SpriteInfo->transformPtr = GetTransform(); SpriteBatch::GetInstance()->AddSpriteToQueue(m_SpriteInfo); } void SpriteComponent::Update(const Context & context) { //[COMMENT] Temp hotfix! #ifdef ANDROID FillSpriteInfo(); #endif } bool SpriteComponent::CheckCulling( float left, float right, float top, float bottom ) const { //Always draw hudObjects if(m_SpriteInfo->bIsHud) { return true; } float32 spriteWidth, spriteHeight; pos objectPos = GetTransform()->GetWorldPosition(); if(m_SpriteInfo->bIsHud) { objectPos.x += left; objectPos.y += bottom; } spriteWidth = float32(GetWidth()) * GetTransform()->GetWorldScale().x; spriteHeight = float32(GetHeight()) * GetTransform()->GetWorldScale().y; float32 objRight = objectPos.x + spriteWidth; float32 objTop = objectPos.y + spriteHeight; return (objRight >= left && objectPos.x <= right) && (objTop >= bottom && objectPos.y <= top); } const tstring& SpriteComponent::GetFilePath() const { return m_FilePath.GetPath(); } const tstring& SpriteComponent::GetName() const { return m_SpriteName; } void SpriteComponent::SetCurrentSegment(uint32 widthSegment, uint32 heightSegment) { m_CurrentWidthSegment = widthSegment; m_CurrentHeightSegment = m_HeightSegments - heightSegment - 1; CreateUVCoords(); } void SpriteComponent::SetColorMultiplier(const Color & color) { m_SpriteInfo->colorMultiplier = color; } void SpriteComponent::SetHUDOptionEnabled(bool enabled) { m_SpriteInfo->bIsHud = enabled; } bool SpriteComponent::IsHUDOptionEnabled() const { return m_SpriteInfo->bIsHud; } void SpriteComponent::SetTexture( const tstring& filepath, const tstring& spriteName, uint32 widthSegments, uint32 heightSegments ) { m_Dimensions.x = 0; m_WidthSegments = widthSegments; m_CurrentWidthSegment = 0; m_Dimensions.y = 0; m_HeightSegments = heightSegments; m_CurrentHeightSegment = 0; m_FilePath = Filepath(filepath); m_SpriteName = spriteName; TextureManager::GetInstance()->LoadTexture(m_FilePath.GetAssetsPath(),m_SpriteName); m_Dimensions.x = TextureManager::GetInstance()->GetTextureDimensions(m_SpriteName).x / m_WidthSegments; m_Dimensions.y = TextureManager::GetInstance()->GetTextureDimensions(m_SpriteName).y / m_HeightSegments; GetTransform()->SetDimensionsSafe(m_Dimensions); CreateUVCoords(); FillSpriteInfo(); } } <commit_msg>Culling fix<commit_after>#include "SpriteComponent.h" #include "../../Logger.h" #include "../../Assets/TextureManager.h" #include "../TransformComponent.h" #include "../../Graphics/SpriteBatch.h" #include "../../Objects/Object.h" #include "SpritesheetComponent.h" #include "TextComponent.h" namespace star { SpriteComponent::SpriteComponent( const tstring& filepath, const tstring& spriteName, uint32 widthSegments, uint32 heightSegments ) : BaseComponent() , m_WidthSegments(widthSegments) , m_HeightSegments(heightSegments) , m_CurrentWidthSegment(0) , m_CurrentHeightSegment(0) , m_FilePath(filepath) , m_SpriteName(spriteName) , m_SpriteInfo(nullptr) { m_SpriteInfo = new SpriteInfo(); } void SpriteComponent::InitializeComponent() { if(m_pParentObject->HasComponent<SpritesheetComponent>(this) || m_pParentObject->HasComponent<TextComponent>(this)) { Logger::GetInstance()->Log(false, _T("Object '") + m_pParentObject->GetName() + _T("': Can't add a SpriteComponent when already \ having a Spritesheet- or TextComponent.")); m_pParentObject->RemoveComponent(this); } else { TextureManager::GetInstance()->LoadTexture( m_FilePath.GetAssetsPath(), m_SpriteName ); m_Dimensions.x = TextureManager::GetInstance()-> GetTextureDimensions(m_SpriteName).x / m_WidthSegments; m_Dimensions.y = TextureManager::GetInstance()-> GetTextureDimensions(m_SpriteName).y / m_HeightSegments; GetTransform()->SetDimensionsSafe(m_Dimensions); CreateUVCoords(); FillSpriteInfo(); } } void SpriteComponent::FillSpriteInfo() { m_SpriteInfo->textureID = TextureManager::GetInstance()->GetTextureID(m_SpriteName); m_SpriteInfo->vertices = vec2(m_Dimensions.x, m_Dimensions.y); } SpriteComponent::~SpriteComponent() { delete m_SpriteInfo; } void SpriteComponent::CreateUVCoords() { float32 startX = float32(m_CurrentWidthSegment) / float32(m_WidthSegments); float32 endX = 1.0f / m_WidthSegments; float32 startY = float32(m_CurrentHeightSegment) / float32(m_HeightSegments); float32 endY = 1.0f / m_HeightSegments; SetUVCoords(vec4(startX, startY, endX, endY)); } void SpriteComponent::SetUVCoords(const vec4& coords) { m_SpriteInfo->uvCoords = coords; } void SpriteComponent::Draw() { m_SpriteInfo->transformPtr = GetTransform(); SpriteBatch::GetInstance()->AddSpriteToQueue(m_SpriteInfo); } void SpriteComponent::Update(const Context & context) { //[COMMENT] Temp hotfix! #ifdef ANDROID FillSpriteInfo(); #endif } bool SpriteComponent::CheckCulling( float left, float right, float top, float bottom ) const { //Always draw hudObjects if(m_SpriteInfo->bIsHud) { return true; } float32 spriteWidth, spriteHeight; pos objectPos = GetTransform()->GetWorldPosition(); if(m_SpriteInfo->bIsHud) { objectPos.x += left; objectPos.y += bottom; } spriteWidth = float32(GetWidth()) * GetTransform()->GetWorldScale().x; spriteHeight = float32(GetHeight()) * GetTransform()->GetWorldScale().y; float32 objRight = objectPos.x + spriteWidth; float32 objTop = objectPos.y + spriteHeight; return (objectPos.x <= right && objRight >= left) && (objectPos.y <= top && objTop >= bottom); } const tstring& SpriteComponent::GetFilePath() const { return m_FilePath.GetPath(); } const tstring& SpriteComponent::GetName() const { return m_SpriteName; } void SpriteComponent::SetCurrentSegment(uint32 widthSegment, uint32 heightSegment) { m_CurrentWidthSegment = widthSegment; m_CurrentHeightSegment = m_HeightSegments - heightSegment - 1; CreateUVCoords(); } void SpriteComponent::SetColorMultiplier(const Color & color) { m_SpriteInfo->colorMultiplier = color; } void SpriteComponent::SetHUDOptionEnabled(bool enabled) { m_SpriteInfo->bIsHud = enabled; } bool SpriteComponent::IsHUDOptionEnabled() const { return m_SpriteInfo->bIsHud; } void SpriteComponent::SetTexture( const tstring& filepath, const tstring& spriteName, uint32 widthSegments, uint32 heightSegments ) { m_Dimensions.x = 0; m_WidthSegments = widthSegments; m_CurrentWidthSegment = 0; m_Dimensions.y = 0; m_HeightSegments = heightSegments; m_CurrentHeightSegment = 0; m_FilePath = Filepath(filepath); m_SpriteName = spriteName; TextureManager::GetInstance()->LoadTexture(m_FilePath.GetAssetsPath(),m_SpriteName); m_Dimensions.x = TextureManager::GetInstance()->GetTextureDimensions(m_SpriteName).x / m_WidthSegments; m_Dimensions.y = TextureManager::GetInstance()->GetTextureDimensions(m_SpriteName).y / m_HeightSegments; GetTransform()->SetDimensionsSafe(m_Dimensions); CreateUVCoords(); FillSpriteInfo(); } } <|endoftext|>
<commit_before>#include "options.hpp" #include <tclap/CmdLine.h> using namespace std; using namespace TCLAP; void Options::parse(int argc, char** argv) try { CmdLine cmd("Distributed Systems Emulator", ' ', "0.0.1"); vector<string> commands{"help", "status", "start", "terminate", "list", "join", "depart", "query", "insert", "delete"}; ValuesConstraint<string> allowed_commands(commands); UnlabeledValueArg<string> command("command", "Command to be executed by the Distributed Systems Emulator Daemon (dsemud)", true, "help", &allowed_commands, cmd); UnlabeledMultiArg<string> parameters("parameters", "Parameters passed to the executed command", false, "list of parameters", cmd, true); cmd.parse(argc, argv); if (command.getValue() == "help") cmd.getOutput()->usage(cmd); } catch (const ArgException& e) { } <commit_msg>cli: Refine help message<commit_after>#include "options.hpp" #include <tclap/CmdLine.h> using namespace std; using namespace TCLAP; void Options::parse(int argc, char** argv) try { CmdLine cmd("Distributed Systems Emulator", ' ', "0.0.1"); vector<string> commands{"help", "status", "start", "terminate", "list", "join", "depart", "query", "insert", "delete"}; ValuesConstraint<string> allowed_commands(commands); UnlabeledValueArg<string> command("command", "Command to be executed by the Distributed Systems Emulator Daemon (dsemud).\n" "Use 'dsemu help <command>' to see usage for each command.", true, "help", &allowed_commands, cmd); UnlabeledMultiArg<string> parameters("parameters", "Parameters passed to the executed command.", false, "parameters", cmd, true); cmd.parse(argc, argv); if (command.getValue() == "help") cmd.getOutput()->usage(cmd); } catch (const ArgException& e) { } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Stanford University * * 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF 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. */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/param.h> #include <sys/types.h> #include <string> #include <iostream> using namespace std; #include <ori/debug.h> #include <ori/repo.h> #include <ori/localrepo.h> #include <ori/server.h> #include "fuse_cmd.h" LocalRepo repository; /******************************************************************** * * * Command Infrastructure * * ********************************************************************/ #define CMD_NEED_REPO 1 #define CMD_FUSE_ENABLED 2 #define CMD_FUSE_ONLY 4 typedef struct Cmd { const char *name; const char *desc; int (*cmd)(int argc, const char *argv[]); void (*usage)(void); int flags; } Cmd; // General Operations int cmd_addkey(int argc, const char *argv[]); int cmd_branches(int argc, const char *argv[]); int cmd_branch(int argc, const char *argv[]); int cmd_checkout(int argc, const char *argv[]); int cmd_clone(int argc, const char *argv[]); void usage_commit(void); int cmd_commit(int argc, const char *argv[]); int cmd_filelog(int argc, const char *argv[]); int cmd_findheads(int argc, const char *argv[]); int cmd_gc(int argc, const char *argv[]); void usage_graft(void); int cmd_graft(int argc, const char *argv[]); int cmd_init(int argc, const char *argv[]); int cmd_listkeys(int argc, const char *argv[]); int cmd_log(int argc, const char *argv[]); int cmd_merge(int argc, const char *argv[]); int cmd_pull(int argc, const char *argv[]); int cmd_rebuildindex(int argc, const char *argv[]); int cmd_rebuildrefs(int argc, const char *argv[]); int cmd_remote(int argc, const char *argv[]); int cmd_removekey(int argc, const char *argv[]); int cmd_setkey(int argc, const char *argv[]); int cmd_show(int argc, const char *argv[]); int cmd_snapshot(int argc, const char *argv[]); int cmd_snapshots(int argc, const char *argv[]); int cmd_status(int argc, const char *argv[]); int cmd_tip(int argc, const char *argv[]); int cmd_treediff(int argc, const char *argv[]); int cmd_verify(int argc, const char *argv[]); // Debug Operations int cmd_catobj(int argc, const char *argv[]); // Debug int cmd_dumpobj(int argc, const char *argv[]); // Debug int cmd_fsck(int argc, const char *argv[]); int cmd_listobj(int argc, const char *argv[]); // Debug int cmd_refcount(int argc, const char *argv[]); // Debug int cmd_stats(int argc, const char *argv[]); // Debug int cmd_purgeobj(int argc, const char *argv[]); // Debug int cmd_purgecommit(int argc, const char *argv[]); int cmd_stripmetadata(int argc, const char *argv[]); // Debug int cmd_sshserver(int argc, const char *argv[]); // Internal int cmd_sshclient(int argc, const char *argv[]); // Debug #if !defined(WITHOUT_MDNS) int cmd_mdnsserver(int argc, const char *argv[]); // Debug #endif int cmd_httpclient(int argc, const char *argv[]); // Debug static int cmd_help(int argc, const char *argv[]); static int cmd_selftest(int argc, const char *argv[]); static Cmd commands[] = { { "addkey", "Add a trusted public key to the repository", cmd_addkey, NULL, CMD_NEED_REPO, }, { "branch", "Set or print current branch", cmd_branch, NULL, CMD_NEED_REPO, }, { "branches", "List all available branches", cmd_branches, NULL, CMD_NEED_REPO, }, { "checkout", "Checkout a revision of the repository", cmd_checkout, NULL, CMD_NEED_REPO, }, { "clone", "Clone a repository into the local directory", cmd_clone, NULL, 0, }, { "commit", "Commit changes into the repository", cmd_commit, usage_commit, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "filelog", "Display a log of commits to the repository for the specified file", cmd_filelog, NULL, CMD_NEED_REPO, }, { "findheads", "Find lost heads", cmd_findheads, NULL, CMD_NEED_REPO, }, { "gc", "Reclaim unused space", cmd_gc, NULL, CMD_NEED_REPO, }, { "graft", "Graft a subtree from a repository into the local repository", cmd_graft, usage_graft, CMD_NEED_REPO, }, { "help", "Show help for a given topic", cmd_help, NULL, 0, }, { "init", "Initialize the repository", cmd_init, NULL, 0, }, { "listkeys", "Display a list of trusted public keys", cmd_listkeys, NULL, CMD_NEED_REPO, }, { "log", "Display a log of commits to the repository", cmd_log, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "merge", "Merge two heads", cmd_merge, NULL, CMD_NEED_REPO, }, { "pull", "Pull changes from a repository", cmd_pull, NULL, CMD_NEED_REPO, }, { "purgecommit", "Purge commit", cmd_purgecommit, NULL, CMD_NEED_REPO, }, { "rebuildindex", "Rebuild index", cmd_rebuildindex, NULL, CMD_NEED_REPO, }, { "rebuildrefs", "Rebuild references", cmd_rebuildrefs, NULL, CMD_NEED_REPO, }, { "remote", "Remote connection management", cmd_remote, NULL, CMD_NEED_REPO, }, { "removekey", "Remove a public key from the repository", cmd_removekey, NULL, CMD_NEED_REPO, }, { "setkey", "Set the repository private key for signing commits", cmd_setkey, NULL, CMD_NEED_REPO, }, { "show", "Show repository information", cmd_show, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "snapshot", "Create a repository snapshot", cmd_snapshot, NULL, CMD_NEED_REPO, }, { "snapshots", "List all snapshots available in the repository", cmd_snapshots, NULL, CMD_NEED_REPO, }, { "status", "Scan for changes since last commit", cmd_status, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "tip", "Print the latest commit on this branch", cmd_tip, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "treediff", "Compare two commits", cmd_treediff, NULL, CMD_NEED_REPO, }, { "verify", "Verify the repository", cmd_verify, NULL, CMD_NEED_REPO, }, /* Internal (always hidden) */ { "sshserver", NULL, // "Run a simple stdin/out server, intended for SSH access", cmd_sshserver, NULL, 0, }, /* Debugging */ { "catobj", "Print an object from the repository (DEBUG)", cmd_catobj, NULL, CMD_NEED_REPO, }, { "dumpobj", "Print the structured representation of a repository object (DEBUG)", cmd_dumpobj, NULL, CMD_NEED_REPO, }, { "fsck", "Check internal state of FUSE file system (DEBUG).", cmd_fsck, NULL, CMD_FUSE_ONLY, }, { "listobj", "List objects (DEBUG)", cmd_listobj, NULL, CMD_NEED_REPO, }, { "refcount", "Print the reference count for all objects (DEBUG)", cmd_refcount, NULL, CMD_NEED_REPO, }, { "stats", "Print repository statistics (DEBUG)", cmd_stats, NULL, CMD_NEED_REPO, }, { "purgeobj", "Purge object (DEBUG)", cmd_purgeobj, NULL, CMD_NEED_REPO, }, { "stripmetadata", "Strip all object metadata including backreferences (DEBUG)", cmd_stripmetadata, NULL, CMD_NEED_REPO, }, { "httpclient", "Connect to a server via HTTP (DEBUG)", cmd_httpclient, NULL, 0, }, { "sshclient", "Connect to a server via SSH (DEBUG)", cmd_sshclient, NULL, 0, }, #if !defined(WITHOUT_MDNS) { "mdnsserver", "Run the mDNS server (DEBUG)", cmd_mdnsserver, NULL, 0, }, #endif { "selftest", "Built-in unit tests (DEBUG)", cmd_selftest, NULL, 0, }, { NULL, NULL, NULL, NULL } }; static int lookupcmd(const char *cmd) { int i; for (i = 0; commands[i].name != NULL; i++) { if (strcmp(commands[i].name, cmd) == 0) return i; } return -1; } int util_selftest(void); int LRUCache_selfTest(void); int Key_selfTest(void); static int cmd_selftest(int argc, const char *argv[]) { int result = 0; result += util_selftest(); result += LRUCache_selfTest(); result += Key_selfTest(); if (result != 0) { cout << -result << " errors occurred." << endl; } return 0; } static int cmd_help(int argc, const char *argv[]) { int i = 0; if (argc >= 2) { i = lookupcmd(argv[1]); if (i != -1 && commands[i].usage != NULL) { commands[i].usage(); return 0; } if (i == -1) { printf("Unknown command '%s'\n", argv[1]); } else { printf("No help for command '%s'\n", argv[1]); return 0; } } for (i = 0; commands[i].name != NULL; i++) { if (commands[i].desc != NULL) printf("%-20s %s\n", commands[i].name, commands[i].desc); } return 0; } int main(int argc, char *argv[]) { bool has_repo = false; int idx; if (argc == 1) { return cmd_help(0, NULL); } idx = lookupcmd(argv[1]); if (idx == -1) { printf("Unknown command '%s'\n", argv[1]); cmd_help(0, NULL); return 1; } // Open the repository for all command except the following if (commands[idx].flags & CMD_NEED_REPO) { if (repository.open()) { has_repo = true; if (ori_open_log(&repository) < 0) { printf("Couldn't open log!\n"); exit(1); } } } if (commands[idx].flags & CMD_FUSE_ONLY) { if (!OF_HasFuse()) { printf("FUSE required for this command!\n"); exit(1); } } if (commands[idx].flags & CMD_FUSE_ENABLED) { if (OF_HasFuse()) has_repo = true; } if (commands[idx].flags & CMD_NEED_REPO) { if (!has_repo) { printf("No repository found!\n"); exit(1); } } LOG("Executing '%s'", argv[1]); return commands[idx].cmd(argc-1, (const char **)argv+1); } <commit_msg>Hide debug-only commands in release builds.<commit_after>/* * Copyright (c) 2012 Stanford University * * 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF 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. */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/param.h> #include <sys/types.h> #include <string> #include <iostream> using namespace std; #include <ori/debug.h> #include <ori/repo.h> #include <ori/localrepo.h> #include <ori/server.h> #include "fuse_cmd.h" LocalRepo repository; /******************************************************************** * * * Command Infrastructure * * ********************************************************************/ #define CMD_NEED_REPO 1 #define CMD_FUSE_ENABLED 2 #define CMD_FUSE_ONLY 4 #define CMD_DEBUG 8 typedef struct Cmd { const char *name; const char *desc; int (*cmd)(int argc, const char *argv[]); void (*usage)(void); int flags; } Cmd; // General Operations int cmd_addkey(int argc, const char *argv[]); int cmd_branches(int argc, const char *argv[]); int cmd_branch(int argc, const char *argv[]); int cmd_checkout(int argc, const char *argv[]); int cmd_clone(int argc, const char *argv[]); void usage_commit(void); int cmd_commit(int argc, const char *argv[]); int cmd_filelog(int argc, const char *argv[]); int cmd_findheads(int argc, const char *argv[]); int cmd_gc(int argc, const char *argv[]); void usage_graft(void); int cmd_graft(int argc, const char *argv[]); int cmd_init(int argc, const char *argv[]); int cmd_listkeys(int argc, const char *argv[]); int cmd_log(int argc, const char *argv[]); int cmd_merge(int argc, const char *argv[]); int cmd_pull(int argc, const char *argv[]); int cmd_rebuildindex(int argc, const char *argv[]); int cmd_rebuildrefs(int argc, const char *argv[]); int cmd_remote(int argc, const char *argv[]); int cmd_removekey(int argc, const char *argv[]); int cmd_setkey(int argc, const char *argv[]); int cmd_show(int argc, const char *argv[]); int cmd_snapshot(int argc, const char *argv[]); int cmd_snapshots(int argc, const char *argv[]); int cmd_status(int argc, const char *argv[]); int cmd_tip(int argc, const char *argv[]); int cmd_treediff(int argc, const char *argv[]); int cmd_verify(int argc, const char *argv[]); // Debug Operations int cmd_catobj(int argc, const char *argv[]); // Debug int cmd_dumpobj(int argc, const char *argv[]); // Debug int cmd_fsck(int argc, const char *argv[]); int cmd_listobj(int argc, const char *argv[]); // Debug int cmd_refcount(int argc, const char *argv[]); // Debug int cmd_stats(int argc, const char *argv[]); // Debug int cmd_purgeobj(int argc, const char *argv[]); // Debug int cmd_purgecommit(int argc, const char *argv[]); int cmd_stripmetadata(int argc, const char *argv[]); // Debug int cmd_sshserver(int argc, const char *argv[]); // Internal int cmd_sshclient(int argc, const char *argv[]); // Debug #if !defined(WITHOUT_MDNS) int cmd_mdnsserver(int argc, const char *argv[]); // Debug #endif int cmd_httpclient(int argc, const char *argv[]); // Debug static int cmd_help(int argc, const char *argv[]); static int cmd_selftest(int argc, const char *argv[]); static Cmd commands[] = { { "addkey", "Add a trusted public key to the repository", cmd_addkey, NULL, CMD_NEED_REPO, }, { "branch", "Set or print current branch", cmd_branch, NULL, CMD_NEED_REPO, }, { "branches", "List all available branches", cmd_branches, NULL, CMD_NEED_REPO, }, { "checkout", "Checkout a revision of the repository", cmd_checkout, NULL, CMD_NEED_REPO, }, { "clone", "Clone a repository into the local directory", cmd_clone, NULL, 0, }, { "commit", "Commit changes into the repository", cmd_commit, usage_commit, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "filelog", "Display a log of commits to the repository for the specified file", cmd_filelog, NULL, CMD_NEED_REPO, }, { "findheads", "Find lost heads", cmd_findheads, NULL, CMD_NEED_REPO, }, { "gc", "Reclaim unused space", cmd_gc, NULL, CMD_NEED_REPO, }, { "graft", "Graft a subtree from a repository into the local repository", cmd_graft, usage_graft, CMD_NEED_REPO, }, { "help", "Show help for a given topic", cmd_help, NULL, 0, }, { "init", "Initialize the repository", cmd_init, NULL, 0, }, { "listkeys", "Display a list of trusted public keys", cmd_listkeys, NULL, CMD_NEED_REPO, }, { "log", "Display a log of commits to the repository", cmd_log, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "merge", "Merge two heads", cmd_merge, NULL, CMD_NEED_REPO, }, { "pull", "Pull changes from a repository", cmd_pull, NULL, CMD_NEED_REPO, }, { "purgecommit", "Purge commit", cmd_purgecommit, NULL, CMD_NEED_REPO, }, { "rebuildindex", "Rebuild index", cmd_rebuildindex, NULL, CMD_NEED_REPO, }, { "rebuildrefs", "Rebuild references", cmd_rebuildrefs, NULL, CMD_NEED_REPO, }, { "remote", "Remote connection management", cmd_remote, NULL, CMD_NEED_REPO, }, { "removekey", "Remove a public key from the repository", cmd_removekey, NULL, CMD_NEED_REPO, }, { "setkey", "Set the repository private key for signing commits", cmd_setkey, NULL, CMD_NEED_REPO, }, { "show", "Show repository information", cmd_show, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "snapshot", "Create a repository snapshot", cmd_snapshot, NULL, CMD_NEED_REPO, }, { "snapshots", "List all snapshots available in the repository", cmd_snapshots, NULL, CMD_NEED_REPO, }, { "status", "Scan for changes since last commit", cmd_status, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "tip", "Print the latest commit on this branch", cmd_tip, NULL, CMD_NEED_REPO | CMD_FUSE_ENABLED, }, { "treediff", "Compare two commits", cmd_treediff, NULL, CMD_NEED_REPO, }, { "verify", "Verify the repository", cmd_verify, NULL, CMD_NEED_REPO, }, /* Internal (always hidden) */ { "sshserver", NULL, // "Run a simple stdin/out server, intended for SSH access", cmd_sshserver, NULL, 0, }, /* Debugging */ { "catobj", "Print an object from the repository (DEBUG)", cmd_catobj, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "dumpobj", "Print the structured representation of a repository object (DEBUG)", cmd_dumpobj, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "fsck", "Check internal state of FUSE file system (DEBUG).", cmd_fsck, NULL, CMD_FUSE_ONLY | CMD_DEBUG, }, { "listobj", "List objects (DEBUG)", cmd_listobj, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "refcount", "Print the reference count for all objects (DEBUG)", cmd_refcount, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "stats", "Print repository statistics (DEBUG)", cmd_stats, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "purgeobj", "Purge object (DEBUG)", cmd_purgeobj, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "stripmetadata", "Strip all object metadata including backreferences (DEBUG)", cmd_stripmetadata, NULL, CMD_NEED_REPO | CMD_DEBUG, }, { "httpclient", "Connect to a server via HTTP (DEBUG)", cmd_httpclient, NULL, CMD_DEBUG, }, { "sshclient", "Connect to a server via SSH (DEBUG)", cmd_sshclient, NULL, CMD_DEBUG, }, #if !defined(WITHOUT_MDNS) { "mdnsserver", "Run the mDNS server (DEBUG)", cmd_mdnsserver, NULL, CMD_DEBUG, }, #endif { "selftest", "Built-in unit tests (DEBUG)", cmd_selftest, NULL, CMD_DEBUG, }, { NULL, NULL, NULL, NULL } }; static int lookupcmd(const char *cmd) { int i; for (i = 0; commands[i].name != NULL; i++) { if (strcmp(commands[i].name, cmd) == 0) return i; } return -1; } int util_selftest(void); int LRUCache_selfTest(void); int Key_selfTest(void); static int cmd_selftest(int argc, const char *argv[]) { int result = 0; result += util_selftest(); result += LRUCache_selfTest(); result += Key_selfTest(); if (result != 0) { cout << -result << " errors occurred." << endl; } return 0; } static int cmd_help(int argc, const char *argv[]) { int i = 0; if (argc >= 2) { i = lookupcmd(argv[1]); if (i != -1 && commands[i].usage != NULL) { commands[i].usage(); return 0; } if (i == -1) { printf("Unknown command '%s'\n", argv[1]); } else { printf("No help for command '%s'\n", argv[1]); return 0; } } for (i = 0; commands[i].name != NULL; i++) { #ifndef DEBUG if (commands[i].flags & CMD_DEBUG) continue; #endif /* DEBUG */ if (commands[i].desc != NULL) printf("%-20s %s\n", commands[i].name, commands[i].desc); } return 0; } int main(int argc, char *argv[]) { bool has_repo = false; int idx; if (argc == 1) { return cmd_help(0, NULL); } idx = lookupcmd(argv[1]); if (idx == -1) { printf("Unknown command '%s'\n", argv[1]); cmd_help(0, NULL); return 1; } // Open the repository for all command except the following if (commands[idx].flags & CMD_NEED_REPO) { if (repository.open()) { has_repo = true; if (ori_open_log(&repository) < 0) { printf("Couldn't open log!\n"); exit(1); } } } if (commands[idx].flags & CMD_FUSE_ONLY) { if (!OF_HasFuse()) { printf("FUSE required for this command!\n"); exit(1); } } if (commands[idx].flags & CMD_FUSE_ENABLED) { if (OF_HasFuse()) has_repo = true; } if (commands[idx].flags & CMD_NEED_REPO) { if (!has_repo) { printf("No repository found!\n"); exit(1); } } LOG("Executing '%s'", argv[1]); return commands[idx].cmd(argc-1, (const char **)argv+1); } <|endoftext|>
<commit_before>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #pragma once #include "ork/ork.hpp" #if ORK_USE_GLM # include "glm/fwd.hpp" #endif // ORK_USE_GLM namespace ork { /* From color.hpp */ enum class color_space; #if ORK_USE_GLM using color4 = glm::vec4; #endif // ORK_USE_GLM /* From command_line.hpp */ #if ORK_USE_BOOST class command_handler; #endif // ORK_USE_BOOST /* From distribution.hpp */ #if ORK_USE_BOOST class command_handler; class random; #endif // ORK_USE_BOOST template<typename T> class triangle_distribution; template<typename T> class trapezoid_distribution; /* From file_utils.hpp */ template<class functor, class iter_t, class sort> struct directory_executer; template<class functor, class search_type = flat_search, class sort_type = unsorted> struct iterate_directory; template<class T> struct directory_range; /* From filter.hpp */ #if ORK_USE_BOOST template<unsigned C> struct ring; template<unsigned order, unsigned inverse_alpha> struct butterworth; #endif // ORK_USE_BOOST } // namespace ork <commit_msg>Added geometry to fwd<commit_after>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #pragma once #include "ork/ork.hpp" #if ORK_USE_GLM # include "glm/fwd.hpp" #endif // ORK_USE_GLM namespace ork { /* From color.hpp */ enum class color_space; #if ORK_USE_GLM using color4 = glm::vec4; #endif // ORK_USE_GLM /* From command_line.hpp */ #if ORK_USE_BOOST class command_handler; #endif // ORK_USE_BOOST /* From distribution.hpp */ #if ORK_USE_BOOST class command_handler; class random; #endif // ORK_USE_BOOST template<typename T> class triangle_distribution; template<typename T> class trapezoid_distribution; /* From file_utils.hpp */ template<class functor, class iter_t, class sort> struct directory_executer; template<class functor, class search_type = flat_search, class sort_type = unsorted> struct iterate_directory; template<class T> struct directory_range; /* From filter.hpp */ #if ORK_USE_BOOST template<unsigned C> struct ring; template<unsigned order, unsigned inverse_alpha> struct butterworth; #endif // ORK_USE_BOOST /* From geometry.hpp */ enum class angle; template<angle> struct circle; namespace GLM { struct dunit3; class bounding_box; class interval; struct segment; class chain; namespace MC { struct view; struct rotated_view; } // namespace MC } // namespace GLM } // namespace ork <|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2010-2011 Matthias Kretz <[email protected]> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <limits> #include <algorithm> using namespace Vc; template<typename T> constexpr bool may_overflow() { return std::is_integral<T>::value && std::is_unsigned<T>::value; } template<typename T1, typename T2> struct is_conversion_exact { static constexpr bool is_T2_integer = std::is_integral<T2>::value; static constexpr bool is_T2_signed = is_T2_integer && std::is_signed<T2>::value; static constexpr bool is_float_int_conversion = std::is_floating_point<T1>::value && is_T2_integer; template <typename U, typename V> static constexpr bool can_represent(V x) { return x <= std::numeric_limits<U>::max() && x >= std::numeric_limits<U>::min(); } template<typename U> static constexpr U max() { return std::numeric_limits<U>::max() - U(1); } template<typename U> static constexpr U min() { return std::numeric_limits<U>::min() + U(1); } static constexpr bool for_value(T1 v) { return (!is_float_int_conversion && !is_T2_signed) || can_represent<T2>(v); } static constexpr bool for_plus_one(T1 v) { return (v <= max<T1>() || may_overflow<T1>()) && (v <= max<T2>() || may_overflow<T2>()) && for_value(v + 1); } static constexpr bool for_minus_one(T1 v) { return (v >= min<T1>() || may_overflow<T1>()) && (v >= min<T2>() || may_overflow<T2>()) && for_value(v - 1); } }; template<typename V1, typename V2> V2 makeReference(V2 reference) { reference.setZero(V2::IndexesFromZero() >= V1::Size); return reference; } template<typename V1, typename V2> void testNumber(double n) { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; constexpr T1 One = T1(1); // compare casts from T1 -> T2 with casts from V1 -> V2 const T1 n1 = static_cast<T1>(n); //std::cerr << "n1 = " << n1 << ", static_cast<T2>(n1) = " << static_cast<T2>(n1) << std::endl; if (is_conversion_exact<T1, T2>::for_value(n1)) { COMPARE(static_cast<V2>(V1(n1)), makeReference<V1>(V2(static_cast<T1>(n1)))) << "\n n1: " << n1 << "\n V1(n1): " << V1(n1) << "\n T2(n1): " << T2(n1) ; } if (is_conversion_exact<T1, T2>::for_plus_one(n1)) { COMPARE(static_cast<V2>(V1(n1) + One), makeReference<V1>(V2(static_cast<T2>(n1 + One)))) << "\n n1: " << n1; } if (is_conversion_exact<T1, T2>::for_minus_one(n1)) { COMPARE(static_cast<V2>(V1(n1) - One), makeReference<V1>(V2(static_cast<T2>(n1 - One)))) << "\n n1: " << n1; } } template<typename T> double maxHelper() { return static_cast<double>(std::numeric_limits<T>::max()); } template<> double maxHelper<int>() { const int intDigits = std::numeric_limits<int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((int(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<> double maxHelper<unsigned int>() { const int intDigits = std::numeric_limits<unsigned int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((unsigned(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<typename V1, typename V2> void testCast2() { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; const double max = std::min(maxHelper<T1>(), maxHelper<T2>()); const double min = std::max( std::numeric_limits<T1>::is_integer ? static_cast<double>(std::numeric_limits<T1>::min()) : static_cast<double>(-std::numeric_limits<T1>::max()), std::numeric_limits<T2>::is_integer ? static_cast<double>(std::numeric_limits<T2>::min()) : static_cast<double>(-std::numeric_limits<T2>::max()) ); testNumber<V1, V2>(-1.); testNumber<V1, V2>(0.); testNumber<V1, V2>(1.); testNumber<V1, V2>(2.); testNumber<V1, V2>(max); testNumber<V1, V2>(max / 4 + max / 2); testNumber<V1, V2>(max / 2); testNumber<V1, V2>(max / 4); testNumber<V1, V2>(min); V1 test(IndexesFromZero); COMPARE(static_cast<V2>(test), makeReference<V1>(V2::IndexesFromZero())); } template<typename T> void testCast() { testCast2<typename T::V1, typename T::V2>(); } #define _CONCAT(A, B) A ## _ ## B #define CONCAT(A, B) _CONCAT(A, B) template<typename T1, typename T2> struct T2Helper { typedef T1 V1; typedef T2 V2; }; void testmain() { #define TEST(v1, v2) \ typedef T2Helper<v1, v2> CONCAT(v1, v2); \ runTest(testCast<CONCAT(v1, v2)>) TEST(double_v, double_v); TEST(double_v, float_v); TEST(double_v, int_v); TEST(double_v, uint_v); //TEST(double_v, short_v); //TEST(double_v, ushort_v); TEST(float_v, double_v); TEST(float_v, float_v); TEST(float_v, int_v); TEST(float_v, uint_v); TEST(float_v, short_v); TEST(float_v, ushort_v); TEST(int_v, double_v); TEST(int_v, float_v); TEST(int_v, int_v); TEST(int_v, uint_v); TEST(int_v, short_v); TEST(int_v, ushort_v); TEST(uint_v, double_v); TEST(uint_v, float_v); TEST(uint_v, int_v); TEST(uint_v, uint_v); TEST(uint_v, short_v); TEST(uint_v, ushort_v); TEST(ushort_v, short_v); TEST(ushort_v, ushort_v); TEST(short_v, short_v); TEST(short_v, ushort_v); #undef TEST } <commit_msg>test that a full float_v can be worked on via double_vs<commit_after>/* This file is part of the Vc library. Copyright (C) 2010-2011 Matthias Kretz <[email protected]> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <limits> #include <algorithm> using namespace Vc; template<typename T> constexpr bool may_overflow() { return std::is_integral<T>::value && std::is_unsigned<T>::value; } template<typename T1, typename T2> struct is_conversion_exact { static constexpr bool is_T2_integer = std::is_integral<T2>::value; static constexpr bool is_T2_signed = is_T2_integer && std::is_signed<T2>::value; static constexpr bool is_float_int_conversion = std::is_floating_point<T1>::value && is_T2_integer; template <typename U, typename V> static constexpr bool can_represent(V x) { return x <= std::numeric_limits<U>::max() && x >= std::numeric_limits<U>::min(); } template<typename U> static constexpr U max() { return std::numeric_limits<U>::max() - U(1); } template<typename U> static constexpr U min() { return std::numeric_limits<U>::min() + U(1); } static constexpr bool for_value(T1 v) { return (!is_float_int_conversion && !is_T2_signed) || can_represent<T2>(v); } static constexpr bool for_plus_one(T1 v) { return (v <= max<T1>() || may_overflow<T1>()) && (v <= max<T2>() || may_overflow<T2>()) && for_value(v + 1); } static constexpr bool for_minus_one(T1 v) { return (v >= min<T1>() || may_overflow<T1>()) && (v >= min<T2>() || may_overflow<T2>()) && for_value(v - 1); } }; template<typename V1, typename V2> V2 makeReference(V2 reference) { reference.setZero(V2::IndexesFromZero() >= V1::Size); return reference; } template<typename V1, typename V2> void testNumber(double n) { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; constexpr T1 One = T1(1); // compare casts from T1 -> T2 with casts from V1 -> V2 const T1 n1 = static_cast<T1>(n); //std::cerr << "n1 = " << n1 << ", static_cast<T2>(n1) = " << static_cast<T2>(n1) << std::endl; if (is_conversion_exact<T1, T2>::for_value(n1)) { COMPARE(static_cast<V2>(V1(n1)), makeReference<V1>(V2(static_cast<T1>(n1)))) << "\n n1: " << n1 << "\n V1(n1): " << V1(n1) << "\n T2(n1): " << T2(n1) ; } if (is_conversion_exact<T1, T2>::for_plus_one(n1)) { COMPARE(static_cast<V2>(V1(n1) + One), makeReference<V1>(V2(static_cast<T2>(n1 + One)))) << "\n n1: " << n1; } if (is_conversion_exact<T1, T2>::for_minus_one(n1)) { COMPARE(static_cast<V2>(V1(n1) - One), makeReference<V1>(V2(static_cast<T2>(n1 - One)))) << "\n n1: " << n1; } } template<typename T> double maxHelper() { return static_cast<double>(std::numeric_limits<T>::max()); } template<> double maxHelper<int>() { const int intDigits = std::numeric_limits<int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((int(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<> double maxHelper<unsigned int>() { const int intDigits = std::numeric_limits<unsigned int>::digits; const int floatDigits = std::numeric_limits<float>::digits; return static_cast<double>(((unsigned(1) << floatDigits) - 1) << (intDigits - floatDigits)); } template<typename V1, typename V2> void testCast2() { typedef typename V1::EntryType T1; typedef typename V2::EntryType T2; const double max = std::min(maxHelper<T1>(), maxHelper<T2>()); const double min = std::max( std::numeric_limits<T1>::is_integer ? static_cast<double>(std::numeric_limits<T1>::min()) : static_cast<double>(-std::numeric_limits<T1>::max()), std::numeric_limits<T2>::is_integer ? static_cast<double>(std::numeric_limits<T2>::min()) : static_cast<double>(-std::numeric_limits<T2>::max()) ); testNumber<V1, V2>(-1.); testNumber<V1, V2>(0.); testNumber<V1, V2>(1.); testNumber<V1, V2>(2.); testNumber<V1, V2>(max); testNumber<V1, V2>(max / 4 + max / 2); testNumber<V1, V2>(max / 2); testNumber<V1, V2>(max / 4); testNumber<V1, V2>(min); V1 test(IndexesFromZero); COMPARE(static_cast<V2>(test), makeReference<V1>(V2::IndexesFromZero())); } template<typename T> void testCast() { testCast2<typename T::V1, typename T::V2>(); } #define _CONCAT(A, B) A ## _ ## B #define CONCAT(A, B) _CONCAT(A, B) template<typename T1, typename T2> struct T2Helper { typedef T1 V1; typedef T2 V2; }; void fullConversion() { float_v x = float_v::Random(); float_v r = static_cast<float_v>(0.1 * static_cast<double_v>(x)).rotated(double_v::Size); for (size_t i = double_v::Size; i < float_v::Size; i += double_v::Size) { float_v tmp = static_cast<float_v>(0.1 * static_cast<double_v>(x.shifted(double_v::Size))); r = r.shifted(double_v::Size, tmp); } for (size_t i = 0; i < float_v::Size; ++i) { COMPARE(r[i], static_cast<float>(x[i] * 0.1)) << "i = " << i; } } void testmain() { #define TEST(v1, v2) \ typedef T2Helper<v1, v2> CONCAT(v1, v2); \ runTest(testCast<CONCAT(v1, v2)>) TEST(double_v, double_v); TEST(double_v, float_v); TEST(double_v, int_v); TEST(double_v, uint_v); //TEST(double_v, short_v); //TEST(double_v, ushort_v); TEST(float_v, double_v); TEST(float_v, float_v); TEST(float_v, int_v); TEST(float_v, uint_v); TEST(float_v, short_v); TEST(float_v, ushort_v); TEST(int_v, double_v); TEST(int_v, float_v); TEST(int_v, int_v); TEST(int_v, uint_v); TEST(int_v, short_v); TEST(int_v, ushort_v); TEST(uint_v, double_v); TEST(uint_v, float_v); TEST(uint_v, int_v); TEST(uint_v, uint_v); TEST(uint_v, short_v); TEST(uint_v, ushort_v); TEST(ushort_v, short_v); TEST(ushort_v, ushort_v); TEST(short_v, short_v); TEST(short_v, ushort_v); #undef TEST runTest(fullConversion); } <|endoftext|>
<commit_before>#include "Rendering/Skybox.h" #include "Rendering/RenderContext.h" #include "Rendering/Renderer.h" #include "Rendering/GraphicsDriver.h" #include "Rendering/DrawItem.h" #include "Rendering/Texture.h" #include "Rendering/RenderPassProgram.h" #include "Rendering/Mesh.h" #include "Misc/Assert.h" namespace MAD { USkybox::USkybox(const eastl::string& inShaderPath, const eastl::string& inCubemapPath, const Vector3& inBoxDimensions) : m_skyboxDimensions(inBoxDimensions) , m_skyboxTransform(Matrix::CreateScale(inBoxDimensions.x, inBoxDimensions.y, inBoxDimensions.z)) { MAD_CHECK_DESC(InitializeSkybox(inShaderPath, inCubemapPath), "Error loading skybox\n"); } void USkybox::DrawSkybox() { auto& graphicsDriver = URenderContext::Get().GetGraphicsDriver(); const auto& gBufferPassDesc = URenderContext::Get().GetRenderer().GetGBufferPassDescriptor(); SPerDrawConstants skyboxDrawConstants; // Bind the program m_skyboxShader->SetProgramActive(graphicsDriver, 0); // Bind the input layout graphicsDriver.SetInputLayout(m_skyboxInputLayout); // Bind the vertex buffer m_skyboxMesh->m_gpuPositions.Bind(graphicsDriver, 0); graphicsDriver.SetIndexBuffer(m_skyboxMesh->m_gpuIndexBuffer, 0); // Set the light accumulation buffer as render target since we dont want that the skybox to be lit (remember to unbind the depth buffer as input incase previous steps needed it as a SRV) graphicsDriver.SetPixelShaderResource(nullptr, ETextureSlot::DepthBuffer); graphicsDriver.SetRenderTargets(&gBufferPassDesc.m_renderTargets[AsIntegral(ERenderTargetSlot::LightingBuffer)], 1, m_depthStencilView.Get()); graphicsDriver.SetDepthStencilState(m_depthStencilState, 0); // Upload sky box's scale matrix skyboxDrawConstants.m_objectToWorldMatrix = m_skyboxTransform; graphicsDriver.UpdateBuffer(EConstantBufferSlot::PerDraw, &skyboxDrawConstants, sizeof(skyboxDrawConstants)); // Bind the rasterizer state graphicsDriver.SetRasterizerState(m_boxRasterizerState); graphicsDriver.SetBlendState(m_skyboxBlendState); graphicsDriver.SetPixelShaderResource(m_boxCubeMapSRV, ETextureSlot::CubeMap); graphicsDriver.DrawIndexed(static_cast<UINT>(m_skyboxMesh->m_indexBuffer.size()), 0, 0); } bool USkybox::InitializeSkybox(const eastl::string& inShaderPath, const eastl::string& inCubemapPath) { eastl::shared_ptr<UTexture> boxCubeMapTex = UTexture::Load(inCubemapPath, true, false, D3D11_RESOURCE_MISC_TEXTURECUBE); m_boxCubeMapSRV = boxCubeMapTex->GetTexureResource(); MAD_CHECK_DESC(m_boxCubeMapSRV, "Error creating the shader resource view for the skybox cube map\n"); if (!m_boxCubeMapSRV) return false; m_skyboxShader = URenderPassProgram::Load(inShaderPath); MAD_CHECK_DESC(m_skyboxShader != nullptr, "Error loading the skybox shader program\n"); if (!m_skyboxShader) return false; m_skyboxInputLayout = UInputLayoutCache::GetInputLayout(EInputLayoutSemantic::Position); MAD_CHECK_DESC(m_skyboxInputLayout, "Error retrieving the skybox input layout\n"); if (!m_skyboxInputLayout) return false; m_depthStencilView = URenderContext::Get().GetRenderer().GetGBufferPassDescriptor().m_depthStencilView; MAD_CHECK_DESC(m_depthStencilView, "Error retrieving the g-buffer's depth buffer\n"); if (!m_depthStencilView) return false; m_depthStencilState = URenderContext::Get().GetRenderer().GetGBufferPassDescriptor().m_depthStencilState; m_boxRasterizerState = URenderContext::Get().GetGraphicsDriver().CreateRasterizerState(EFillMode::Solid, ECullMode::Front); MAD_CHECK_DESC(m_boxRasterizerState, "Error creating rasterizer state\n"); if (!m_boxRasterizerState) return false; m_skyboxBlendState = URenderContext::Get().GetGraphicsDriver().CreateBlendState(false); MAD_CHECK_DESC(m_skyboxBlendState, "Error creating blend state\n"); if (!m_skyboxBlendState) return false; // Initialize the position vertex buffer with the vertices of the entire box m_skyboxMesh = UMesh::Load("engine\\meshes\\primitives\\icosphere.obj"); MAD_CHECK_DESC(m_skyboxMesh != nullptr, "Error loading the skybox cube mesh\n"); if (!m_skyboxMesh) return false; return true; } }<commit_msg>Added graphics debugging event group for the sky sphere<commit_after>#include "Rendering/Skybox.h" #include "Rendering/RenderContext.h" #include "Rendering/Renderer.h" #include "Rendering/GraphicsDriver.h" #include "Rendering/DrawItem.h" #include "Rendering/Texture.h" #include "Rendering/RenderPassProgram.h" #include "Rendering/Mesh.h" #include "Misc/Assert.h" namespace MAD { USkybox::USkybox(const eastl::string& inShaderPath, const eastl::string& inCubemapPath, const Vector3& inBoxDimensions) : m_skyboxDimensions(inBoxDimensions) , m_skyboxTransform(Matrix::CreateScale(inBoxDimensions.x, inBoxDimensions.y, inBoxDimensions.z)) { MAD_CHECK_DESC(InitializeSkybox(inShaderPath, inCubemapPath), "Error loading skybox\n"); } void USkybox::DrawSkybox() { auto& graphicsDriver = URenderContext::Get().GetGraphicsDriver(); const auto& gBufferPassDesc = URenderContext::Get().GetRenderer().GetGBufferPassDescriptor(); SPerDrawConstants skyboxDrawConstants; graphicsDriver.StartEventGroup(L"Drawing Sky Sphere"); // Bind the program m_skyboxShader->SetProgramActive(graphicsDriver, 0); // Bind the input layout graphicsDriver.SetInputLayout(m_skyboxInputLayout); // Bind the vertex buffer m_skyboxMesh->m_gpuPositions.Bind(graphicsDriver, 0); graphicsDriver.SetIndexBuffer(m_skyboxMesh->m_gpuIndexBuffer, 0); // Set the light accumulation buffer as render target since we dont want that the skybox to be lit (remember to unbind the depth buffer as input incase previous steps needed it as a SRV) graphicsDriver.SetPixelShaderResource(nullptr, ETextureSlot::DepthBuffer); graphicsDriver.SetRenderTargets(&gBufferPassDesc.m_renderTargets[AsIntegral(ERenderTargetSlot::LightingBuffer)], 1, m_depthStencilView.Get()); graphicsDriver.SetDepthStencilState(m_depthStencilState, 0); // Upload sky box's scale matrix skyboxDrawConstants.m_objectToWorldMatrix = m_skyboxTransform; graphicsDriver.UpdateBuffer(EConstantBufferSlot::PerDraw, &skyboxDrawConstants, sizeof(skyboxDrawConstants)); // Bind the rasterizer state graphicsDriver.SetRasterizerState(m_boxRasterizerState); graphicsDriver.SetBlendState(m_skyboxBlendState); graphicsDriver.SetPixelShaderResource(m_boxCubeMapSRV, ETextureSlot::CubeMap); graphicsDriver.DrawIndexed(static_cast<UINT>(m_skyboxMesh->m_indexBuffer.size()), 0, 0); graphicsDriver.EndEventGroup(); } bool USkybox::InitializeSkybox(const eastl::string& inShaderPath, const eastl::string& inCubemapPath) { eastl::shared_ptr<UTexture> boxCubeMapTex = UTexture::Load(inCubemapPath, true, false, D3D11_RESOURCE_MISC_TEXTURECUBE); m_boxCubeMapSRV = boxCubeMapTex->GetTexureResource(); MAD_CHECK_DESC(m_boxCubeMapSRV, "Error creating the shader resource view for the skybox cube map\n"); if (!m_boxCubeMapSRV) return false; m_skyboxShader = URenderPassProgram::Load(inShaderPath); MAD_CHECK_DESC(m_skyboxShader != nullptr, "Error loading the skybox shader program\n"); if (!m_skyboxShader) return false; m_skyboxInputLayout = UInputLayoutCache::GetInputLayout(EInputLayoutSemantic::Position); MAD_CHECK_DESC(m_skyboxInputLayout, "Error retrieving the skybox input layout\n"); if (!m_skyboxInputLayout) return false; m_depthStencilView = URenderContext::Get().GetRenderer().GetGBufferPassDescriptor().m_depthStencilView; MAD_CHECK_DESC(m_depthStencilView, "Error retrieving the g-buffer's depth buffer\n"); if (!m_depthStencilView) return false; m_depthStencilState = URenderContext::Get().GetRenderer().GetGBufferPassDescriptor().m_depthStencilState; m_boxRasterizerState = URenderContext::Get().GetGraphicsDriver().CreateRasterizerState(EFillMode::Solid, ECullMode::Front); MAD_CHECK_DESC(m_boxRasterizerState, "Error creating rasterizer state\n"); if (!m_boxRasterizerState) return false; m_skyboxBlendState = URenderContext::Get().GetGraphicsDriver().CreateBlendState(false); MAD_CHECK_DESC(m_skyboxBlendState, "Error creating blend state\n"); if (!m_skyboxBlendState) return false; // Initialize the position vertex buffer with the vertices of the entire box m_skyboxMesh = UMesh::Load("engine\\meshes\\primitives\\icosphere.obj"); MAD_CHECK_DESC(m_skyboxMesh != nullptr, "Error loading the skybox cube mesh\n"); if (!m_skyboxMesh) return false; return true; } }<|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_SQRT_HPP #define STAN_MATH_PRIM_FUN_SQRT_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/functor/apply_scalar_unary.hpp> #include <stan/math/prim/functor/apply_vector_unary.hpp> #include <cmath> #include <complex> namespace stan { namespace math { /** * Structure to wrap `sqrt()` so that it can be vectorized. * * @tparam T type of variable * @param x variable * @return Square root of x. */ struct sqrt_fun { template <typename T> static inline T fun(const T& x) { using std::sqrt; return sqrt(x); } }; /** * Vectorized version of `sqrt()`. * * @tparam Container type of container * @param x container * @return Square root of each value in x. */ template <typename Container, require_not_container_st<std::is_arithmetic, Container>* = nullptr> inline auto sqrt(const Container& x) { return apply_scalar_unary<sqrt_fun, Container>::apply(x); } /** * Version of `sqrt()` that accepts std::vectors, Eigen Matrix/Array objects * or expressions, and containers of these. * * @tparam Container Type of x * @param x Container * @return Square root of each value in x. */ template <typename Container, require_container_st<std::is_arithmetic, Container>* = nullptr> inline auto sqrt(const Container& x) { return apply_vector_unary<Container>::apply( x, [](const auto& v) { return v.array().sqrt(); }); } namespace internal { /** * Return the square root of the complex argument. * * @tparam V value type of argument * @param[in] z argument * @return square root of the argument */ template <typename V> inline std::complex<V> complex_sqrt(const std::complex<V>& z) { auto m = sqrt(hypot(z.real(), z.imag())); auto at = 0.5 * atan2(z.imag(), z.real()); return {m * cos(at), m * sin(at)}; } } // namespace internal } // namespace math } // namespace stan #endif <commit_msg>add missing require to sqrt<commit_after>#ifndef STAN_MATH_PRIM_FUN_SQRT_HPP #define STAN_MATH_PRIM_FUN_SQRT_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/functor/apply_scalar_unary.hpp> #include <stan/math/prim/functor/apply_vector_unary.hpp> #include <cmath> #include <complex> namespace stan { namespace math { /** * Structure to wrap `sqrt()` so that it can be vectorized. * * @tparam T type of variable * @param x variable * @return Square root of x. */ struct sqrt_fun { template <typename T> static inline T fun(const T& x) { using std::sqrt; return sqrt(x); } }; /** * Vectorized version of `sqrt()`. * * @tparam Container type of container * @param x container * @return Square root of each value in x. */ template <typename Container, require_not_container_st<std::is_arithmetic, Container>* = nullptr, require_all_not_nonscalar_prim_or_rev_kernel_expression_t< Container>* = nullptr> inline auto sqrt(const Container& x) { return apply_scalar_unary<sqrt_fun, Container>::apply(x); } /** * Version of `sqrt()` that accepts std::vectors, Eigen Matrix/Array objects * or expressions, and containers of these. * * @tparam Container Type of x * @param x Container * @return Square root of each value in x. */ template <typename Container, require_container_st<std::is_arithmetic, Container>* = nullptr> inline auto sqrt(const Container& x) { return apply_vector_unary<Container>::apply( x, [](const auto& v) { return v.array().sqrt(); }); } namespace internal { /** * Return the square root of the complex argument. * * @tparam V value type of argument * @param[in] z argument * @return square root of the argument */ template <typename V> inline std::complex<V> complex_sqrt(const std::complex<V>& z) { auto m = sqrt(hypot(z.real(), z.imag())); auto at = 0.5 * atan2(z.imag(), z.real()); return {m * cos(at), m * sin(at)}; } } // namespace internal } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <QList> #include <QObject> #include <QTest> #include <QHttpEngine/QHttpParser> #include <QHttpEngine/QHttpSocket> #include <QHttpEngine/QIByteArray> typedef QList<QByteArray> QByteArrayList; Q_DECLARE_METATYPE(QHttpSocket::Method) Q_DECLARE_METATYPE(QHttpSocket::QQueryStringMap) Q_DECLARE_METATYPE(QHttpSocket::QHttpHeaderMap) const QIByteArray Key1 = "a"; const QByteArray Value1 = "b"; const QByteArray Line1 = Key1 + ": " + Value1; const QIByteArray Key2 = "c"; const QByteArray Value2 = "d"; const QByteArray Line2 = Key2 + ": " + Value2; class TestQHttpParser : public QObject { Q_OBJECT public: TestQHttpParser(); private Q_SLOTS: void testSplit_data(); void testSplit(); void testParsePath_data(); void testParsePath(); void testParseHeaderList_data(); void testParseHeaderList(); void testParseHeaders_data(); void testParseHeaders(); void testParseRequestHeaders_data(); void testParseRequestHeaders(); void testParseResponseHeaders_data(); void testParseResponseHeaders(); private: QHttpSocket::QHttpHeaderMap headers; }; TestQHttpParser::TestQHttpParser() { headers.insert(Key1, Value1); headers.insert(Key2, Value2); } void TestQHttpParser::testSplit_data() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArray>("delim"); QTest::addColumn<int>("maxSplit"); QTest::addColumn<QByteArrayList>("parts"); QTest::newRow("empty string") << QByteArray() << QByteArray(",") << 0 << (QByteArrayList() << ""); QTest::newRow("no delimiter") << QByteArray("a") << QByteArray(",") << 0 << (QByteArrayList() << "a"); QTest::newRow("delimiter") << QByteArray("a::b::c") << QByteArray("::") << 0 << (QByteArrayList() << "a" << "b" << "c"); QTest::newRow("empty parts") << QByteArray("a,,") << QByteArray(",") << 0 << (QByteArrayList() << "a" << "" << ""); QTest::newRow("maxSplit") << QByteArray("a,a,a") << QByteArray(",") << 1 << (QByteArrayList() << "a" << "a,a"); } void TestQHttpParser::testSplit() { QFETCH(QByteArray, data); QFETCH(QByteArray, delim); QFETCH(int, maxSplit); QFETCH(QByteArrayList, parts); QByteArrayList outParts; QHttpParser::split(data, delim, maxSplit, outParts); QCOMPARE(outParts, parts); } void TestQHttpParser::testParsePath_data() { QTest::addColumn<QByteArray>("rawPath"); QTest::addColumn<QString>("path"); QTest::addColumn<QHttpSocket::QQueryStringMap>("map"); QTest::newRow("no query string") << QByteArray("/path") << QString("/path") << QHttpSocket::QQueryStringMap(); QTest::newRow("single parameter") << QByteArray("/path?a=b") << QString("/path") << QHttpSocket::QQueryStringMap({{"a", "b"}}); } void TestQHttpParser::testParsePath() { QFETCH(QByteArray, rawPath); QFETCH(QString, path); QFETCH(QHttpSocket::QQueryStringMap, map); QString outPath; QHttpSocket::QQueryStringMap outMap; QVERIFY(QHttpParser::parsePath(rawPath, outPath, outMap)); QCOMPARE(path, outPath); QCOMPARE(map, outMap); } void TestQHttpParser::testParseHeaderList_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArrayList>("lines"); QTest::addColumn<QHttpSocket::QHttpHeaderMap>("headers"); QTest::newRow("empty line") << false << (QByteArrayList() << ""); QTest::newRow("multiple lines") << true << (QByteArrayList() << Line1 << Line2) << headers; } void TestQHttpParser::testParseHeaderList() { QFETCH(bool, success); QFETCH(QByteArrayList, lines); QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseHeaderList(lines, outHeaders), success); if (success) { QFETCH(QHttpSocket::QHttpHeaderMap, headers); QCOMPARE(outHeaders, headers); } } void TestQHttpParser::testParseHeaders_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArrayList>("parts"); QTest::newRow("empty headers") << false << QByteArray(""); QTest::newRow("simple GET request") << true << QByteArray("GET / HTTP/1.0") << (QByteArrayList() << "GET" << "/" << "HTTP/1.0"); } void TestQHttpParser::testParseHeaders() { QFETCH(bool, success); QFETCH(QByteArray, data); QByteArrayList outParts; QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseHeaders(data, outParts, outHeaders), success); if (success) { QFETCH(QByteArrayList, parts); QCOMPARE(outParts, parts); } } void TestQHttpParser::testParseRequestHeaders_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<QHttpSocket::Method>("method"); QTest::addColumn<QByteArray>("path"); QTest::newRow("bad HTTP version") << false << QByteArray("GET / HTTP/0.9"); QTest::newRow("GET request") << true << QByteArray("GET / HTTP/1.0") << QByteArray("GET") << QByteArray("/"); } void TestQHttpParser::testParseRequestHeaders() { QFETCH(bool, success); QFETCH(QByteArray, data); QHttpSocket::Method outMethod; QByteArray outPath; QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseRequestHeaders(data, outMethod, outPath, outHeaders), success); if (success) { QFETCH(QHttpSocket::Method, method); QFETCH(QByteArray, path); QCOMPARE(method, outMethod); QCOMPARE(path, outPath); } } void TestQHttpParser::testParseResponseHeaders_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("statusCode"); QTest::addColumn<QByteArray>("statusReason"); QTest::newRow("invalid status code") << false << QByteArray("HTTP/1.0 600 BAD RESPONSE"); QTest::newRow("404 response") << true << QByteArray("HTTP/1.0 404 NOT FOUND") << 404 << QByteArray("NOT FOUND"); } void TestQHttpParser::testParseResponseHeaders() { QFETCH(bool, success); QFETCH(QByteArray, data); int outStatusCode; QByteArray outStatusReason; QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseResponseHeaders(data, outStatusCode, outStatusReason, outHeaders), success); if (success) { QFETCH(int, statusCode); QFETCH(QByteArray, statusReason); QCOMPARE(statusCode, outStatusCode); QCOMPARE(statusReason, outStatusReason); } } QTEST_MAIN(TestQHttpParser) #include "TestQHttpParser.moc" <commit_msg>Fix incorrect parameter for QHttpParser test.<commit_after>/* * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <QList> #include <QObject> #include <QTest> #include <QHttpEngine/QHttpParser> #include <QHttpEngine/QHttpSocket> #include <QHttpEngine/QIByteArray> typedef QList<QByteArray> QByteArrayList; Q_DECLARE_METATYPE(QHttpSocket::Method) Q_DECLARE_METATYPE(QHttpSocket::QQueryStringMap) Q_DECLARE_METATYPE(QHttpSocket::QHttpHeaderMap) const QIByteArray Key1 = "a"; const QByteArray Value1 = "b"; const QByteArray Line1 = Key1 + ": " + Value1; const QIByteArray Key2 = "c"; const QByteArray Value2 = "d"; const QByteArray Line2 = Key2 + ": " + Value2; class TestQHttpParser : public QObject { Q_OBJECT public: TestQHttpParser(); private Q_SLOTS: void testSplit_data(); void testSplit(); void testParsePath_data(); void testParsePath(); void testParseHeaderList_data(); void testParseHeaderList(); void testParseHeaders_data(); void testParseHeaders(); void testParseRequestHeaders_data(); void testParseRequestHeaders(); void testParseResponseHeaders_data(); void testParseResponseHeaders(); private: QHttpSocket::QHttpHeaderMap headers; }; TestQHttpParser::TestQHttpParser() { headers.insert(Key1, Value1); headers.insert(Key2, Value2); } void TestQHttpParser::testSplit_data() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArray>("delim"); QTest::addColumn<int>("maxSplit"); QTest::addColumn<QByteArrayList>("parts"); QTest::newRow("empty string") << QByteArray() << QByteArray(",") << 0 << (QByteArrayList() << ""); QTest::newRow("no delimiter") << QByteArray("a") << QByteArray(",") << 0 << (QByteArrayList() << "a"); QTest::newRow("delimiter") << QByteArray("a::b::c") << QByteArray("::") << 0 << (QByteArrayList() << "a" << "b" << "c"); QTest::newRow("empty parts") << QByteArray("a,,") << QByteArray(",") << 0 << (QByteArrayList() << "a" << "" << ""); QTest::newRow("maxSplit") << QByteArray("a,a,a") << QByteArray(",") << 1 << (QByteArrayList() << "a" << "a,a"); } void TestQHttpParser::testSplit() { QFETCH(QByteArray, data); QFETCH(QByteArray, delim); QFETCH(int, maxSplit); QFETCH(QByteArrayList, parts); QByteArrayList outParts; QHttpParser::split(data, delim, maxSplit, outParts); QCOMPARE(outParts, parts); } void TestQHttpParser::testParsePath_data() { QTest::addColumn<QByteArray>("rawPath"); QTest::addColumn<QString>("path"); QTest::addColumn<QHttpSocket::QQueryStringMap>("map"); QTest::newRow("no query string") << QByteArray("/path") << QString("/path") << QHttpSocket::QQueryStringMap(); QTest::newRow("single parameter") << QByteArray("/path?a=b") << QString("/path") << QHttpSocket::QQueryStringMap({{"a", "b"}}); } void TestQHttpParser::testParsePath() { QFETCH(QByteArray, rawPath); QFETCH(QString, path); QFETCH(QHttpSocket::QQueryStringMap, map); QString outPath; QHttpSocket::QQueryStringMap outMap; QVERIFY(QHttpParser::parsePath(rawPath, outPath, outMap)); QCOMPARE(path, outPath); QCOMPARE(map, outMap); } void TestQHttpParser::testParseHeaderList_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArrayList>("lines"); QTest::addColumn<QHttpSocket::QHttpHeaderMap>("headers"); QTest::newRow("empty line") << false << (QByteArrayList() << ""); QTest::newRow("multiple lines") << true << (QByteArrayList() << Line1 << Line2) << headers; } void TestQHttpParser::testParseHeaderList() { QFETCH(bool, success); QFETCH(QByteArrayList, lines); QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseHeaderList(lines, outHeaders), success); if (success) { QFETCH(QHttpSocket::QHttpHeaderMap, headers); QCOMPARE(outHeaders, headers); } } void TestQHttpParser::testParseHeaders_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArrayList>("parts"); QTest::newRow("empty headers") << false << QByteArray(""); QTest::newRow("simple GET request") << true << QByteArray("GET / HTTP/1.0") << (QByteArrayList() << "GET" << "/" << "HTTP/1.0"); } void TestQHttpParser::testParseHeaders() { QFETCH(bool, success); QFETCH(QByteArray, data); QByteArrayList outParts; QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseHeaders(data, outParts, outHeaders), success); if (success) { QFETCH(QByteArrayList, parts); QCOMPARE(outParts, parts); } } void TestQHttpParser::testParseRequestHeaders_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<QHttpSocket::Method>("method"); QTest::addColumn<QByteArray>("path"); QTest::newRow("bad HTTP version") << false << QByteArray("GET / HTTP/0.9"); QTest::newRow("GET request") << true << QByteArray("GET / HTTP/1.0") << QHttpSocket::GET << QByteArray("/"); } void TestQHttpParser::testParseRequestHeaders() { QFETCH(bool, success); QFETCH(QByteArray, data); QHttpSocket::Method outMethod; QByteArray outPath; QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseRequestHeaders(data, outMethod, outPath, outHeaders), success); if (success) { QFETCH(QHttpSocket::Method, method); QFETCH(QByteArray, path); QCOMPARE(method, outMethod); QCOMPARE(path, outPath); } } void TestQHttpParser::testParseResponseHeaders_data() { QTest::addColumn<bool>("success"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("statusCode"); QTest::addColumn<QByteArray>("statusReason"); QTest::newRow("invalid status code") << false << QByteArray("HTTP/1.0 600 BAD RESPONSE"); QTest::newRow("404 response") << true << QByteArray("HTTP/1.0 404 NOT FOUND") << 404 << QByteArray("NOT FOUND"); } void TestQHttpParser::testParseResponseHeaders() { QFETCH(bool, success); QFETCH(QByteArray, data); int outStatusCode; QByteArray outStatusReason; QHttpSocket::QHttpHeaderMap outHeaders; QCOMPARE(QHttpParser::parseResponseHeaders(data, outStatusCode, outStatusReason, outHeaders), success); if (success) { QFETCH(int, statusCode); QFETCH(QByteArray, statusReason); QCOMPARE(statusCode, outStatusCode); QCOMPARE(statusReason, outStatusReason); } } QTEST_MAIN(TestQHttpParser) #include "TestQHttpParser.moc" <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <realm/db.hpp> #include <future> #include <windows.h> namespace realm { namespace _impl { class RealmCoordinator; namespace win32 { template <class T, void (*Initializer)(T&)> class SharedMemory { public: SharedMemory(LPCWSTR name) { //assume another process have already initialzied the shared memory bool shouldInit = false; m_mapped_file = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, name); auto error = GetLastError(); if (m_mapped_file == NULL) { m_mapped_file = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(T), name); error = GetLastError(); //init since this is the first process creating the shared memory shouldInit = true; } if (m_mapped_file == NULL) { throw std::system_error(error, std::system_category()); } LPVOID view = MapViewOfFile(m_mapped_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(T)); error = GetLastError(); if (view == NULL) { throw std::system_error(error, std::system_category()); } m_memory = reinterpret_cast<T*>(view); if (shouldInit) { try { Initializer(get()); } catch (...) { UnmapViewOfFile(m_memory); throw; } } } T& get() const noexcept { return *m_memory; } ~SharedMemory() { if (m_memory) { UnmapViewOfFile(m_memory); m_memory = nullptr; } if (m_mapped_file) { CloseHandle(m_mapped_file); m_mapped_file = nullptr; } } private: T* m_memory = nullptr; HANDLE m_mapped_file = nullptr; }; } class ExternalCommitHelper { public: ExternalCommitHelper(RealmCoordinator& parent); ~ExternalCommitHelper(); void notify_others(); private: void listen(); RealmCoordinator& m_parent; // The listener thread std::future<void> m_thread; win32::SharedMemory<util::InterprocessCondVar::SharedPart, util::InterprocessCondVar::init_shared_part> m_condvar_shared; util::InterprocessCondVar m_commit_available; util::InterprocessMutex m_mutex; bool m_keep_listening = true; }; } // namespace _impl } // namespace realm <commit_msg>fix formatting to make clang happy<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <realm/db.hpp> #include <future> #include <windows.h> namespace realm { namespace _impl { class RealmCoordinator; namespace win32 { template <class T, void (*Initializer)(T&)> class SharedMemory { public: SharedMemory(LPCWSTR name) { // assume another process have already initialzied the shared memory bool shouldInit = false; m_mapped_file = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, name); auto error = GetLastError(); if (m_mapped_file == NULL) { m_mapped_file = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(T), name); error = GetLastError(); // init since this is the first process creating the shared memory shouldInit = true; } if (m_mapped_file == NULL) { throw std::system_error(error, std::system_category()); } LPVOID view = MapViewOfFile(m_mapped_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(T)); error = GetLastError(); if (view == NULL) { throw std::system_error(error, std::system_category()); } m_memory = reinterpret_cast<T*>(view); if (shouldInit) { try { Initializer(get()); } catch (...) { UnmapViewOfFile(m_memory); throw; } } } T& get() const noexcept { return *m_memory; } ~SharedMemory() { if (m_memory) { UnmapViewOfFile(m_memory); m_memory = nullptr; } if (m_mapped_file) { CloseHandle(m_mapped_file); m_mapped_file = nullptr; } } private: T* m_memory = nullptr; HANDLE m_mapped_file = nullptr; }; } // namespace win32 class ExternalCommitHelper { public: ExternalCommitHelper(RealmCoordinator& parent); ~ExternalCommitHelper(); void notify_others(); private: void listen(); RealmCoordinator& m_parent; // The listener thread std::future<void> m_thread; win32::SharedMemory<util::InterprocessCondVar::SharedPart, util::InterprocessCondVar::init_shared_part> m_condvar_shared; util::InterprocessCondVar m_commit_available; util::InterprocessMutex m_mutex; bool m_keep_listening = true; }; } // namespace _impl } // namespace realm <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "core/app-template.hh" #include "core/distributed.hh" #include "core/future-util.hh" struct X { sstring echo(sstring arg) { return arg; } future<> stop() { return make_ready_future<>(); } }; template <typename T, typename Func> future<> do_with_distributed(Func&& func) { auto x = make_shared<distributed<T>>(); return func(*x).finally([x] { return x->stop(); }).finally([x]{}); } future<> test_that_each_core_gets_the_arguments() { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, &X::echo, sstring("hello")); }); }); } future<> test_functor_version() { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, [] (X& x) { return x.echo("hello"); }); }); } int main(int argc, char** argv) { app_template app; return app.run(argc, argv, [] { test_that_each_core_gets_the_arguments().then([] { return test_functor_version(); }).then([] { return engine().exit(0); }).or_terminate(); }); } <commit_msg>test: distrubuted_test: Test that constructor arguments are copied on each core<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "core/app-template.hh" #include "core/distributed.hh" #include "core/future-util.hh" struct X { sstring echo(sstring arg) { return arg; } future<> stop() { return make_ready_future<>(); } }; template <typename T, typename Func> future<> do_with_distributed(Func&& func) { auto x = make_shared<distributed<T>>(); return func(*x).finally([x] { return x->stop(); }).finally([x]{}); } future<> test_that_each_core_gets_the_arguments() { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, &X::echo, sstring("hello")); }); }); } future<> test_functor_version() { return do_with_distributed<X>([] (auto& x) { return x.start().then([&x] { return x.map_reduce([] (sstring msg){ if (msg != "hello") { throw std::runtime_error("wrong message"); } }, [] (X& x) { return x.echo("hello"); }); }); }); } struct Y { sstring s; Y(sstring s) : s(std::move(s)) {} future<> stop() { return make_ready_future<>(); } }; future<> test_constructor_argument_is_passed_to_each_core() { return do_with_distributed<Y>([] (auto& y) { return y.start(sstring("hello")).then([&y] { return y.invoke_on_all([] (Y& y) { if (y.s != "hello") { throw std::runtime_error(sprint("expected message mismatch, is \"%s\"", y.s)); } }); }); }); } int main(int argc, char** argv) { app_template app; return app.run(argc, argv, [] { test_that_each_core_gets_the_arguments().then([] { return test_functor_version(); }).then([] { return test_constructor_argument_is_passed_to_each_core(); }).then([] { return engine().exit(0); }).or_terminate(); }); } <|endoftext|>
<commit_before><commit_msg>resolved fdo#48706 recognize $.12 as currency number<commit_after><|endoftext|>
<commit_before>#ifndef _CONTRAST_SUBMODULAR_FEATURE_HPP_ #define _CONTRAST_SUBMODULAR_FEATURE_HPP_ #include "interactive_seg_app.hpp" #include "feature.hpp" #include <opencv2/core/core.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> class ContrastSubmodularFeature : public InteractiveSegApp::FG { public: typedef InteractiveSegApp::FG::Constr Constr; typedef std::function<void(const std::vector<unsigned char>&)> PatchFn; typedef uint32_t Assgn; static constexpr Assgn clique_size = 4; static constexpr size_t per_cluster = (1 << clique_size) - 2; static constexpr size_t num_clusters = 50; double m_scale; ContrastSubmodularFeature() : m_scale(1.0) { } explicit ContrastSubmodularFeature(double scale) : m_scale(scale) { } virtual size_t NumFeatures() const override { return per_cluster*num_clusters; } virtual std::vector<FVAL> Psi(const IS_PatternData& p, const IS_LabelData& l) const override { cv::Mat patch_feature = m_patch_feature[p.Name()]; const Assgn all_zeros = 0; const Assgn all_ones = (1 << clique_size) - 1; std::vector<FVAL> psi(NumFeatures(), 0); cv::Point base, pt; const cv::Point patch_size(1.0, 1.0); for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) { for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) { Assgn a = 0; int feature = patch_feature.at<int>(base); int i = 0; for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) { for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) { unsigned char label = l.m_gt.at<unsigned char>(pt); if (label == cv::GC_FGD || label == cv::GC_PR_FGD) a |= 1 << i; i++; } } if (a != all_zeros && a != all_ones) psi[a-1 + feature*per_cluster] += m_scale; } } for (auto& v : psi) v = -v; return psi; } virtual void AddToCRF(CRF& crf, const IS_PatternData& p, double* w) const override { cv::Mat patch_feature = m_patch_feature[p.Name()]; std::vector<std::vector<REAL>> costTables(num_clusters, std::vector<REAL>(per_cluster+2, 0)); for (size_t i = 0; i < num_clusters; ++i) { for (size_t j = 0; j < per_cluster; ++j) { costTables[i][j+1] = doubleToREAL(m_scale*w[i*per_cluster+j]); } } cv::Point base, pt; const cv::Point patch_size(1.0, 1.0); for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) { for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) { std::vector<CRF::NodeId> vars; int feature = patch_feature.at<int>(base); for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) { for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) { vars.push_back(pt.y*p.m_image.cols + pt.x); } } crf.AddClique(vars, costTables[feature]); } } } virtual Constr CollectConstrs(size_t feature_base, double constraint_scale) const override { typedef std::vector<std::pair<size_t, double>> LHS; typedef double RHS; Constr ret; Assgn all_zeros = 0; Assgn all_ones = (1 << clique_size) - 1; for (size_t cluster = 0; cluster < num_clusters; ++cluster) { size_t base = feature_base + cluster*per_cluster; for (Assgn s = 0; s < all_ones; ++s) { for (size_t i = 0; i < clique_size; ++i) { Assgn si = s | (1 << i); if (si != s) { for (size_t j = i+1; j < clique_size; ++j) { Assgn t = s | (1 << j); if (t != s && j != i) { Assgn ti = t | (1 << i); // Decreasing marginal costs, so we require // f(ti) - f(t) <= f(si) - f(s) // i.e. f(si) - f(s) - f(ti) + f(t) >= 0 LHS lhs = {{base+si-1, constraint_scale}, {base+t-1, constraint_scale}}; if (s != all_zeros) lhs.push_back(std::make_pair(base+s-1, -constraint_scale)); if (ti != all_ones) lhs.push_back(std::make_pair(base+ti-1, -constraint_scale)); RHS rhs = 0; ret.push_back(std::make_pair(lhs, rhs)); } } } } } } return ret; } virtual double Violation(size_t feature_base, double* w) const override { size_t num_constraints = 0; double total_violation = 0; Assgn all_zeros = 0; Assgn all_ones = (1 << clique_size) - 1; for (size_t cluster = 0; cluster < num_clusters; ++cluster) { size_t base = feature_base + cluster*per_cluster; for (Assgn s = 0; s < all_ones; ++s) { for (size_t i = 0; i < clique_size; ++i) { Assgn si = s | (1 << i); if (si != s) { for (size_t j = i+1; j < clique_size; ++j) { Assgn t = s | (1 << j); if (t != s && j != i) { Assgn ti = t | (1 << i); num_constraints++; // Decreasing marginal costs, so we require // f(ti) - f(t) <= f(si) - f(s) // i.e. f(si) - f(s) - f(ti) + f(t) >= 0 double violation = -w[base+si-1] - w[base+t-1]; if (s != all_zeros) violation += w[base+s-1]; if (ti != all_ones) violation += w[base+ti-1]; if (violation > 0) total_violation += violation; } } } } } } //std::cout << "Num constraints: " << num_constraints <<"\n"; //std::cout << "Min violation: " << min_violation << "\n"; return total_violation; } virtual void Train(const std::vector<IS_PatternData*>& patterns, const std::vector<IS_LabelData*>& labels) { cv::Mat samples; std::cout << "Training submodular filters -- "; std::cout.flush(); samples.create(0, filters, CV_32FC1); for (const IS_PatternData* xp : patterns) { cv::Mat im = xp->m_image; cv::Mat response; GetResponse(im, response); samples.push_back(response); } std::cout << samples.rows << " samples..."; std::cout.flush(); cv::Mat best_labels; cv::kmeans(samples, num_clusters, best_labels, cv::TermCriteria(CV_TERMCRIT_EPS, 10, 0.01), 1, cv::KMEANS_RANDOM_CENTERS, m_centers); std::cout << "Done!\n"; } virtual void Evaluate(const std::vector<IS_PatternData*>& patterns) override { std::cout << "Evaluating Contrast Submodular Features..."; std::cout.flush(); for (const IS_PatternData* xp : patterns) { cv::Mat im = xp->m_image; cv::Mat response; cv::Mat& features = m_patch_feature[xp->Name()]; GetResponse(im, response); features.create(im.rows, im.cols, CV_32SC1); Classify(response, features, m_centers); } std::cout << "Done!\n"; } virtual void SaveEvaluation(const std::string& output_dir) const { std::string outfile = output_dir + "/contrast-submodular-feature.dat"; std::ofstream os(outfile, std::ios_base::binary); boost::archive::binary_oarchive ar(os); ar & m_patch_feature; } virtual void LoadEvaluation(const std::string& output_dir) { std::string infile = output_dir + "/contrast-submodular-feature.dat"; std::ifstream is(infile, std::ios_base::binary); boost::archive::binary_iarchive ar(is); ar & m_patch_feature; } private: static constexpr size_t filters = 5; void FilterResponse(cv::Mat im, cv::Mat& out) { ASSERT(im.channels() == 1); ASSERT(im.type() == CV_32FC1); const size_t samples = im.rows*im.cols; out.create(samples, filters, CV_32FC1); std::vector<cv::Mat> all_filtered; cv::Mat filtered; filtered.create(im.rows, im.cols, CV_32FC1); cv::Sobel(im, filtered, CV_32F, 1, 0); all_filtered.push_back(filtered); cv::Sobel(im, filtered, CV_32F, 0, 1); all_filtered.push_back(filtered); cv::Sobel(im, filtered, CV_32F, 2, 0); all_filtered.push_back(filtered); cv::Sobel(im, filtered, CV_32F, 0, 2); all_filtered.push_back(filtered); cv::Sobel(im, filtered, CV_32F, 1, 1); all_filtered.push_back(filtered); for (int i = 0; i < 5; ++i) { filtered = all_filtered[i]; ASSERT(filtered.rows == im.rows); ASSERT(filtered.cols == im.cols); cv::Point pf, po; po.x = i; po.y = 0; for (pf.y = 0; pf.y < im.rows; ++pf.y) { for (pf.x = 0; pf.x < im.cols; ++pf.x) { out.at<float>(po) = filtered.at<float>(pf); po.y++; } } ASSERT(po.y == out.rows); } } void GetResponse(cv::Mat im, cv::Mat& response) { cv::Mat tmp; im.convertTo(tmp, CV_32F); cv::Mat grayscale; cv::cvtColor(tmp, grayscale, CV_BGR2GRAY); grayscale *= 1./255; FilterResponse(grayscale, response); ASSERT(response.rows == im.cols*im.rows); ASSERT((size_t)response.cols == filters); } void Subsample(cv::Mat in, cv::Mat& out, size_t num_samples) { std::uniform_int_distribution<size_t> dist(0, in.rows-1); out.create(num_samples, in.cols, in.type()); for (size_t i = 0; i < num_samples; ++i) { size_t r = dist(gen); in.row(r).copyTo(out.row(i)); } } void Classify(cv::Mat response, cv::Mat& out, cv::Mat centers) { ASSERT((size_t)response.cols == filters); ASSERT((size_t)centers.cols == filters); ASSERT((size_t)centers.rows == num_clusters); std::vector<size_t> counts(num_clusters, 0); size_t i = 0; cv::Point p; for (p.y = 0; p.y < out.rows; ++p.y) { for (p.x = 0; p.x < out.cols; ++p.x) { ASSERT(i < (size_t)response.rows); cv::Mat row = response.row(i); double min_dist = std::numeric_limits<double>::max(); int min_center = 0; for (int j = 0; j < centers.rows; ++j) { cv::Mat center = centers.row(j); double dist = cv::norm(row, center); if (dist < min_dist) { min_dist = dist; min_center = j; } } counts[min_center]++; ASSERT(min_dist < std::numeric_limits<double>::max()); out.at<int>(p) = min_center; i++; } } std::cout << "Cluster counts: "; for (auto c : counts) std::cout << c << " "; std::cout << "\n"; } friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int version) { //std::cout << "Serializing ContrastSubmodularFeature\n"; ar & boost::serialization::base_object<FeatureGroup>(*this); ar & m_scale; } mutable std::map<std::string, cv::Mat> m_patch_feature; std::mt19937 gen; cv::Mat m_centers; }; BOOST_CLASS_EXPORT_GUID(ContrastSubmodularFeature, "ContrastSubmodularFeature") #endif <commit_msg>Changing filters in ContrastSubmodular to use less blurring<commit_after>#ifndef _CONTRAST_SUBMODULAR_FEATURE_HPP_ #define _CONTRAST_SUBMODULAR_FEATURE_HPP_ #include "interactive_seg_app.hpp" #include "feature.hpp" #include <opencv2/core/core.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> class ContrastSubmodularFeature : public InteractiveSegApp::FG { public: typedef InteractiveSegApp::FG::Constr Constr; typedef std::function<void(const std::vector<unsigned char>&)> PatchFn; typedef uint32_t Assgn; static constexpr Assgn clique_size = 4; static constexpr size_t per_cluster = (1 << clique_size) - 2; static constexpr size_t num_clusters = 50; double m_scale; ContrastSubmodularFeature() : m_scale(1.0) { } explicit ContrastSubmodularFeature(double scale) : m_scale(scale) { } virtual size_t NumFeatures() const override { return per_cluster*num_clusters; } virtual std::vector<FVAL> Psi(const IS_PatternData& p, const IS_LabelData& l) const override { cv::Mat patch_feature = m_patch_feature[p.Name()]; const Assgn all_zeros = 0; const Assgn all_ones = (1 << clique_size) - 1; std::vector<FVAL> psi(NumFeatures(), 0); cv::Point base, pt; const cv::Point patch_size(1.0, 1.0); for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) { for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) { Assgn a = 0; int feature = patch_feature.at<int>(base); int i = 0; for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) { for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) { unsigned char label = l.m_gt.at<unsigned char>(pt); if (label == cv::GC_FGD || label == cv::GC_PR_FGD) a |= 1 << i; i++; } } if (a != all_zeros && a != all_ones) psi[a-1 + feature*per_cluster] += m_scale; } } for (auto& v : psi) v = -v; return psi; } virtual void AddToCRF(CRF& crf, const IS_PatternData& p, double* w) const override { cv::Mat patch_feature = m_patch_feature[p.Name()]; std::vector<std::vector<REAL>> costTables(num_clusters, std::vector<REAL>(per_cluster+2, 0)); for (size_t i = 0; i < num_clusters; ++i) { for (size_t j = 0; j < per_cluster; ++j) { costTables[i][j+1] = doubleToREAL(m_scale*w[i*per_cluster+j]); } } cv::Point base, pt; const cv::Point patch_size(1.0, 1.0); for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) { for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) { std::vector<CRF::NodeId> vars; int feature = patch_feature.at<int>(base); for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) { for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) { vars.push_back(pt.y*p.m_image.cols + pt.x); } } crf.AddClique(vars, costTables[feature]); } } } virtual Constr CollectConstrs(size_t feature_base, double constraint_scale) const override { typedef std::vector<std::pair<size_t, double>> LHS; typedef double RHS; Constr ret; Assgn all_zeros = 0; Assgn all_ones = (1 << clique_size) - 1; for (size_t cluster = 0; cluster < num_clusters; ++cluster) { size_t base = feature_base + cluster*per_cluster; for (Assgn s = 0; s < all_ones; ++s) { for (size_t i = 0; i < clique_size; ++i) { Assgn si = s | (1 << i); if (si != s) { for (size_t j = i+1; j < clique_size; ++j) { Assgn t = s | (1 << j); if (t != s && j != i) { Assgn ti = t | (1 << i); // Decreasing marginal costs, so we require // f(ti) - f(t) <= f(si) - f(s) // i.e. f(si) - f(s) - f(ti) + f(t) >= 0 LHS lhs = {{base+si-1, constraint_scale}, {base+t-1, constraint_scale}}; if (s != all_zeros) lhs.push_back(std::make_pair(base+s-1, -constraint_scale)); if (ti != all_ones) lhs.push_back(std::make_pair(base+ti-1, -constraint_scale)); RHS rhs = 0; ret.push_back(std::make_pair(lhs, rhs)); } } } } } } return ret; } virtual double Violation(size_t feature_base, double* w) const override { size_t num_constraints = 0; double total_violation = 0; Assgn all_zeros = 0; Assgn all_ones = (1 << clique_size) - 1; for (size_t cluster = 0; cluster < num_clusters; ++cluster) { size_t base = feature_base + cluster*per_cluster; for (Assgn s = 0; s < all_ones; ++s) { for (size_t i = 0; i < clique_size; ++i) { Assgn si = s | (1 << i); if (si != s) { for (size_t j = i+1; j < clique_size; ++j) { Assgn t = s | (1 << j); if (t != s && j != i) { Assgn ti = t | (1 << i); num_constraints++; // Decreasing marginal costs, so we require // f(ti) - f(t) <= f(si) - f(s) // i.e. f(si) - f(s) - f(ti) + f(t) >= 0 double violation = -w[base+si-1] - w[base+t-1]; if (s != all_zeros) violation += w[base+s-1]; if (ti != all_ones) violation += w[base+ti-1]; if (violation > 0) total_violation += violation; } } } } } } //std::cout << "Num constraints: " << num_constraints <<"\n"; //std::cout << "Min violation: " << min_violation << "\n"; return total_violation; } virtual void Train(const std::vector<IS_PatternData*>& patterns, const std::vector<IS_LabelData*>& labels) { cv::Mat samples; std::cout << "Training submodular filters -- "; std::cout.flush(); samples.create(0, filters, CV_32FC1); for (const IS_PatternData* xp : patterns) { cv::Mat im = xp->m_image; cv::Mat response; GetResponse(im, response); samples.push_back(response); } std::cout << samples.rows << " samples..."; std::cout.flush(); cv::Mat best_labels; cv::kmeans(samples, num_clusters, best_labels, cv::TermCriteria(CV_TERMCRIT_EPS, 10, 0.01), 1, cv::KMEANS_RANDOM_CENTERS, m_centers); std::cout << "Done!\n"; } virtual void Evaluate(const std::vector<IS_PatternData*>& patterns) override { std::cout << "Evaluating Contrast Submodular Features..."; std::cout.flush(); for (const IS_PatternData* xp : patterns) { cv::Mat im = xp->m_image; cv::Mat response; cv::Mat& features = m_patch_feature[xp->Name()]; GetResponse(im, response); features.create(im.rows, im.cols, CV_32SC1); Classify(response, features, m_centers); } std::cout << "Done!\n"; } virtual void SaveEvaluation(const std::string& output_dir) const { std::string outfile = output_dir + "/contrast-submodular-feature.dat"; std::ofstream os(outfile, std::ios_base::binary); boost::archive::binary_oarchive ar(os); ar & m_patch_feature; } virtual void LoadEvaluation(const std::string& output_dir) { std::string infile = output_dir + "/contrast-submodular-feature.dat"; std::ifstream is(infile, std::ios_base::binary); boost::archive::binary_iarchive ar(is); ar & m_patch_feature; } private: static constexpr int filters = 4; void FilterResponse(cv::Mat im, cv::Mat& out) { ASSERT(im.channels() == 1); ASSERT(im.type() == CV_32FC1); const size_t samples = im.rows*im.cols; out.create(samples, filters, CV_32FC1); std::vector<cv::Mat> all_filtered; cv::Mat filtered; filtered.create(im.rows, im.cols, CV_32FC1); cv::Mat x_deriv = (cv::Mat_<float>(2,2) << 1.0, -1.0, 1.0, -1.0); cv::filter2D(im, filtered, CV_32F, x_deriv, cv::Point(0,0)); all_filtered.push_back(filtered); cv::Mat y_deriv = (cv::Mat_<float>(2,2) << 1.0, 1.0, -1.0, -1.0); cv::filter2D(im, filtered, CV_32F, y_deriv, cv::Point(0,0)); all_filtered.push_back(filtered); cv::Mat xy_deriv = (cv::Mat_<float>(2,2) << 1.0, 0.0, 0.0, -1.0); cv::filter2D(im, filtered, CV_32F, xy_deriv, cv::Point(0,0)); all_filtered.push_back(filtered); cv::Mat yx_deriv = (cv::Mat_<float>(2,2) << 0.0, 1.0, -1.0, 0.0); cv::filter2D(im, filtered, CV_32F, yx_deriv, cv::Point(0,0)); all_filtered.push_back(filtered); for (int i = 0; i < filters; ++i) { filtered = all_filtered[i]; ASSERT(filtered.rows == im.rows); ASSERT(filtered.cols == im.cols); cv::Point pf, po; po.x = i; po.y = 0; for (pf.y = 0; pf.y < im.rows; ++pf.y) { for (pf.x = 0; pf.x < im.cols; ++pf.x) { out.at<float>(po) = filtered.at<float>(pf); po.y++; } } ASSERT(po.y == out.rows); } } void GetResponse(cv::Mat im, cv::Mat& response) { cv::Mat tmp; im.convertTo(tmp, CV_32F); cv::Mat grayscale; cv::cvtColor(tmp, grayscale, CV_BGR2GRAY); grayscale *= 1./255; FilterResponse(grayscale, response); ASSERT(response.rows == im.cols*im.rows); ASSERT(response.cols == filters); } void Subsample(cv::Mat in, cv::Mat& out, size_t num_samples) { std::uniform_int_distribution<size_t> dist(0, in.rows-1); out.create(num_samples, in.cols, in.type()); for (size_t i = 0; i < num_samples; ++i) { size_t r = dist(gen); in.row(r).copyTo(out.row(i)); } } void Classify(cv::Mat response, cv::Mat& out, cv::Mat centers) { ASSERT(response.cols == filters); ASSERT(centers.cols == filters); ASSERT((size_t)centers.rows == num_clusters); std::vector<size_t> counts(num_clusters, 0); size_t i = 0; cv::Point p; for (p.y = 0; p.y < out.rows; ++p.y) { for (p.x = 0; p.x < out.cols; ++p.x) { ASSERT(i < (size_t)response.rows); cv::Mat row = response.row(i); double min_dist = std::numeric_limits<double>::max(); int min_center = 0; for (int j = 0; j < centers.rows; ++j) { cv::Mat center = centers.row(j); double dist = cv::norm(row, center); if (dist < min_dist) { min_dist = dist; min_center = j; } } counts[min_center]++; ASSERT(min_dist < std::numeric_limits<double>::max()); out.at<int>(p) = min_center; i++; } } std::cout << "Cluster counts: "; for (auto c : counts) std::cout << c << " "; std::cout << "\n"; } friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int version) { //std::cout << "Serializing ContrastSubmodularFeature\n"; ar & boost::serialization::base_object<FeatureGroup>(*this); ar & m_scale; } mutable std::map<std::string, cv::Mat> m_patch_feature; std::mt19937 gen; cv::Mat m_centers; }; BOOST_CLASS_EXPORT_GUID(ContrastSubmodularFeature, "ContrastSubmodularFeature") #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ddeinf.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:59:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #define UNICODE #include <string.h> #include "ddeimp.hxx" #include <svtools/svdde.hxx> // --- DdeInternal::InfCallback() ---------------------------------- #ifdef WNT HDDEDATA CALLBACK DdeInternal::InfCallback( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD ) #else #if defined ( MTW ) || ( defined ( GCC ) && defined ( OS2 )) || defined( ICC ) HDDEDATA CALLBACK __EXPORT DdeInternal::InfCallback( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD ) #else HDDEDATA CALLBACK _export DdeInternal::InfCallback( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD ) #endif #endif { return (HDDEDATA)DDE_FNOTPROCESSED; } // --- DdeServiceList::DdeServiceList() ---------------------------- DdeServiceList::DdeServiceList( const String* pTopic ) { DWORD hDdeInst = NULL; HCONVLIST hConvList = NULL; HCONV hConv = NULL; UINT nStatus = DMLERR_NO_ERROR; HSZ hTopic = NULL; nStatus = DdeInitialize( &hDdeInst, (PFNCALLBACK) DdeInternal::InfCallback, APPCLASS_STANDARD | APPCMD_CLIENTONLY | CBF_FAIL_ALLSVRXACTIONS | CBF_SKIP_ALLNOTIFICATIONS, 0L ); if ( nStatus == DMLERR_NO_ERROR ) { if ( pTopic ) { LPCTSTR p = reinterpret_cast<LPCTSTR>(pTopic->GetBuffer()); #ifdef __MINGW32__ hTopic = DdeCreateStringHandle( hDdeInst, const_cast<LPTSTR>(p), CP_WINUNICODE ); #else hTopic = DdeCreateStringHandle( hDdeInst, p, CP_WINUNICODE ); #endif } hConvList = DdeConnectList( hDdeInst, NULL, hTopic, NULL, NULL ); nStatus = DdeGetLastError( hDdeInst ); } if ( nStatus == DMLERR_NO_ERROR ) { while ( ( hConv = DdeQueryNextServer( hConvList, hConv ) ) != NULL) { CONVINFO aInf; TCHAR buf[256], *p; HSZ h; #ifdef OS2 aInf.nSize = sizeof( aInf ); #else aInf.cb = sizeof( aInf ); #endif if( DdeQueryConvInfo( hConv, QID_SYNC, &aInf)) { h = aInf.hszServiceReq; if ( !h ) #ifndef OS2 h = aInf.hszSvcPartner; #else h = aInf.hszPartner; #endif DdeQueryString( hDdeInst, h, buf, sizeof(buf) / sizeof(TCHAR), CP_WINUNICODE ); p = buf + lstrlen( buf ); *p++ = '|'; *p = 0; DdeQueryString( hDdeInst, aInf.hszTopic, p, sizeof(buf)/sizeof(TCHAR)-lstrlen( buf ), CP_WINUNICODE ); aServices.Insert( new String( reinterpret_cast<const sal_Unicode*>(buf) ) ); } } DdeDisconnectList( hConvList ); } if ( hTopic) DdeFreeStringHandle( hDdeInst, hTopic ); if ( hDdeInst ) DdeUninitialize( hDdeInst ); } // --- DdeServiceList::~DdeServiceList() --------------------------- DdeServiceList::~DdeServiceList() { String* s; while ( ( s = aServices.First() ) != NULL ) { aServices.Remove( s ); delete s; } } // --- DdeTopicList::DdeTopicList() -------------------------------- DdeTopicList::DdeTopicList( const String& rService ) { DdeConnection aSys( rService, String( reinterpret_cast<const sal_Unicode*>(SZDDESYS_TOPIC) ) ); if ( !aSys.GetError() ) { DdeRequest aReq( aSys, String( reinterpret_cast<const sal_Unicode*>(SZDDESYS_ITEM_TOPICS) ), 500 ); aReq.SetDataHdl( LINK( this, DdeTopicList, Data ) ); aReq.Execute(); } } // --- DdeTopicList::~DdeTopicList() ------------------------------- DdeTopicList::~DdeTopicList() { String* s; while ( ( s = aTopics.First() ) != NULL ) { aTopics.Remove( s ); delete s; } } // --- DdeTopicList::Data() -------------------------------------------- IMPL_LINK( DdeTopicList, Data, DdeData*, pData ) { char* p = (char*) (const void *) *pData; char* q = p; short i; char buf[256]; while ( *p && *p != '\r' && *p != '\n' ) { q = buf; i = 0; while ( i < 255 && *p && *p != '\r' && *p != '\n' && *p != '\t' ) *q++ = *p++, i++; *q = 0; while ( *p && *p != '\r' && *p != '\n' && *p != '\t' ) p++; aTopics.Insert( new String( String::CreateFromAscii(buf) ) ); if ( *p == '\t' ) p++; } return 0; } <commit_msg>INTEGRATION: CWS os2port01 (1.2.10); FILE MERGED 2007/08/12 14:23:11 obr 1.2.10.2: RESYNC: (1.2-1.6); FILE MERGED 2006/12/28 15:06:04 ydario 1.2.10.1: OS/2 initial import.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ddeinf.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2007-09-20 16:30:31 $ * * 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_svtools.hxx" #define UNICODE #include <string.h> #include "ddeimp.hxx" #include <svtools/svdde.hxx> // --- DdeInternal::InfCallback() ---------------------------------- #ifdef WNT HDDEDATA CALLBACK DdeInternal::InfCallback( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD ) #else #if defined ( MTW ) || ( defined ( GCC ) && defined ( OS2 )) || defined( ICC ) HDDEDATA CALLBACK __EXPORT DdeInternal::InfCallback( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD ) #else HDDEDATA CALLBACK _export DdeInternal::InfCallback( WORD, WORD, HCONV, HSZ, HSZ, HDDEDATA, DWORD, DWORD ) #endif #endif { return (HDDEDATA)DDE_FNOTPROCESSED; } // --- DdeServiceList::DdeServiceList() ---------------------------- DdeServiceList::DdeServiceList( const String* pTopic ) { DWORD hDdeInst = NULL; HCONVLIST hConvList = NULL; HCONV hConv = NULL; UINT nStatus = DMLERR_NO_ERROR; HSZ hTopic = NULL; #ifndef OS2 // YD FIXME nStatus = DdeInitialize( &hDdeInst, (PFNCALLBACK) DdeInternal::InfCallback, APPCLASS_STANDARD | APPCMD_CLIENTONLY | CBF_FAIL_ALLSVRXACTIONS | CBF_SKIP_ALLNOTIFICATIONS, 0L ); if ( nStatus == DMLERR_NO_ERROR ) { if ( pTopic ) { LPCTSTR p = reinterpret_cast<LPCTSTR>(pTopic->GetBuffer()); #ifdef __MINGW32__ hTopic = DdeCreateStringHandle( hDdeInst, const_cast<LPTSTR>(p), CP_WINUNICODE ); #else hTopic = DdeCreateStringHandle( hDdeInst, p, CP_WINUNICODE ); #endif } hConvList = DdeConnectList( hDdeInst, NULL, hTopic, NULL, NULL ); nStatus = DdeGetLastError( hDdeInst ); } if ( nStatus == DMLERR_NO_ERROR ) { while ( ( hConv = DdeQueryNextServer( hConvList, hConv ) ) != NULL) { CONVINFO aInf; TCHAR buf[256], *p; HSZ h; #ifdef OS2 aInf.nSize = sizeof( aInf ); #else aInf.cb = sizeof( aInf ); #endif if( DdeQueryConvInfo( hConv, QID_SYNC, &aInf)) { h = aInf.hszServiceReq; if ( !h ) #ifndef OS2 h = aInf.hszSvcPartner; #else h = aInf.hszPartner; #endif DdeQueryString( hDdeInst, h, buf, sizeof(buf) / sizeof(TCHAR), CP_WINUNICODE ); p = buf + lstrlen( buf ); *p++ = '|'; *p = 0; DdeQueryString( hDdeInst, aInf.hszTopic, p, sizeof(buf)/sizeof(TCHAR)-lstrlen( buf ), CP_WINUNICODE ); aServices.Insert( new String( reinterpret_cast<const sal_Unicode*>(buf) ) ); } } DdeDisconnectList( hConvList ); } if ( hTopic) DdeFreeStringHandle( hDdeInst, hTopic ); if ( hDdeInst ) DdeUninitialize( hDdeInst ); #endif } // --- DdeServiceList::~DdeServiceList() --------------------------- DdeServiceList::~DdeServiceList() { String* s; while ( ( s = aServices.First() ) != NULL ) { aServices.Remove( s ); delete s; } } // --- DdeTopicList::DdeTopicList() -------------------------------- DdeTopicList::DdeTopicList( const String& rService ) { DdeConnection aSys( rService, String( reinterpret_cast<const sal_Unicode*>(SZDDESYS_TOPIC) ) ); if ( !aSys.GetError() ) { DdeRequest aReq( aSys, String( reinterpret_cast<const sal_Unicode*>(SZDDESYS_ITEM_TOPICS) ), 500 ); aReq.SetDataHdl( LINK( this, DdeTopicList, Data ) ); aReq.Execute(); } } // --- DdeTopicList::~DdeTopicList() ------------------------------- DdeTopicList::~DdeTopicList() { String* s; while ( ( s = aTopics.First() ) != NULL ) { aTopics.Remove( s ); delete s; } } // --- DdeTopicList::Data() -------------------------------------------- IMPL_LINK( DdeTopicList, Data, DdeData*, pData ) { char* p = (char*) (const void *) *pData; char* q = p; short i; char buf[256]; while ( *p && *p != '\r' && *p != '\n' ) { q = buf; i = 0; while ( i < 255 && *p && *p != '\r' && *p != '\n' && *p != '\t' ) *q++ = *p++, i++; *q = 0; while ( *p && *p != '\r' && *p != '\n' && *p != '\t' ) p++; aTopics.Insert( new String( String::CreateFromAscii(buf) ) ); if ( *p == '\t' ) p++; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: e3dundo.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:02:32 $ * * 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_svx.hxx" #ifndef _E3D_UNDO_HXX #include <svx/e3dundo.hxx> #endif #ifndef _SVDMODEL_HXX #include <svx/svdmodel.hxx> #endif #ifndef _OUTLOBJ_HXX #include <svx/outlobj.hxx> #endif #ifndef _E3D_VIEW3D_HXX #include <svx/view3d.hxx> #endif #ifndef _E3D_SCENE3D_HXX #include <svx/scene3d.hxx> #endif /************************************************************************/ TYPEINIT1(E3dUndoAction, SfxUndoAction); /************************************************************************\ |* |* Destruktor der Basisklasse |* \************************************************************************/ E3dUndoAction::~E3dUndoAction () { } /************************************************************************\ |* |* Repeat gibt es nicht |* \************************************************************************/ BOOL E3dUndoAction::CanRepeat(SfxRepeatTarget&) const { return FALSE; } /************************************************************************/ TYPEINIT1(E3dRotateUndoAction, E3dUndoAction); /************************************************************************ E3dRotateUndoAction ************************************************************************/ /************************************************************************\ |* |* Undodestruktor fuer 3D-Rotation |* \************************************************************************/ E3dRotateUndoAction::~E3dRotateUndoAction () { } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Undo () { pMy3DObj->SetTransform(aMyOldRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Redo () { pMy3DObj->SetTransform(aMyNewRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************* |* |* E3dAttributesUndoAction |* \************************************************************************/ TYPEINIT1(E3dAttributesUndoAction, SdrUndoAction); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ E3dAttributesUndoAction::E3dAttributesUndoAction( SdrModel &rModel, E3dView* p3dView, E3dObject* pInObject, const SfxItemSet& rNewSet, const SfxItemSet& rOldSet, BOOL bUseSubObj) : SdrUndoAction( rModel ), pObject ( pInObject ), pView ( p3dView ), bUseSubObjects(bUseSubObj), aNewSet ( rNewSet ), aOldSet ( rOldSet ) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ E3dAttributesUndoAction::~E3dAttributesUndoAction() { } /************************************************************************* |* |* Undo() |* Implementiert ueber Set3DAttributes(), um die Attribute nur an einer |* Stelle pflegen zu muessen! |* \************************************************************************/ void E3dAttributesUndoAction::Undo() { //pObject->SetItemSetAndBroadcast(aOldSet); pObject->SetMergedItemSetAndBroadcast(aOldSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Redo() |* \************************************************************************/ void E3dAttributesUndoAction::Redo() { //pObject->SetItemSetAndBroadcast(aNewSet); pObject->SetMergedItemSetAndBroadcast(aNewSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ BOOL E3dAttributesUndoAction::CanRepeat(SfxRepeatTarget& /*rView*/) const { return FALSE; } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ void E3dAttributesUndoAction::Repeat() { } <commit_msg>INTEGRATION: CWS changefileheader (1.8.368); FILE MERGED 2008/04/01 12:48:40 thb 1.8.368.2: #i85898# Stripping all external header guards 2008/03/31 14:21:44 rt 1.8.368.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: e3dundo.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_svx.hxx" #include <svx/e3dundo.hxx> #include <svx/svdmodel.hxx> #include <svx/outlobj.hxx> #include <svx/view3d.hxx> #include <svx/scene3d.hxx> /************************************************************************/ TYPEINIT1(E3dUndoAction, SfxUndoAction); /************************************************************************\ |* |* Destruktor der Basisklasse |* \************************************************************************/ E3dUndoAction::~E3dUndoAction () { } /************************************************************************\ |* |* Repeat gibt es nicht |* \************************************************************************/ BOOL E3dUndoAction::CanRepeat(SfxRepeatTarget&) const { return FALSE; } /************************************************************************/ TYPEINIT1(E3dRotateUndoAction, E3dUndoAction); /************************************************************************ E3dRotateUndoAction ************************************************************************/ /************************************************************************\ |* |* Undodestruktor fuer 3D-Rotation |* \************************************************************************/ E3dRotateUndoAction::~E3dRotateUndoAction () { } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Undo () { pMy3DObj->SetTransform(aMyOldRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Redo () { pMy3DObj->SetTransform(aMyNewRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************* |* |* E3dAttributesUndoAction |* \************************************************************************/ TYPEINIT1(E3dAttributesUndoAction, SdrUndoAction); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ E3dAttributesUndoAction::E3dAttributesUndoAction( SdrModel &rModel, E3dView* p3dView, E3dObject* pInObject, const SfxItemSet& rNewSet, const SfxItemSet& rOldSet, BOOL bUseSubObj) : SdrUndoAction( rModel ), pObject ( pInObject ), pView ( p3dView ), bUseSubObjects(bUseSubObj), aNewSet ( rNewSet ), aOldSet ( rOldSet ) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ E3dAttributesUndoAction::~E3dAttributesUndoAction() { } /************************************************************************* |* |* Undo() |* Implementiert ueber Set3DAttributes(), um die Attribute nur an einer |* Stelle pflegen zu muessen! |* \************************************************************************/ void E3dAttributesUndoAction::Undo() { //pObject->SetItemSetAndBroadcast(aOldSet); pObject->SetMergedItemSetAndBroadcast(aOldSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Redo() |* \************************************************************************/ void E3dAttributesUndoAction::Redo() { //pObject->SetItemSetAndBroadcast(aNewSet); pObject->SetMergedItemSetAndBroadcast(aNewSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ BOOL E3dAttributesUndoAction::CanRepeat(SfxRepeatTarget& /*rView*/) const { return FALSE; } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ void E3dAttributesUndoAction::Repeat() { } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: clonelist.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:56:15 $ * * 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_svx.hxx" // #i13033# // New mechanism to hold a ist of all original and cloned objects for later // re-creating the connections for contained connectors #ifndef _CLONELIST_HXX_ #include <clonelist.hxx> #endif #ifndef _SVDOEDGE_HXX #include <svx/svdoedge.hxx> #endif #ifndef _E3D_SCENE3D_HXX #include <svx/scene3d.hxx> #endif CloneList::CloneList() { } CloneList::~CloneList() { } void CloneList::AddPair(const SdrObject* pOriginal, SdrObject* pClone) { maOriginalList.Insert((SdrObject*)pOriginal, LIST_APPEND); maCloneList.Insert(pClone, LIST_APPEND); // look for subobjects, too. sal_Bool bOriginalIsGroup(pOriginal->IsGroupObject()); sal_Bool bCloneIsGroup(pClone->IsGroupObject()); if(bOriginalIsGroup && pOriginal->ISA(E3dObject) && !pOriginal->ISA(E3dScene)) bOriginalIsGroup = sal_False; if(bCloneIsGroup && pClone->ISA(E3dObject) && !pClone->ISA(E3dScene)) bCloneIsGroup = sal_False; if(bOriginalIsGroup && bCloneIsGroup) { const SdrObjList* pOriginalList = pOriginal->GetSubList(); SdrObjList* pCloneList = pClone->GetSubList(); if(pOriginalList && pCloneList && pOriginalList->GetObjCount() == pCloneList->GetObjCount()) { for(sal_uInt32 a(0); a < pOriginalList->GetObjCount(); a++) { // recursive call AddPair(pOriginalList->GetObj(a), pCloneList->GetObj(a)); } } } } sal_uInt32 CloneList::Count() const { return maOriginalList.Count(); } const SdrObject* CloneList::GetOriginal(sal_uInt32 nIndex) const { return (SdrObject*)maOriginalList.GetObject(nIndex); } SdrObject* CloneList::GetClone(sal_uInt32 nIndex) const { return (SdrObject*)maCloneList.GetObject(nIndex); } void CloneList::CopyConnections() const { for(sal_uInt32 a(0); a < maOriginalList.Count(); a++) { const SdrEdgeObj* pOriginalEdge = PTR_CAST(SdrEdgeObj, GetOriginal(a)); SdrEdgeObj* pCloneEdge = PTR_CAST(SdrEdgeObj, GetClone(a)); if(pOriginalEdge && pCloneEdge) { SdrObject* pOriginalNode1 = pOriginalEdge->GetConnectedNode(sal_True); SdrObject* pOriginalNode2 = pOriginalEdge->GetConnectedNode(sal_False); if(pOriginalNode1) { sal_uInt32 nPos(maOriginalList.GetPos(pOriginalNode1)); if(LIST_ENTRY_NOTFOUND != nPos) { if(pOriginalEdge->GetConnectedNode(sal_True) != GetClone(nPos)) { pCloneEdge->ConnectToNode(sal_True, GetClone(nPos)); } } } if(pOriginalNode2) { sal_uInt32 nPos(maOriginalList.GetPos(pOriginalNode2)); if(LIST_ENTRY_NOTFOUND != nPos) { if(pOriginalEdge->GetConnectedNode(sal_False) != GetClone(nPos)) { pCloneEdge->ConnectToNode(sal_False, GetClone(nPos)); } } } } } } // eof <commit_msg>INTEGRATION: CWS changefileheader (1.5.368); FILE MERGED 2008/04/01 12:49:48 thb 1.5.368.2: #i85898# Stripping all external header guards 2008/03/31 14:23:18 rt 1.5.368.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: clonelist.cxx,v $ * $Revision: 1.6 $ * * 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_svx.hxx" // #i13033# // New mechanism to hold a ist of all original and cloned objects for later // re-creating the connections for contained connectors #include <clonelist.hxx> #include <svx/svdoedge.hxx> #include <svx/scene3d.hxx> CloneList::CloneList() { } CloneList::~CloneList() { } void CloneList::AddPair(const SdrObject* pOriginal, SdrObject* pClone) { maOriginalList.Insert((SdrObject*)pOriginal, LIST_APPEND); maCloneList.Insert(pClone, LIST_APPEND); // look for subobjects, too. sal_Bool bOriginalIsGroup(pOriginal->IsGroupObject()); sal_Bool bCloneIsGroup(pClone->IsGroupObject()); if(bOriginalIsGroup && pOriginal->ISA(E3dObject) && !pOriginal->ISA(E3dScene)) bOriginalIsGroup = sal_False; if(bCloneIsGroup && pClone->ISA(E3dObject) && !pClone->ISA(E3dScene)) bCloneIsGroup = sal_False; if(bOriginalIsGroup && bCloneIsGroup) { const SdrObjList* pOriginalList = pOriginal->GetSubList(); SdrObjList* pCloneList = pClone->GetSubList(); if(pOriginalList && pCloneList && pOriginalList->GetObjCount() == pCloneList->GetObjCount()) { for(sal_uInt32 a(0); a < pOriginalList->GetObjCount(); a++) { // recursive call AddPair(pOriginalList->GetObj(a), pCloneList->GetObj(a)); } } } } sal_uInt32 CloneList::Count() const { return maOriginalList.Count(); } const SdrObject* CloneList::GetOriginal(sal_uInt32 nIndex) const { return (SdrObject*)maOriginalList.GetObject(nIndex); } SdrObject* CloneList::GetClone(sal_uInt32 nIndex) const { return (SdrObject*)maCloneList.GetObject(nIndex); } void CloneList::CopyConnections() const { for(sal_uInt32 a(0); a < maOriginalList.Count(); a++) { const SdrEdgeObj* pOriginalEdge = PTR_CAST(SdrEdgeObj, GetOriginal(a)); SdrEdgeObj* pCloneEdge = PTR_CAST(SdrEdgeObj, GetClone(a)); if(pOriginalEdge && pCloneEdge) { SdrObject* pOriginalNode1 = pOriginalEdge->GetConnectedNode(sal_True); SdrObject* pOriginalNode2 = pOriginalEdge->GetConnectedNode(sal_False); if(pOriginalNode1) { sal_uInt32 nPos(maOriginalList.GetPos(pOriginalNode1)); if(LIST_ENTRY_NOTFOUND != nPos) { if(pOriginalEdge->GetConnectedNode(sal_True) != GetClone(nPos)) { pCloneEdge->ConnectToNode(sal_True, GetClone(nPos)); } } } if(pOriginalNode2) { sal_uInt32 nPos(maOriginalList.GetPos(pOriginalNode2)); if(LIST_ENTRY_NOTFOUND != nPos) { if(pOriginalEdge->GetConnectedNode(sal_False) != GetClone(nPos)) { pCloneEdge->ConnectToNode(sal_False, GetClone(nPos)); } } } } } } // eof <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unobtabl.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2004-11-15 17:30:33 $ * * 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 _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SV_CVTGRF_HXX #include <vcl/cvtgrf.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SVX_XIT_HXX #include <xit.hxx> #endif #ifndef SVX_LIGHT #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #endif #ifndef _SVX_UNONAMEITEMTABLE_HXX_ #include "UnoNameItemTable.hxx" #endif #include "xbtmpit.hxx" #include "svdmodel.hxx" #include "xflhtit.hxx" #include "unoapi.hxx" #include "impgrf.hxx" #include "unomid.hxx" #include "unoprnms.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoBitmapTable : public SvxUnoNameItemTable { public: SvxUnoBitmapTable( SdrModel* pModel ) throw(); virtual ~SvxUnoBitmapTable() throw(); virtual NameOrIndex* createItem() const throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); }; SvxUnoBitmapTable::SvxUnoBitmapTable( SdrModel* pModel ) throw() : SvxUnoNameItemTable( pModel, XATTR_FILLBITMAP, MID_GRAFURL ) { } SvxUnoBitmapTable::~SvxUnoBitmapTable() throw() { } OUString SAL_CALL SvxUnoBitmapTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoBitmapTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoBitmapTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.BitmapTable" )); return aSNS; } NameOrIndex* SvxUnoBitmapTable::createItem() const throw() { return new XFillBitmapItem(); } // XElementAccess uno::Type SAL_CALL SvxUnoBitmapTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType( (const ::rtl::OUString*)0 ); } /** * Create a bitmaptable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoBitmapTable_createInstance( SdrModel* pModel ) { return *new SvxUnoBitmapTable(pModel); } #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif /** returns a GraphicObject for this URL */ GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw() { const String aURL( rURL ), aPrefix( RTL_CONSTASCII_STRINGPARAM(UNO_NAME_GRAPHOBJ_URLPREFIX) ); if( aURL.Search( aPrefix ) == 0 ) { // graphic manager url ByteString aUniqueID( String(rURL.copy( sizeof( UNO_NAME_GRAPHOBJ_URLPREFIX ) - 1 )), RTL_TEXTENCODING_UTF8 ); return GraphicObject( aUniqueID ); } else { Graphic aGraphic; #ifndef SVX_LIGHT if ( aURL.Len() ) { SfxMedium aMedium( aURL, STREAM_READ, TRUE ); SvStream* pStream = aMedium.GetInStream(); if( pStream ) GraphicConverter::Import( *pStream, aGraphic ); } #else String aSystemPath( rURL ); utl::LocalFileHelper::ConvertURLToSystemPath( aSystemPath, aSystemPath ); SvFileStream aFile( aSystemPath, STREAM_READ ); GraphicConverter::Import( aFile, aGraphic ); #endif return GraphicObject( aGraphic ); } } <commit_msg>INTEGRATION: CWS impress18 (1.11.1068); FILE MERGED 2004/11/09 12:47:41 cl 1.11.1068.1: #i36727# filter empty bitmap items<commit_after>/************************************************************************* * * $RCSfile: unobtabl.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2004-11-18 09:20:10 $ * * 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 _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SV_CVTGRF_HXX #include <vcl/cvtgrf.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SVX_XIT_HXX #include <xit.hxx> #endif #ifndef SVX_LIGHT #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #endif #ifndef _SVX_UNONAMEITEMTABLE_HXX_ #include "UnoNameItemTable.hxx" #endif #include "xbtmpit.hxx" #include "svdmodel.hxx" #include "xflhtit.hxx" #include "unoapi.hxx" #include "impgrf.hxx" #include "unomid.hxx" #include "unoprnms.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoBitmapTable : public SvxUnoNameItemTable { public: SvxUnoBitmapTable( SdrModel* pModel ) throw(); virtual ~SvxUnoBitmapTable() throw(); virtual NameOrIndex* createItem() const throw(); virtual bool isValid( const NameOrIndex* pItem ) const; // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); }; SvxUnoBitmapTable::SvxUnoBitmapTable( SdrModel* pModel ) throw() : SvxUnoNameItemTable( pModel, XATTR_FILLBITMAP, MID_GRAFURL ) { } SvxUnoBitmapTable::~SvxUnoBitmapTable() throw() { } bool SvxUnoBitmapTable::isValid( const NameOrIndex* pItem ) const { if( SvxUnoNameItemTable::isValid( pItem ) ) { const XFillBitmapItem* pBitmapItem = dynamic_cast< const XFillBitmapItem* >( pItem ); if( pBitmapItem ) { const GraphicObject& rGraphic = pBitmapItem->GetValue().GetGraphicObject(); return rGraphic.GetSizeBytes() > 0; } } return false; } OUString SAL_CALL SvxUnoBitmapTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoBitmapTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoBitmapTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.BitmapTable" )); return aSNS; } NameOrIndex* SvxUnoBitmapTable::createItem() const throw() { return new XFillBitmapItem(); } // XElementAccess uno::Type SAL_CALL SvxUnoBitmapTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType( (const ::rtl::OUString*)0 ); } /** * Create a bitmaptable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoBitmapTable_createInstance( SdrModel* pModel ) { return *new SvxUnoBitmapTable(pModel); } #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif /** returns a GraphicObject for this URL */ GraphicObject CreateGraphicObjectFromURL( const ::rtl::OUString &rURL ) throw() { const String aURL( rURL ), aPrefix( RTL_CONSTASCII_STRINGPARAM(UNO_NAME_GRAPHOBJ_URLPREFIX) ); if( aURL.Search( aPrefix ) == 0 ) { // graphic manager url ByteString aUniqueID( String(rURL.copy( sizeof( UNO_NAME_GRAPHOBJ_URLPREFIX ) - 1 )), RTL_TEXTENCODING_UTF8 ); return GraphicObject( aUniqueID ); } else { Graphic aGraphic; #ifndef SVX_LIGHT if ( aURL.Len() ) { SfxMedium aMedium( aURL, STREAM_READ, TRUE ); SvStream* pStream = aMedium.GetInStream(); if( pStream ) GraphicConverter::Import( *pStream, aGraphic ); } #else String aSystemPath( rURL ); utl::LocalFileHelper::ConvertURLToSystemPath( aSystemPath, aSystemPath ); SvFileStream aFile( aSystemPath, STREAM_READ ); GraphicConverter::Import( aFile, aGraphic ); #endif return GraphicObject( aGraphic ); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <bookmrk.hxx> #include <IDocumentMarkAccess.hxx> #include <doc.hxx> #include <errhdl.hxx> #include <ndtxt.hxx> #include <pam.hxx> #include <swserv.hxx> #include <sfx2/linkmgr.hxx> #include <swtypes.hxx> #include <undobj.hxx> #include <unobookmark.hxx> #include <rtl/random.h> #include <xmloff/odffields.hxx> SV_IMPL_REF( SwServerObject ) using namespace ::sw::mark; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace { static void lcl_FixPosition(SwPosition& rPos) { // make sure the position has 1) the proper node, and 2) a proper index SwTxtNode* pTxtNode = rPos.nNode.GetNode().GetTxtNode(); if(pTxtNode == NULL && rPos.nContent.GetIndex() > 0) { OSL_TRACE( "bookmrk.cxx::lcl_FixPosition" " - illegal position: %d without proper TxtNode", rPos.nContent.GetIndex()); rPos.nContent.Assign(NULL, 0); } else if(pTxtNode != NULL && rPos.nContent.GetIndex() > pTxtNode->Len()) { OSL_TRACE( "bookmrk.cxx::lcl_FixPosition" " - illegal position: %d is beyond %d", rPos.nContent.GetIndex(), pTxtNode->Len()); rPos.nContent.Assign(pTxtNode, pTxtNode->Len()); } }; static void lcl_AssureFieldMarksSet(Fieldmark* const pField, SwDoc* const io_pDoc, const sal_Unicode aStartMark, const sal_Unicode aEndMark) { SwPosition& rStart = pField->GetMarkStart(); SwPosition& rEnd = pField->GetMarkEnd(); SwTxtNode const * const pStartTxtNode = io_pDoc->GetNodes()[rStart.nNode]->GetTxtNode(); SwTxtNode const * const pEndTxtNode = io_pDoc->GetNodes()[rEnd.nNode]->GetTxtNode(); const sal_Unicode ch_start=pStartTxtNode->GetTxt().GetChar(rStart.nContent.GetIndex()); xub_StrLen nEndPos = rEnd.nContent.GetIndex() == 0 ? 0 : rEnd.nContent.GetIndex() - 1; const sal_Unicode ch_end=pEndTxtNode->GetTxt().GetChar( nEndPos ); SwPaM aStartPaM(rStart); SwPaM aEndPaM(rEnd); io_pDoc->StartUndo(UNDO_UI_REPLACE, NULL); if( ( ch_start != aStartMark ) && ( aEndMark != CH_TXT_ATR_FORMELEMENT ) ) { io_pDoc->InsertString(aStartPaM, aStartMark); rStart.nContent--; } if ( aEndMark && ( ch_end != aEndMark ) ) { io_pDoc->InsertString(aEndPaM, aEndMark); rEnd.nContent++; } io_pDoc->EndUndo(UNDO_UI_REPLACE, NULL); }; } namespace sw { namespace mark { MarkBase::MarkBase(const SwPaM& aPaM, const ::rtl::OUString& rName) : SwModify(0) , m_pPos1(new SwPosition(*(aPaM.GetPoint()))) , m_aName(rName) { lcl_FixPosition(*m_pPos1); if(aPaM.HasMark()) { MarkBase::SetOtherMarkPos(*(aPaM.GetMark())); lcl_FixPosition(*m_pPos2); } } bool MarkBase::IsCoveringPosition(const SwPosition& rPos) const { return GetMarkStart() <= rPos && rPos < GetMarkEnd(); } void MarkBase::SetMarkPos(const SwPosition& rNewPos) { ::boost::scoped_ptr<SwPosition>(new SwPosition(rNewPos)).swap(m_pPos1); //lcl_FixPosition(*m_pPos1); } void MarkBase::SetOtherMarkPos(const SwPosition& rNewPos) { ::boost::scoped_ptr<SwPosition>(new SwPosition(rNewPos)).swap(m_pPos2); //lcl_FixPosition(*m_pPos2); } rtl::OUString MarkBase::ToString( ) const { rtl::OUStringBuffer buf; buf.appendAscii( "Mark: ( Name, [ Node1, Index1 ] ): ( " ); buf.append( m_aName ).appendAscii( ", [ " ); buf.append( sal_Int32( GetMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetMarkPos().nContent.GetIndex( ) ) ).appendAscii( " ] )" ); return buf.makeStringAndClear( ); } MarkBase::~MarkBase() { } ::rtl::OUString MarkBase::GenerateNewName(const ::rtl::OUString& rPrefix) { static rtlRandomPool aPool = rtl_random_createPool(); static ::rtl::OUString sUniquePostfix; static sal_Int32 nCount = SAL_MAX_INT32; ::rtl::OUStringBuffer aResult(rPrefix); if(nCount == SAL_MAX_INT32) { sal_Int32 nRandom; ::rtl::OUStringBuffer sUniquePostfixBuffer; rtl_random_getBytes(aPool, &nRandom, sizeof(nRandom)); sUniquePostfix = ::rtl::OUStringBuffer(13).appendAscii("_").append(static_cast<sal_Int32>(abs(nRandom))).makeStringAndClear(); nCount = 0; } // putting the counter in front of the random parts will speed up string comparisons return aResult.append(nCount++).append(sUniquePostfix).makeStringAndClear(); } void MarkBase::Modify(SfxPoolItem *pOld, SfxPoolItem *pNew) { SwModify::Modify(pOld, pNew); if (pOld && (RES_REMOVE_UNO_OBJECT == pOld->Which())) { // invalidate cached uno object SetXBookmark(uno::Reference<text::XTextContent>(0)); } } NavigatorReminder::NavigatorReminder(const SwPaM& rPaM) : MarkBase(rPaM, our_sNamePrefix) { } const ::rtl::OUString NavigatorReminder::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__NavigatorReminder__")); UnoMark::UnoMark(const SwPaM& aPaM) : MarkBase(aPaM, MarkBase::GenerateNewName(our_sNamePrefix)) { } const ::rtl::OUString UnoMark::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__UnoMark__")); DdeBookmark::DdeBookmark(const SwPaM& aPaM) : MarkBase(aPaM, MarkBase::GenerateNewName(our_sNamePrefix)) , m_aRefObj(NULL) { } void DdeBookmark::SetRefObject(SwServerObject* pObj) { m_aRefObj = pObj; } const ::rtl::OUString DdeBookmark::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__DdeLink__")); void DdeBookmark::DeregisterFromDoc(SwDoc* const pDoc) { if(m_aRefObj.Is()) pDoc->GetLinkManager().RemoveServer(m_aRefObj); } DdeBookmark::~DdeBookmark() { if( m_aRefObj.Is() ) { if(m_aRefObj->HasDataLinks()) { ::sfx2::SvLinkSource* p = &m_aRefObj; p->SendDataChanged(); } m_aRefObj->SetNoServer(); } } Bookmark::Bookmark(const SwPaM& aPaM, const KeyCode& rCode, const ::rtl::OUString& rName, const ::rtl::OUString& rShortName) : DdeBookmark(aPaM) , ::sfx2::Metadatable() , m_aCode(rCode) , m_sShortName(rShortName) { m_aName = rName; } void Bookmark::InitDoc(SwDoc* const io_pDoc) { if(io_pDoc->DoesUndo()) { io_pDoc->ClearRedo(); io_pDoc->AppendUndo(new SwUndoInsBookmark(*this)); } io_pDoc->SetModified(); } // ::sfx2::Metadatable ::sfx2::IXmlIdRegistry& Bookmark::GetRegistry() { SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::MakeUnoObject: no doc?"); return pDoc->GetXmlIdRegistry(); } bool Bookmark::IsInClipboard() const { SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::IsInClipboard: no doc?"); return pDoc->IsClipBoard(); } bool Bookmark::IsInUndo() const { return false; } bool Bookmark::IsInContent() const { SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::IsInContent: no doc?"); return !pDoc->IsInHeaderFooter( SwNodeIndex(GetMarkPos().nNode) ); } uno::Reference< rdf::XMetadatable > Bookmark::MakeUnoObject() { // create new SwXBookmark SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::MakeUnoObject: no doc?"); const uno::Reference< rdf::XMetadatable> xMeta( SwXBookmark::CreateXBookmark(*pDoc, *this), uno::UNO_QUERY); return xMeta; } Fieldmark::Fieldmark(const SwPaM& rPaM) : MarkBase(rPaM, MarkBase::GenerateNewName(our_sNamePrefix)) { if(!IsExpanded()) SetOtherMarkPos(GetMarkPos()); } rtl::OUString Fieldmark::ToString( ) const { rtl::OUStringBuffer buf; buf.appendAscii( "Fieldmark: ( Name, Type, [ Nd1, Id1 ], [ Nd2, Id2 ] ): ( " ); buf.append( m_aName ).appendAscii( ", " ); buf.append( m_aFieldname ).appendAscii( ", [ " ); buf.append( sal_Int32( GetMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ], [" ); buf.append( sal_Int32( GetOtherMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetOtherMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ] ) " ); return buf.makeStringAndClear( ); } void Fieldmark::Invalidate( ) { // @TODO: Does exist a better solution to trigger a format of the // fieldmark portion? If yes, please use it. SwPaM aPaM( this->GetMarkPos(), this->GetOtherMarkPos() ); aPaM.InvalidatePaM(); } const ::rtl::OUString Fieldmark::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__Fieldmark__")); TextFieldmark::TextFieldmark(const SwPaM& rPaM) : Fieldmark(rPaM) { } void TextFieldmark::InitDoc(SwDoc* const io_pDoc) { lcl_AssureFieldMarksSet(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND); } CheckboxFieldmark::CheckboxFieldmark(const SwPaM& rPaM) : Fieldmark(rPaM) { } void CheckboxFieldmark::InitDoc(SwDoc* const io_pDoc) { lcl_AssureFieldMarksSet(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FORMELEMENT); // For some reason the end mark is moved from 1 by the Insert: we don't // want this for checkboxes this->GetMarkEnd( ).nContent--; } void CheckboxFieldmark::SetChecked(bool checked) { (*GetParameters())[::rtl::OUString::createFromAscii(ODF_FORMCHECKBOX_RESULT)] = makeAny(checked); bool bOld( IsChecked() ); if ( bOld != checked ) { // mark document as modified SwDoc *const pDoc( GetMarkPos().GetDoc() ); if ( pDoc ) pDoc->SetModified(); } } bool CheckboxFieldmark::IsChecked() const { bool bResult = false; parameter_map_t::const_iterator pResult = GetParameters()->find(::rtl::OUString::createFromAscii(ODF_FORMCHECKBOX_RESULT)); if(pResult != GetParameters()->end()) pResult->second >>= bResult; return bResult; } rtl::OUString CheckboxFieldmark::toString( ) const { rtl::OUStringBuffer buf; buf.appendAscii( "CheckboxFieldmark: ( Name, Type, [ Nd1, Id1 ], [ Nd2, Id2 ] ): ( " ); buf.append( m_aName ).appendAscii( ", " ); buf.append( GetFieldname() ).appendAscii( ", [ " ); buf.append( sal_Int32( GetMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ], [" ); buf.append( sal_Int32( GetOtherMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetOtherMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ] ) " ); return buf.makeStringAndClear( ); } }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>minor tweak to existing fix for ( bnc#660816 & fdo#34908<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <bookmrk.hxx> #include <IDocumentMarkAccess.hxx> #include <doc.hxx> #include <errhdl.hxx> #include <ndtxt.hxx> #include <pam.hxx> #include <swserv.hxx> #include <sfx2/linkmgr.hxx> #include <swtypes.hxx> #include <undobj.hxx> #include <unobookmark.hxx> #include <rtl/random.h> #include <xmloff/odffields.hxx> SV_IMPL_REF( SwServerObject ) using namespace ::sw::mark; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace { static void lcl_FixPosition(SwPosition& rPos) { // make sure the position has 1) the proper node, and 2) a proper index SwTxtNode* pTxtNode = rPos.nNode.GetNode().GetTxtNode(); if(pTxtNode == NULL && rPos.nContent.GetIndex() > 0) { OSL_TRACE( "bookmrk.cxx::lcl_FixPosition" " - illegal position: %d without proper TxtNode", rPos.nContent.GetIndex()); rPos.nContent.Assign(NULL, 0); } else if(pTxtNode != NULL && rPos.nContent.GetIndex() > pTxtNode->Len()) { OSL_TRACE( "bookmrk.cxx::lcl_FixPosition" " - illegal position: %d is beyond %d", rPos.nContent.GetIndex(), pTxtNode->Len()); rPos.nContent.Assign(pTxtNode, pTxtNode->Len()); } }; static void lcl_AssureFieldMarksSet(Fieldmark* const pField, SwDoc* const io_pDoc, const sal_Unicode aStartMark, const sal_Unicode aEndMark) { SwPosition& rStart = pField->GetMarkStart(); SwPosition& rEnd = pField->GetMarkEnd(); SwTxtNode const * const pStartTxtNode = io_pDoc->GetNodes()[rStart.nNode]->GetTxtNode(); SwTxtNode const * const pEndTxtNode = io_pDoc->GetNodes()[rEnd.nNode]->GetTxtNode(); const sal_Unicode ch_start=pStartTxtNode->GetTxt().GetChar(rStart.nContent.GetIndex()); xub_StrLen nEndPos = rEnd.nContent.GetIndex() == 0 ? 0 : rEnd.nContent.GetIndex() - 1; const sal_Unicode ch_end=pEndTxtNode->GetTxt().GetChar( nEndPos ); SwPaM aStartPaM(rStart); SwPaM aEndPaM(rEnd); io_pDoc->StartUndo(UNDO_UI_REPLACE, NULL); if( ( ch_start != aStartMark ) && ( aEndMark != CH_TXT_ATR_FORMELEMENT ) ) { io_pDoc->InsertString(aStartPaM, aStartMark); rStart.nContent--; } if ( aEndMark && ( ch_end != aEndMark ) ) { io_pDoc->InsertString(aEndPaM, aEndMark); rEnd.nContent++; } io_pDoc->EndUndo(UNDO_UI_REPLACE, NULL); }; } namespace sw { namespace mark { MarkBase::MarkBase(const SwPaM& aPaM, const ::rtl::OUString& rName) : SwModify(0) , m_pPos1(new SwPosition(*(aPaM.GetPoint()))) , m_aName(rName) { lcl_FixPosition(*m_pPos1); if(aPaM.HasMark()) { MarkBase::SetOtherMarkPos(*(aPaM.GetMark())); lcl_FixPosition(*m_pPos2); } } bool MarkBase::IsCoveringPosition(const SwPosition& rPos) const { return GetMarkStart() <= rPos && rPos < GetMarkEnd(); } void MarkBase::SetMarkPos(const SwPosition& rNewPos) { ::boost::scoped_ptr<SwPosition>(new SwPosition(rNewPos)).swap(m_pPos1); //lcl_FixPosition(*m_pPos1); } void MarkBase::SetOtherMarkPos(const SwPosition& rNewPos) { ::boost::scoped_ptr<SwPosition>(new SwPosition(rNewPos)).swap(m_pPos2); //lcl_FixPosition(*m_pPos2); } rtl::OUString MarkBase::ToString( ) const { rtl::OUStringBuffer buf; buf.appendAscii( "Mark: ( Name, [ Node1, Index1 ] ): ( " ); buf.append( m_aName ).appendAscii( ", [ " ); buf.append( sal_Int32( GetMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetMarkPos().nContent.GetIndex( ) ) ).appendAscii( " ] )" ); return buf.makeStringAndClear( ); } MarkBase::~MarkBase() { } ::rtl::OUString MarkBase::GenerateNewName(const ::rtl::OUString& rPrefix) { static rtlRandomPool aPool = rtl_random_createPool(); static ::rtl::OUString sUniquePostfix; static sal_Int32 nCount = SAL_MAX_INT32; ::rtl::OUStringBuffer aResult(rPrefix); if(nCount == SAL_MAX_INT32) { sal_Int32 nRandom; ::rtl::OUStringBuffer sUniquePostfixBuffer; rtl_random_getBytes(aPool, &nRandom, sizeof(nRandom)); sUniquePostfix = ::rtl::OUStringBuffer(13).appendAscii("_").append(static_cast<sal_Int32>(abs(nRandom))).makeStringAndClear(); nCount = 0; } // putting the counter in front of the random parts will speed up string comparisons return aResult.append(nCount++).append(sUniquePostfix).makeStringAndClear(); } void MarkBase::Modify(SfxPoolItem *pOld, SfxPoolItem *pNew) { SwModify::Modify(pOld, pNew); if (pOld && (RES_REMOVE_UNO_OBJECT == pOld->Which())) { // invalidate cached uno object SetXBookmark(uno::Reference<text::XTextContent>(0)); } } NavigatorReminder::NavigatorReminder(const SwPaM& rPaM) : MarkBase(rPaM, our_sNamePrefix) { } const ::rtl::OUString NavigatorReminder::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__NavigatorReminder__")); UnoMark::UnoMark(const SwPaM& aPaM) : MarkBase(aPaM, MarkBase::GenerateNewName(our_sNamePrefix)) { } const ::rtl::OUString UnoMark::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__UnoMark__")); DdeBookmark::DdeBookmark(const SwPaM& aPaM) : MarkBase(aPaM, MarkBase::GenerateNewName(our_sNamePrefix)) , m_aRefObj(NULL) { } void DdeBookmark::SetRefObject(SwServerObject* pObj) { m_aRefObj = pObj; } const ::rtl::OUString DdeBookmark::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__DdeLink__")); void DdeBookmark::DeregisterFromDoc(SwDoc* const pDoc) { if(m_aRefObj.Is()) pDoc->GetLinkManager().RemoveServer(m_aRefObj); } DdeBookmark::~DdeBookmark() { if( m_aRefObj.Is() ) { if(m_aRefObj->HasDataLinks()) { ::sfx2::SvLinkSource* p = &m_aRefObj; p->SendDataChanged(); } m_aRefObj->SetNoServer(); } } Bookmark::Bookmark(const SwPaM& aPaM, const KeyCode& rCode, const ::rtl::OUString& rName, const ::rtl::OUString& rShortName) : DdeBookmark(aPaM) , ::sfx2::Metadatable() , m_aCode(rCode) , m_sShortName(rShortName) { m_aName = rName; } void Bookmark::InitDoc(SwDoc* const io_pDoc) { if(io_pDoc->DoesUndo()) { io_pDoc->ClearRedo(); io_pDoc->AppendUndo(new SwUndoInsBookmark(*this)); } io_pDoc->SetModified(); } // ::sfx2::Metadatable ::sfx2::IXmlIdRegistry& Bookmark::GetRegistry() { SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::MakeUnoObject: no doc?"); return pDoc->GetXmlIdRegistry(); } bool Bookmark::IsInClipboard() const { SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::IsInClipboard: no doc?"); return pDoc->IsClipBoard(); } bool Bookmark::IsInUndo() const { return false; } bool Bookmark::IsInContent() const { SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::IsInContent: no doc?"); return !pDoc->IsInHeaderFooter( SwNodeIndex(GetMarkPos().nNode) ); } uno::Reference< rdf::XMetadatable > Bookmark::MakeUnoObject() { // create new SwXBookmark SwDoc *const pDoc( GetMarkPos().GetDoc() ); OSL_ENSURE(pDoc, "Bookmark::MakeUnoObject: no doc?"); const uno::Reference< rdf::XMetadatable> xMeta( SwXBookmark::CreateXBookmark(*pDoc, *this), uno::UNO_QUERY); return xMeta; } Fieldmark::Fieldmark(const SwPaM& rPaM) : MarkBase(rPaM, MarkBase::GenerateNewName(our_sNamePrefix)) { if(!IsExpanded()) SetOtherMarkPos(GetMarkPos()); } rtl::OUString Fieldmark::ToString( ) const { rtl::OUStringBuffer buf; buf.appendAscii( "Fieldmark: ( Name, Type, [ Nd1, Id1 ], [ Nd2, Id2 ] ): ( " ); buf.append( m_aName ).appendAscii( ", " ); buf.append( m_aFieldname ).appendAscii( ", [ " ); buf.append( sal_Int32( GetMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ], [" ); buf.append( sal_Int32( GetOtherMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetOtherMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ] ) " ); return buf.makeStringAndClear( ); } void Fieldmark::Invalidate( ) { // @TODO: Does exist a better solution to trigger a format of the // fieldmark portion? If yes, please use it. SwPaM aPaM( this->GetMarkPos(), this->GetOtherMarkPos() ); aPaM.InvalidatePaM(); } const ::rtl::OUString Fieldmark::our_sNamePrefix(RTL_CONSTASCII_USTRINGPARAM("__Fieldmark__")); TextFieldmark::TextFieldmark(const SwPaM& rPaM) : Fieldmark(rPaM) { } void TextFieldmark::InitDoc(SwDoc* const io_pDoc) { lcl_AssureFieldMarksSet(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND); } CheckboxFieldmark::CheckboxFieldmark(const SwPaM& rPaM) : Fieldmark(rPaM) { } void CheckboxFieldmark::InitDoc(SwDoc* const io_pDoc) { lcl_AssureFieldMarksSet(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FORMELEMENT); // For some reason the end mark is moved from 1 by the Insert: we don't // want this for checkboxes this->GetMarkEnd( ).nContent--; } void CheckboxFieldmark::SetChecked(bool checked) { if ( IsChecked() != checked ) { (*GetParameters())[::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(ODF_FORMCHECKBOX_RESULT))] = makeAny(checked); // mark document as modified SwDoc *const pDoc( GetMarkPos().GetDoc() ); if ( pDoc ) pDoc->SetModified(); } } bool CheckboxFieldmark::IsChecked() const { bool bResult = false; parameter_map_t::const_iterator pResult = GetParameters()->find(::rtl::OUString::createFromAscii(ODF_FORMCHECKBOX_RESULT)); if(pResult != GetParameters()->end()) pResult->second >>= bResult; return bResult; } rtl::OUString CheckboxFieldmark::toString( ) const { rtl::OUStringBuffer buf; buf.appendAscii( "CheckboxFieldmark: ( Name, Type, [ Nd1, Id1 ], [ Nd2, Id2 ] ): ( " ); buf.append( m_aName ).appendAscii( ", " ); buf.append( GetFieldname() ).appendAscii( ", [ " ); buf.append( sal_Int32( GetMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ], [" ); buf.append( sal_Int32( GetOtherMarkPos().nNode.GetIndex( ) ) ).appendAscii( ", " ); buf.append( sal_Int32( GetOtherMarkPos( ).nContent.GetIndex( ) ) ).appendAscii( " ] ) " ); return buf.makeStringAndClear( ); } }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unocrsr.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:54:01 $ * * 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 * ************************************************************************/ #pragma hdrstop #ifndef _UNOCRSR_HXX #include <unocrsr.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _SWTABLE_HXX #include <swtable.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _ROOTFRM_HXX #include <rootfrm.hxx> #endif SV_IMPL_PTRARR( SwUnoCrsrTbl, SwUnoCrsrPtr ) IMPL_FIXEDMEMPOOL_NEWDEL( SwUnoCrsr, 10, 10 ) SwUnoCrsr::SwUnoCrsr( const SwPosition &rPos, SwPaM* pRing ) : SwCursor( rPos, pRing ), SwModify( 0 ), bRemainInSection( TRUE ), bSkipOverHiddenSections( FALSE ), bSkipOverProtectSections( FALSE ) {} // @@@ semantic: no copy ctor. SwUnoCrsr::SwUnoCrsr( SwUnoCrsr& rICrsr ) : SwCursor( rICrsr ), SwModify( 0 ), bRemainInSection( rICrsr.bRemainInSection ), bSkipOverHiddenSections( rICrsr.bSkipOverHiddenSections ), bSkipOverProtectSections( rICrsr.bSkipOverProtectSections ) {} SwUnoCrsr::~SwUnoCrsr() { SwDoc* pDoc = GetDoc(); if( !pDoc->IsInDtor() ) { // dann muss der Cursor aus dem Array ausgetragen werden SwUnoCrsrTbl& rTbl = (SwUnoCrsrTbl&)pDoc->GetUnoCrsrTbl(); USHORT nDelPos = rTbl.GetPos( this ); if( USHRT_MAX != nDelPos ) rTbl.Remove( nDelPos ); else ASSERT( !this, "UNO Cursor nicht mehr im Array" ); } // den gesamten Ring loeschen! while( GetNext() != this ) { Ring* pNxt = GetNext(); pNxt->MoveTo( 0 ); // ausketten delete pNxt; // und loeschen } } SwUnoCrsr::operator SwUnoCrsr* () { return this; } /* SwCursor* SwUnoCrsr::Create( SwPaM* pRing ) const { return new SwUnoCrsr( *GetPoint(), pRing ); } */ FASTBOOL SwUnoCrsr::IsSelOvr( int eFlags ) { if( bRemainInSection ) { SwDoc* pDoc = GetDoc(); SwNodeIndex aOldIdx( *pDoc->GetNodes()[ GetSavePos()->nNode ] ); SwNodeIndex& rPtIdx = GetPoint()->nNode; SwStartNode *pOldSttNd = aOldIdx.GetNode().StartOfSectionNode(), *pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); if( pOldSttNd != pNewSttNd ) { BOOL bMoveDown = GetSavePos()->nNode < rPtIdx.GetIndex(); BOOL bValidPos = FALSE; // search the correct surrounded start node - which the index // can't leave. while( pOldSttNd->IsSectionNode() ) pOldSttNd = pOldSttNd->StartOfSectionNode(); // is the new index inside this surrounded section? if( rPtIdx > *pOldSttNd && rPtIdx < pOldSttNd->EndOfSectionIndex() ) { // check if it a valid move inside this section // (only over SwSection's !) const SwStartNode* pInvalidNode; do { pInvalidNode = 0; pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); const SwStartNode *pSttNd = pNewSttNd, *pEndNd = pOldSttNd; if( pSttNd->EndOfSectionIndex() > pEndNd->EndOfSectionIndex() ) { pEndNd = pNewSttNd; pSttNd = pOldSttNd; } while( pSttNd->GetIndex() > pEndNd->GetIndex() ) { if( !pSttNd->IsSectionNode() ) pInvalidNode = pSttNd; pSttNd = pSttNd->StartOfSectionNode(); } if( pInvalidNode ) { if( bMoveDown ) { rPtIdx.Assign( *pInvalidNode->EndOfSectionNode(), 1 ); if( !rPtIdx.GetNode().IsCntntNode() && !pDoc->GetNodes().GoNextSection( &rPtIdx )) break; } else { rPtIdx.Assign( *pInvalidNode, -1 ); if( !rPtIdx.GetNode().IsCntntNode() && !pDoc->GetNodes().GoPrevSection( &rPtIdx )) break; } } else bValidPos = TRUE; } while ( pInvalidNode ); } if( bValidPos ) { SwCntntNode* pCNd = GetCntntNode(); USHORT nCnt = 0; if( pCNd && !bMoveDown ) nCnt = pCNd->Len(); GetPoint()->nContent.Assign( pCNd, nCnt ); } else { rPtIdx = GetSavePos()->nNode; GetPoint()->nContent.Assign( GetCntntNode(), GetSavePos()->nCntnt ); return TRUE; } } } return SwCursor::IsSelOvr( eFlags ); } /* */ SwUnoTableCrsr::SwUnoTableCrsr(const SwPosition& rPos) : SwCursor(rPos), SwUnoCrsr(rPos), SwTableCursor(rPos), aTblSel(rPos) { SetRemainInSection(FALSE); } SwUnoTableCrsr::~SwUnoTableCrsr() { while( aTblSel.GetNext() != &aTblSel ) delete aTblSel.GetNext(); // und loeschen } SwUnoTableCrsr::operator SwUnoCrsr* () { return this; } SwUnoTableCrsr::operator SwTableCursor* () { return this; } SwUnoTableCrsr::operator SwUnoTableCrsr* () { return this; } /* SwCursor* SwUnoTableCrsr::Create( SwPaM* pRing ) const { return SwUnoCrsr::Create( pRing ); } */ FASTBOOL SwUnoTableCrsr::IsSelOvr( int eFlags ) { FASTBOOL bRet = SwUnoCrsr::IsSelOvr( eFlags ); if( !bRet ) { const SwTableNode* pTNd = GetPoint()->nNode.GetNode().FindTableNode(); bRet = !(pTNd == GetDoc()->GetNodes()[ GetSavePos()->nNode ]-> FindTableNode() && (!HasMark() || pTNd == GetMark()->nNode.GetNode().FindTableNode() )); } return bRet; } void SwUnoTableCrsr::MakeBoxSels() { const SwCntntNode* pCNd; bool bMakeTblCrsrs = true; if( GetPoint()->nNode.GetIndex() && GetMark()->nNode.GetIndex() && 0 != ( pCNd = GetCntntNode() ) && pCNd->GetFrm() && 0 != ( pCNd = GetCntntNode(FALSE) ) && pCNd->GetFrm() ) bMakeTblCrsrs = GetDoc()->GetRootFrm()->MakeTblCrsrs( *this ); if ( !bMakeTblCrsrs ) { SwSelBoxes& rTmpBoxes = (SwSelBoxes&)GetBoxes(); USHORT nCount = 0; while( nCount < rTmpBoxes.Count() ) DeleteBox( nCount ); } if( IsChgd() ) { SwTableCursor::MakeBoxSels( &aTblSel ); if( !GetBoxesCount() ) { const SwTableBox* pBox; const SwNode* pBoxNd = GetPoint()->nNode.GetNode().FindTableBoxStartNode(); const SwTableNode* pTblNd = pBoxNd ? pBoxNd->FindTableNode() : 0; if( pTblNd && 0 != ( pBox = pTblNd->GetTable().GetTblBox( pBoxNd->GetIndex() )) ) InsertBox( *pBox ); } } } <commit_msg>INTEGRATION: CWS pchfix02 (1.10.2); FILE MERGED 2006/09/01 17:51:21 kaib 1.10.2.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unocrsr.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2006-09-16 20:48:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _UNOCRSR_HXX #include <unocrsr.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _SWTABLE_HXX #include <swtable.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _ROOTFRM_HXX #include <rootfrm.hxx> #endif SV_IMPL_PTRARR( SwUnoCrsrTbl, SwUnoCrsrPtr ) IMPL_FIXEDMEMPOOL_NEWDEL( SwUnoCrsr, 10, 10 ) SwUnoCrsr::SwUnoCrsr( const SwPosition &rPos, SwPaM* pRing ) : SwCursor( rPos, pRing ), SwModify( 0 ), bRemainInSection( TRUE ), bSkipOverHiddenSections( FALSE ), bSkipOverProtectSections( FALSE ) {} // @@@ semantic: no copy ctor. SwUnoCrsr::SwUnoCrsr( SwUnoCrsr& rICrsr ) : SwCursor( rICrsr ), SwModify( 0 ), bRemainInSection( rICrsr.bRemainInSection ), bSkipOverHiddenSections( rICrsr.bSkipOverHiddenSections ), bSkipOverProtectSections( rICrsr.bSkipOverProtectSections ) {} SwUnoCrsr::~SwUnoCrsr() { SwDoc* pDoc = GetDoc(); if( !pDoc->IsInDtor() ) { // dann muss der Cursor aus dem Array ausgetragen werden SwUnoCrsrTbl& rTbl = (SwUnoCrsrTbl&)pDoc->GetUnoCrsrTbl(); USHORT nDelPos = rTbl.GetPos( this ); if( USHRT_MAX != nDelPos ) rTbl.Remove( nDelPos ); else ASSERT( !this, "UNO Cursor nicht mehr im Array" ); } // den gesamten Ring loeschen! while( GetNext() != this ) { Ring* pNxt = GetNext(); pNxt->MoveTo( 0 ); // ausketten delete pNxt; // und loeschen } } SwUnoCrsr::operator SwUnoCrsr* () { return this; } /* SwCursor* SwUnoCrsr::Create( SwPaM* pRing ) const { return new SwUnoCrsr( *GetPoint(), pRing ); } */ FASTBOOL SwUnoCrsr::IsSelOvr( int eFlags ) { if( bRemainInSection ) { SwDoc* pDoc = GetDoc(); SwNodeIndex aOldIdx( *pDoc->GetNodes()[ GetSavePos()->nNode ] ); SwNodeIndex& rPtIdx = GetPoint()->nNode; SwStartNode *pOldSttNd = aOldIdx.GetNode().StartOfSectionNode(), *pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); if( pOldSttNd != pNewSttNd ) { BOOL bMoveDown = GetSavePos()->nNode < rPtIdx.GetIndex(); BOOL bValidPos = FALSE; // search the correct surrounded start node - which the index // can't leave. while( pOldSttNd->IsSectionNode() ) pOldSttNd = pOldSttNd->StartOfSectionNode(); // is the new index inside this surrounded section? if( rPtIdx > *pOldSttNd && rPtIdx < pOldSttNd->EndOfSectionIndex() ) { // check if it a valid move inside this section // (only over SwSection's !) const SwStartNode* pInvalidNode; do { pInvalidNode = 0; pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); const SwStartNode *pSttNd = pNewSttNd, *pEndNd = pOldSttNd; if( pSttNd->EndOfSectionIndex() > pEndNd->EndOfSectionIndex() ) { pEndNd = pNewSttNd; pSttNd = pOldSttNd; } while( pSttNd->GetIndex() > pEndNd->GetIndex() ) { if( !pSttNd->IsSectionNode() ) pInvalidNode = pSttNd; pSttNd = pSttNd->StartOfSectionNode(); } if( pInvalidNode ) { if( bMoveDown ) { rPtIdx.Assign( *pInvalidNode->EndOfSectionNode(), 1 ); if( !rPtIdx.GetNode().IsCntntNode() && !pDoc->GetNodes().GoNextSection( &rPtIdx )) break; } else { rPtIdx.Assign( *pInvalidNode, -1 ); if( !rPtIdx.GetNode().IsCntntNode() && !pDoc->GetNodes().GoPrevSection( &rPtIdx )) break; } } else bValidPos = TRUE; } while ( pInvalidNode ); } if( bValidPos ) { SwCntntNode* pCNd = GetCntntNode(); USHORT nCnt = 0; if( pCNd && !bMoveDown ) nCnt = pCNd->Len(); GetPoint()->nContent.Assign( pCNd, nCnt ); } else { rPtIdx = GetSavePos()->nNode; GetPoint()->nContent.Assign( GetCntntNode(), GetSavePos()->nCntnt ); return TRUE; } } } return SwCursor::IsSelOvr( eFlags ); } /* */ SwUnoTableCrsr::SwUnoTableCrsr(const SwPosition& rPos) : SwCursor(rPos), SwUnoCrsr(rPos), SwTableCursor(rPos), aTblSel(rPos) { SetRemainInSection(FALSE); } SwUnoTableCrsr::~SwUnoTableCrsr() { while( aTblSel.GetNext() != &aTblSel ) delete aTblSel.GetNext(); // und loeschen } SwUnoTableCrsr::operator SwUnoCrsr* () { return this; } SwUnoTableCrsr::operator SwTableCursor* () { return this; } SwUnoTableCrsr::operator SwUnoTableCrsr* () { return this; } /* SwCursor* SwUnoTableCrsr::Create( SwPaM* pRing ) const { return SwUnoCrsr::Create( pRing ); } */ FASTBOOL SwUnoTableCrsr::IsSelOvr( int eFlags ) { FASTBOOL bRet = SwUnoCrsr::IsSelOvr( eFlags ); if( !bRet ) { const SwTableNode* pTNd = GetPoint()->nNode.GetNode().FindTableNode(); bRet = !(pTNd == GetDoc()->GetNodes()[ GetSavePos()->nNode ]-> FindTableNode() && (!HasMark() || pTNd == GetMark()->nNode.GetNode().FindTableNode() )); } return bRet; } void SwUnoTableCrsr::MakeBoxSels() { const SwCntntNode* pCNd; bool bMakeTblCrsrs = true; if( GetPoint()->nNode.GetIndex() && GetMark()->nNode.GetIndex() && 0 != ( pCNd = GetCntntNode() ) && pCNd->GetFrm() && 0 != ( pCNd = GetCntntNode(FALSE) ) && pCNd->GetFrm() ) bMakeTblCrsrs = GetDoc()->GetRootFrm()->MakeTblCrsrs( *this ); if ( !bMakeTblCrsrs ) { SwSelBoxes& rTmpBoxes = (SwSelBoxes&)GetBoxes(); USHORT nCount = 0; while( nCount < rTmpBoxes.Count() ) DeleteBox( nCount ); } if( IsChgd() ) { SwTableCursor::MakeBoxSels( &aTblSel ); if( !GetBoxesCount() ) { const SwTableBox* pBox; const SwNode* pBoxNd = GetPoint()->nNode.GetNode().FindTableBoxStartNode(); const SwTableNode* pTblNd = pBoxNd ? pBoxNd->FindTableNode() : 0; if( pTblNd && 0 != ( pBox = pTblNd->GetTable().GetTblBox( pBoxNd->GetIndex() )) ) InsertBox( *pBox ); } } } <|endoftext|>
<commit_before><commit_msg>warning C4245: '=' : conversion from 'char' to 'sal_Unicode'...<commit_after><|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 <hintids.hxx> #include <vcl/msgbox.hxx> #include <svl/urihelper.hxx> #include <svl/stritem.hxx> #include <editeng/flstitem.hxx> #include <sfx2/htmlmode.hxx> #include <svl/cjkoptions.hxx> #include <cmdid.h> #include <helpid.h> #include <swtypes.hxx> #include <view.hxx> #include <wrtsh.hxx> #include <docsh.hxx> #include <uitool.hxx> #include <fmtinfmt.hxx> #include <macassgn.hxx> #include <chrdlg.hxx> #include <swmodule.hxx> #include <poolfmt.hxx> #include <globals.hrc> #include <chrdlg.hrc> #include <chrdlgmodes.hxx> #include <com/sun/star/ui/dialogs/TemplateDescription.hpp> #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #include <SwStyleNameMapper.hxx> #include <sfx2/filedlghelper.hxx> #include <sfx2/viewfrm.hxx> #include <svx/svxdlg.hxx> #include <svx/svxids.hrc> #include <svx/flagsdef.hxx> #include <svx/dialogs.hrc> using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::sfx2; SwCharDlg::SwCharDlg(vcl::Window* pParent, SwView& rVw, const SfxItemSet& rCoreSet, sal_uInt8 nDialogMode, const OUString* pStr) : SfxTabDialog(0, pParent, "CharacterPropertiesDialog", "modules/swriter/ui/characterproperties.ui", &rCoreSet, pStr != 0) , m_rView(rVw) , m_nDialogMode(nDialogMode) { if(pStr) { SetText(GetText() + SW_RESSTR(STR_TEXTCOLL_HEADER) + *pStr + ")"); } SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); OSL_ENSURE(pFact, "Dialog creation failed!"); m_nCharStdId = AddTabPage("font", pFact->GetTabPageCreatorFunc(RID_SVXPAGE_CHAR_NAME), 0); m_nCharExtId = AddTabPage("fonteffects", pFact->GetTabPageCreatorFunc(RID_SVXPAGE_CHAR_EFFECTS), 0); m_nCharPosId = AddTabPage("position", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_POSITION ), 0 ); m_nCharTwoId = AddTabPage("asianlayout", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_TWOLINES ), 0 ); m_nCharUrlId = AddTabPage("hyperlink", SwCharURLPage::Create, 0); m_nCharBgdId = AddTabPage("background", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 ); m_nCharBrdId = AddTabPage("borders", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), 0 ); SvtCJKOptions aCJKOptions; if(m_nDialogMode == DLG_CHAR_DRAW || m_nDialogMode == DLG_CHAR_ANN) { RemoveTabPage(m_nCharUrlId); RemoveTabPage(m_nCharBgdId); RemoveTabPage(m_nCharTwoId); } else if(!aCJKOptions.IsDoubleLinesEnabled()) RemoveTabPage(m_nCharTwoId); if(m_nDialogMode != DLG_CHAR_STD) RemoveTabPage(m_nCharBrdId); } SwCharDlg::~SwCharDlg() { } // set FontList void SwCharDlg::PageCreated( sal_uInt16 nId, SfxTabPage &rPage ) { SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); if (nId == m_nCharStdId) { SvxFontListItem aFontListItem( *( (SvxFontListItem*) ( m_rView.GetDocShell()->GetItem( SID_ATTR_CHAR_FONTLIST ) ) ) ); aSet.Put (SvxFontListItem( aFontListItem.GetFontList(), SID_ATTR_CHAR_FONTLIST)); if(m_nDialogMode != DLG_CHAR_DRAW && m_nDialogMode != DLG_CHAR_ANN) aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER)); rPage.PageCreated(aSet); } else if (nId == m_nCharExtId) { if(m_nDialogMode == DLG_CHAR_DRAW || m_nDialogMode == DLG_CHAR_ANN) aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP)); else { aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER|SVX_ENABLE_FLASH)); } rPage.PageCreated(aSet); } else if (nId == m_nCharPosId) { aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER)); rPage.PageCreated(aSet); } else if (nId == m_nCharTwoId) { aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER)); rPage.PageCreated(aSet); } } SwCharURLPage::SwCharURLPage(vcl::Window* pParent, const SfxItemSet& rCoreSet) : SfxTabPage(pParent, "CharURLPage", "modules/swriter/ui/charurlpage.ui", &rCoreSet) , pINetItem(0) , bModified(false) { get(m_pURLED, "urled"); get(m_pTextFT, "textft"); get(m_pTextED, "texted"); get(m_pNameED, "nameed"); get(m_pTargetFrmLB, "targetfrmlb"); get(m_pURLPB, "urlpb"); get(m_pEventPB, "eventpb"); get(m_pVisitedLB, "visitedlb"); get(m_pNotVisitedLB, "unvisitedlb"); get(m_pCharStyleContainer, "charstyle"); const SfxPoolItem* pItem; SfxObjectShell* pShell; if(SfxItemState::SET == rCoreSet.GetItemState(SID_HTML_MODE, false, &pItem) || ( 0 != ( pShell = SfxObjectShell::Current()) && 0 != (pItem = pShell->GetItem(SID_HTML_MODE)))) { sal_uInt16 nHtmlMode = ((const SfxUInt16Item*)pItem)->GetValue(); if(HTMLMODE_ON & nHtmlMode) m_pCharStyleContainer->Hide(); } m_pURLPB->SetClickHdl (LINK( this, SwCharURLPage, InsertFileHdl)); m_pEventPB->SetClickHdl(LINK( this, SwCharURLPage, EventHdl )); SwView *pView = ::GetActiveView(); ::FillCharStyleListBox(*m_pVisitedLB, pView->GetDocShell()); ::FillCharStyleListBox(*m_pNotVisitedLB, pView->GetDocShell()); TargetList* pList = new TargetList; const SfxFrame& rFrame = pView->GetViewFrame()->GetTopFrame(); rFrame.GetTargetList(*pList); if ( !pList->empty() ) { size_t nCount = pList->size(); for ( size_t i = 0; i < nCount; i++ ) { m_pTargetFrmLB->InsertEntry( pList->at( i ) ); } } delete pList; } SwCharURLPage::~SwCharURLPage() { delete pINetItem; } void SwCharURLPage::Reset(const SfxItemSet* rSet) { const SfxPoolItem* pItem; if ( SfxItemState::SET == rSet->GetItemState( RES_TXTATR_INETFMT, false, &pItem ) ) { const SwFmtINetFmt* pINetFmt = (const SwFmtINetFmt*) pItem; m_pURLED->SetText(INetURLObject::decode(pINetFmt->GetValue(), '%', INetURLObject::DECODE_UNAMBIGUOUS, RTL_TEXTENCODING_UTF8)); m_pURLED->SaveValue(); m_pURLED->SetText(pINetFmt->GetName()); OUString sEntry = pINetFmt->GetVisitedFmt(); if (sEntry.isEmpty()) { OSL_ENSURE( false, "<SwCharURLPage::Reset(..)> - missing visited character format at hyperlink attribute" ); SwStyleNameMapper::FillUIName(RES_POOLCHR_INET_VISIT, sEntry); } m_pVisitedLB->SelectEntry( sEntry ); sEntry = pINetFmt->GetINetFmt(); if (sEntry.isEmpty()) { OSL_ENSURE( false, "<SwCharURLPage::Reset(..)> - missing unvisited character format at hyperlink attribute" ); SwStyleNameMapper::FillUIName(RES_POOLCHR_INET_NORMAL, sEntry); } m_pNotVisitedLB->SelectEntry(sEntry); m_pTargetFrmLB->SetText(pINetFmt->GetTargetFrame()); m_pVisitedLB-> SaveValue(); m_pNotVisitedLB->SaveValue(); m_pTargetFrmLB-> SaveValue(); pINetItem = new SvxMacroItem(FN_INET_FIELD_MACRO); if( pINetFmt->GetMacroTbl() ) pINetItem->SetMacroTable( *pINetFmt->GetMacroTbl() ); } if(SfxItemState::SET == rSet->GetItemState(FN_PARAM_SELECTION, false, &pItem)) { m_pTextED->SetText(((const SfxStringItem*)pItem)->GetValue()); m_pTextFT->Enable( false ); m_pTextED->Enable( false ); } } bool SwCharURLPage::FillItemSet(SfxItemSet* rSet) { OUString sURL = m_pURLED->GetText(); if(!sURL.isEmpty()) { sURL = URIHelper::SmartRel2Abs(INetURLObject(), sURL, Link(), false ); // #i100683# file URLs should be normalized in the UI if ( sURL.startsWith("file:") ) sURL = URIHelper::simpleNormalizedMakeRelative(OUString(), sURL); } SwFmtINetFmt aINetFmt(sURL, m_pTargetFrmLB->GetText()); aINetFmt.SetName(m_pNameED->GetText()); bool bURLModified = m_pURLED->IsValueChangedFromSaved(); bool bNameModified = m_pNameED->IsModified(); bool bTargetModified = m_pTargetFrmLB->IsValueChangedFromSaved(); bModified = bURLModified | bNameModified | bTargetModified; // set valid settings first OUString sEntry = m_pVisitedLB->GetSelectEntry(); sal_uInt16 nId = SwStyleNameMapper::GetPoolIdFromUIName( sEntry, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT); aINetFmt.SetVisitedFmtAndId( sEntry, nId ); sEntry = m_pNotVisitedLB->GetSelectEntry(); nId = SwStyleNameMapper::GetPoolIdFromUIName( sEntry, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT); aINetFmt.SetINetFmtAndId( sEntry, nId ); if( pINetItem && !pINetItem->GetMacroTable().empty() ) aINetFmt.SetMacroTbl( &pINetItem->GetMacroTable() ); if(m_pVisitedLB->IsValueChangedFromSaved()) bModified = true; if(m_pNotVisitedLB->IsValueChangedFromSaved()) bModified = true; if(m_pTextED->IsModified()) { bModified = true; rSet->Put(SfxStringItem(FN_PARAM_SELECTION, m_pTextED->GetText())); } if(bModified) rSet->Put(aINetFmt); return bModified; } SfxTabPage* SwCharURLPage::Create( vcl::Window* pParent, const SfxItemSet* rAttrSet ) { return ( new SwCharURLPage( pParent, *rAttrSet ) ); } IMPL_LINK_NOARG(SwCharURLPage, InsertFileHdl) { FileDialogHelper aDlgHelper( TemplateDescription::FILEOPEN_SIMPLE, 0 ); if( aDlgHelper.Execute() == ERRCODE_NONE ) { Reference < XFilePicker > xFP = aDlgHelper.GetFilePicker(); m_pURLED->SetText(xFP->getFiles().getConstArray()[0]); } return 0; } IMPL_LINK_NOARG(SwCharURLPage, EventHdl) { bModified |= SwMacroAssignDlg::INetFmtDlg( this, ::GetActiveView()->GetWrtShell(), pINetItem ); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>this is more natural<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 <hintids.hxx> #include <vcl/msgbox.hxx> #include <svl/urihelper.hxx> #include <svl/stritem.hxx> #include <editeng/flstitem.hxx> #include <sfx2/htmlmode.hxx> #include <svl/cjkoptions.hxx> #include <cmdid.h> #include <helpid.h> #include <swtypes.hxx> #include <view.hxx> #include <wrtsh.hxx> #include <docsh.hxx> #include <uitool.hxx> #include <fmtinfmt.hxx> #include <macassgn.hxx> #include <chrdlg.hxx> #include <swmodule.hxx> #include <poolfmt.hxx> #include <globals.hrc> #include <chrdlg.hrc> #include <chrdlgmodes.hxx> #include <com/sun/star/ui/dialogs/TemplateDescription.hpp> #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #include <SwStyleNameMapper.hxx> #include <sfx2/filedlghelper.hxx> #include <sfx2/viewfrm.hxx> #include <svx/svxdlg.hxx> #include <svx/svxids.hrc> #include <svx/flagsdef.hxx> #include <svx/dialogs.hrc> using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::sfx2; SwCharDlg::SwCharDlg(vcl::Window* pParent, SwView& rVw, const SfxItemSet& rCoreSet, sal_uInt8 nDialogMode, const OUString* pStr) : SfxTabDialog(0, pParent, "CharacterPropertiesDialog", "modules/swriter/ui/characterproperties.ui", &rCoreSet, pStr != 0) , m_rView(rVw) , m_nDialogMode(nDialogMode) { if(pStr) { SetText(GetText() + SW_RESSTR(STR_TEXTCOLL_HEADER) + *pStr + ")"); } SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); OSL_ENSURE(pFact, "Dialog creation failed!"); m_nCharStdId = AddTabPage("font", pFact->GetTabPageCreatorFunc(RID_SVXPAGE_CHAR_NAME), 0); m_nCharExtId = AddTabPage("fonteffects", pFact->GetTabPageCreatorFunc(RID_SVXPAGE_CHAR_EFFECTS), 0); m_nCharPosId = AddTabPage("position", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_POSITION ), 0 ); m_nCharTwoId = AddTabPage("asianlayout", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_CHAR_TWOLINES ), 0 ); m_nCharUrlId = AddTabPage("hyperlink", SwCharURLPage::Create, 0); m_nCharBgdId = AddTabPage("background", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 ); m_nCharBrdId = AddTabPage("borders", pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), 0 ); SvtCJKOptions aCJKOptions; if(m_nDialogMode == DLG_CHAR_DRAW || m_nDialogMode == DLG_CHAR_ANN) { RemoveTabPage(m_nCharUrlId); RemoveTabPage(m_nCharBgdId); RemoveTabPage(m_nCharTwoId); } else if(!aCJKOptions.IsDoubleLinesEnabled()) RemoveTabPage(m_nCharTwoId); if(m_nDialogMode != DLG_CHAR_STD) RemoveTabPage(m_nCharBrdId); } SwCharDlg::~SwCharDlg() { } // set FontList void SwCharDlg::PageCreated( sal_uInt16 nId, SfxTabPage &rPage ) { SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); if (nId == m_nCharStdId) { SvxFontListItem aFontListItem( *( (SvxFontListItem*) ( m_rView.GetDocShell()->GetItem( SID_ATTR_CHAR_FONTLIST ) ) ) ); aSet.Put (SvxFontListItem( aFontListItem.GetFontList(), SID_ATTR_CHAR_FONTLIST)); if(m_nDialogMode != DLG_CHAR_DRAW && m_nDialogMode != DLG_CHAR_ANN) aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER)); rPage.PageCreated(aSet); } else if (nId == m_nCharExtId) { if(m_nDialogMode == DLG_CHAR_DRAW || m_nDialogMode == DLG_CHAR_ANN) aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP)); else { aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER|SVX_ENABLE_FLASH)); } rPage.PageCreated(aSet); } else if (nId == m_nCharPosId) { aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER)); rPage.PageCreated(aSet); } else if (nId == m_nCharTwoId) { aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_PREVIEW_CHARACTER)); rPage.PageCreated(aSet); } } SwCharURLPage::SwCharURLPage(vcl::Window* pParent, const SfxItemSet& rCoreSet) : SfxTabPage(pParent, "CharURLPage", "modules/swriter/ui/charurlpage.ui", &rCoreSet) , pINetItem(0) , bModified(false) { get(m_pURLED, "urled"); get(m_pTextFT, "textft"); get(m_pTextED, "texted"); get(m_pNameED, "nameed"); get(m_pTargetFrmLB, "targetfrmlb"); get(m_pURLPB, "urlpb"); get(m_pEventPB, "eventpb"); get(m_pVisitedLB, "visitedlb"); get(m_pNotVisitedLB, "unvisitedlb"); get(m_pCharStyleContainer, "charstyle"); const SfxPoolItem* pItem; SfxObjectShell* pShell; if(SfxItemState::SET == rCoreSet.GetItemState(SID_HTML_MODE, false, &pItem) || ( 0 != ( pShell = SfxObjectShell::Current()) && 0 != (pItem = pShell->GetItem(SID_HTML_MODE)))) { sal_uInt16 nHtmlMode = ((const SfxUInt16Item*)pItem)->GetValue(); if(HTMLMODE_ON & nHtmlMode) m_pCharStyleContainer->Hide(); } m_pURLPB->SetClickHdl (LINK( this, SwCharURLPage, InsertFileHdl)); m_pEventPB->SetClickHdl(LINK( this, SwCharURLPage, EventHdl )); SwView *pView = ::GetActiveView(); ::FillCharStyleListBox(*m_pVisitedLB, pView->GetDocShell()); ::FillCharStyleListBox(*m_pNotVisitedLB, pView->GetDocShell()); TargetList* pList = new TargetList; const SfxFrame& rFrame = pView->GetViewFrame()->GetTopFrame(); rFrame.GetTargetList(*pList); if ( !pList->empty() ) { size_t nCount = pList->size(); for ( size_t i = 0; i < nCount; i++ ) { m_pTargetFrmLB->InsertEntry( pList->at( i ) ); } } delete pList; } SwCharURLPage::~SwCharURLPage() { delete pINetItem; } void SwCharURLPage::Reset(const SfxItemSet* rSet) { const SfxPoolItem* pItem; if ( SfxItemState::SET == rSet->GetItemState( RES_TXTATR_INETFMT, false, &pItem ) ) { const SwFmtINetFmt* pINetFmt = (const SwFmtINetFmt*) pItem; m_pURLED->SetText(INetURLObject::decode(pINetFmt->GetValue(), '%', INetURLObject::DECODE_UNAMBIGUOUS, RTL_TEXTENCODING_UTF8)); m_pURLED->SaveValue(); m_pURLED->SetText(pINetFmt->GetName()); OUString sEntry = pINetFmt->GetVisitedFmt(); if (sEntry.isEmpty()) { OSL_ENSURE( false, "<SwCharURLPage::Reset(..)> - missing visited character format at hyperlink attribute" ); SwStyleNameMapper::FillUIName(RES_POOLCHR_INET_VISIT, sEntry); } m_pVisitedLB->SelectEntry( sEntry ); sEntry = pINetFmt->GetINetFmt(); if (sEntry.isEmpty()) { OSL_ENSURE( false, "<SwCharURLPage::Reset(..)> - missing unvisited character format at hyperlink attribute" ); SwStyleNameMapper::FillUIName(RES_POOLCHR_INET_NORMAL, sEntry); } m_pNotVisitedLB->SelectEntry(sEntry); m_pTargetFrmLB->SetText(pINetFmt->GetTargetFrame()); m_pVisitedLB-> SaveValue(); m_pNotVisitedLB->SaveValue(); m_pTargetFrmLB-> SaveValue(); pINetItem = new SvxMacroItem(FN_INET_FIELD_MACRO); if( pINetFmt->GetMacroTbl() ) pINetItem->SetMacroTable( *pINetFmt->GetMacroTbl() ); } if(SfxItemState::SET == rSet->GetItemState(FN_PARAM_SELECTION, false, &pItem)) { m_pTextED->SetText(((const SfxStringItem*)pItem)->GetValue()); m_pTextFT->Enable( false ); m_pTextED->Enable( false ); } } bool SwCharURLPage::FillItemSet(SfxItemSet* rSet) { OUString sURL = m_pURLED->GetText(); if(!sURL.isEmpty()) { sURL = URIHelper::SmartRel2Abs(INetURLObject(), sURL, Link(), false ); // #i100683# file URLs should be normalized in the UI if ( sURL.startsWith("file:") ) sURL = URIHelper::simpleNormalizedMakeRelative(OUString(), sURL); } SwFmtINetFmt aINetFmt(sURL, m_pTargetFrmLB->GetText()); aINetFmt.SetName(m_pNameED->GetText()); bool bURLModified = m_pURLED->IsValueChangedFromSaved(); bool bNameModified = m_pNameED->IsModified(); bool bTargetModified = m_pTargetFrmLB->IsValueChangedFromSaved(); bModified = bURLModified || bNameModified || bTargetModified; // set valid settings first OUString sEntry = m_pVisitedLB->GetSelectEntry(); sal_uInt16 nId = SwStyleNameMapper::GetPoolIdFromUIName( sEntry, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT); aINetFmt.SetVisitedFmtAndId( sEntry, nId ); sEntry = m_pNotVisitedLB->GetSelectEntry(); nId = SwStyleNameMapper::GetPoolIdFromUIName( sEntry, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT); aINetFmt.SetINetFmtAndId( sEntry, nId ); if( pINetItem && !pINetItem->GetMacroTable().empty() ) aINetFmt.SetMacroTbl( &pINetItem->GetMacroTable() ); if(m_pVisitedLB->IsValueChangedFromSaved()) bModified = true; if(m_pNotVisitedLB->IsValueChangedFromSaved()) bModified = true; if(m_pTextED->IsModified()) { bModified = true; rSet->Put(SfxStringItem(FN_PARAM_SELECTION, m_pTextED->GetText())); } if(bModified) rSet->Put(aINetFmt); return bModified; } SfxTabPage* SwCharURLPage::Create( vcl::Window* pParent, const SfxItemSet* rAttrSet ) { return ( new SwCharURLPage( pParent, *rAttrSet ) ); } IMPL_LINK_NOARG(SwCharURLPage, InsertFileHdl) { FileDialogHelper aDlgHelper( TemplateDescription::FILEOPEN_SIMPLE, 0 ); if( aDlgHelper.Execute() == ERRCODE_NONE ) { Reference < XFilePicker > xFP = aDlgHelper.GetFilePicker(); m_pURLED->SetText(xFP->getFiles().getConstArray()[0]); } return 0; } IMPL_LINK_NOARG(SwCharURLPage, EventHdl) { bModified |= SwMacroAssignDlg::INetFmtDlg( this, ::GetActiveView()->GetWrtShell(), pINetItem ); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/***************************************************************************** maskFastaFromBed.cpp (c) 2009 - Aaron Quinlan Hall Laboratory Department of Biochemistry and Molecular Genetics University of Virginia [email protected] Licenced under the GNU General Public License 2.0 license. ******************************************************************************/ #include "lineFileUtilities.h" #include "maskFastaFromBed.h" MaskFastaFromBed::MaskFastaFromBed(const string &fastaInFile, const string &bedFile, const string &fastaOutFile, bool softMask, char maskChar, bool useFullHeader) { _softMask = softMask; _fastaInFile = fastaInFile; _bedFile = bedFile; _fastaOutFile = fastaOutFile; _maskChar = maskChar; _useFullHeader = useFullHeader; _bed = new BedFile(_bedFile); _bed->loadBedFileIntoMapNoBin(); // start masking. MaskFasta(); } MaskFastaFromBed::~MaskFastaFromBed(void) { } //****************************************************************************** // Mask the Fasta file based on the coordinates in the BED file. //****************************************************************************** void MaskFastaFromBed::MaskFasta() { /* Make sure that we can open all of the files successfully*/ // open the fasta database for reading ifstream fa(_fastaInFile.c_str(), ios::in); if ( !fa ) { cerr << "Error: The requested fasta file (" << _fastaInFile << ") could not be opened. Exiting!" << endl; exit (1); } // open the fasta database for reading ofstream faOut(_fastaOutFile.c_str(), ios::out); if ( !faOut ) { cerr << "Error: The requested fasta output file (" << _fastaOutFile << ") could not be opened. Exiting!" << endl; exit (1); } /* Read the fastaDb chromosome by chromosome*/ string fastaInLine; string currChromFull; string currChrom; string currDNA = ""; currDNA.reserve(500000000); CHRPOS fastaWidth = -1; bool widthSet = false; CHRPOS start, end, length; string replacement; while (getline(fa,fastaInLine)) { if (fastaInLine.find(">",0) != 0 ) { if (widthSet == false) { fastaWidth = fastaInLine.size(); widthSet = true; } currDNA += fastaInLine; } else { if (currDNA.size() > 0) { vector<BED> bedList = _bed->bedMapNoBin[currChrom]; /* loop through each BED entry for this chrom and mask the requested sequence in the FASTA file. */ for (unsigned int i = 0; i < bedList.size(); i++) { start = bedList[i].start; end = bedList[i].end; length = end - start; /* (1) if soft masking, extract the sequence, lowercase it, then put it back (2) otherwise replace with Ns */ if (_softMask) { replacement = currDNA.substr(start, length); toLowerCase(replacement); currDNA.replace(start, length, replacement); } else { string hardmask(length, _maskChar); currDNA.replace(start, length, hardmask); } } // write the masked chrom to the output file PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth); } // reset for the next chromosome. currChromFull = fastaInLine.substr(1); currChrom = split(currChromFull, " \t").at(0); currDNA = ""; } } // process the last chromosome. // exact same logic as in the main loop. if (currDNA.size() > 0) { vector<BED> bedList = _bed->bedMapNoBin[currChrom]; for (unsigned int i = 0; i < bedList.size(); i++) { start = bedList[i].start; end = bedList[i].end; length = end - start; if (_softMask) { replacement = currDNA.substr(start, length); toLowerCase(replacement); currDNA.replace(start, length, replacement); } else { string hardmask(length, _maskChar); currDNA.replace(start, length, hardmask); } } PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth); } // closed for business. fa.close(); faOut.close(); } void MaskFastaFromBed::PrettyPrintChrom(ofstream &out, string chrom, const string &sequence, CHRPOS width) { CHRPOS seqLength = sequence.size(); out << ">" << chrom << endl; for(CHRPOS i = 0; i < seqLength; i += (CHRPOS)width) { if (i + width < seqLength) out << sequence.substr(i, width) << endl; else out << sequence.substr(i, seqLength-i) << endl; } } <commit_msg>performance fix for #720<commit_after>/***************************************************************************** maskFastaFromBed.cpp (c) 2009 - Aaron Quinlan Hall Laboratory Department of Biochemistry and Molecular Genetics University of Virginia [email protected] Licenced under the GNU General Public License 2.0 license. ******************************************************************************/ #include "lineFileUtilities.h" #include "maskFastaFromBed.h" MaskFastaFromBed::MaskFastaFromBed(const string &fastaInFile, const string &bedFile, const string &fastaOutFile, bool softMask, char maskChar, bool useFullHeader) { _softMask = softMask; _fastaInFile = fastaInFile; _bedFile = bedFile; _fastaOutFile = fastaOutFile; _maskChar = maskChar; _useFullHeader = useFullHeader; _bed = new BedFile(_bedFile); _bed->loadBedFileIntoMapNoBin(); // start masking. MaskFasta(); } MaskFastaFromBed::~MaskFastaFromBed(void) { } //****************************************************************************** // Mask the Fasta file based on the coordinates in the BED file. //****************************************************************************** void MaskFastaFromBed::MaskFasta() { /* Make sure that we can open all of the files successfully*/ // open the fasta database for reading ifstream fa(_fastaInFile.c_str(), ios::in); if ( !fa ) { cerr << "Error: The requested fasta file (" << _fastaInFile << ") could not be opened. Exiting!" << endl; exit (1); } // open the fasta database for reading ofstream faOut(_fastaOutFile.c_str(), ios::out); if ( !faOut ) { cerr << "Error: The requested fasta output file (" << _fastaOutFile << ") could not be opened. Exiting!" << endl; exit (1); } /* Read the fastaDb chromosome by chromosome*/ string fastaInLine; string currChromFull; string currChrom; string currDNA = ""; currDNA.reserve(500000000); CHRPOS fastaWidth = -1; bool widthSet = false; CHRPOS start, end, length; string replacement; while (getline(fa,fastaInLine)) { if (fastaInLine.find(">",0) != 0 ) { if (widthSet == false) { fastaWidth = fastaInLine.size(); widthSet = true; } currDNA += fastaInLine; } else { if (currDNA.size() > 0) { vector<BED> bedList = _bed->bedMapNoBin[currChrom]; /* loop through each BED entry for this chrom and mask the requested sequence in the FASTA file. */ for (unsigned int i = 0; i < bedList.size(); i++) { start = bedList[i].start; end = bedList[i].end; length = end - start; /* (1) if soft masking, extract the sequence, lowercase it, then put it back (2) otherwise replace with Ns */ if (_softMask) { replacement = currDNA.substr(start, length); toLowerCase(replacement); currDNA.replace(start, length, replacement); } else { string hardmask(length, _maskChar); currDNA.replace(start, length, hardmask); } } // write the masked chrom to the output file PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth); } // reset for the next chromosome. currChromFull = fastaInLine.substr(1); currChrom = split(currChromFull, " \t").at(0); currDNA = ""; } } // process the last chromosome. // exact same logic as in the main loop. if (currDNA.size() > 0) { vector<BED> bedList = _bed->bedMapNoBin[currChrom]; for (unsigned int i = 0; i < bedList.size(); i++) { start = bedList[i].start; end = bedList[i].end; length = end - start; if (_softMask) { replacement = currDNA.substr(start, length); toLowerCase(replacement); currDNA.replace(start, length, replacement); } else { string hardmask(length, _maskChar); currDNA.replace(start, length, hardmask); } } PrettyPrintChrom(faOut, _useFullHeader ? currChromFull : currChrom, currDNA, fastaWidth); } // closed for business. fa.close(); faOut.close(); } void MaskFastaFromBed::PrettyPrintChrom(ofstream &out, string chrom, const string &sequence, CHRPOS width) { CHRPOS seqLength = sequence.size(); out << ">" << chrom << '\n'; for(CHRPOS i = 0; i < seqLength; i += (CHRPOS)width) { if (i + width < seqLength) out << sequence.substr(i, width) << '\n'; else out << sequence.substr(i, seqLength-i) << '\n'; } out.flush(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/clock.h" #if defined(_WIN32) #include <Windows.h> #include <WinSock.h> #include <MMSystem.h> #elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC)) #include <sys/time.h> #include <time.h> #endif #include "webrtc/system_wrappers/interface/tick_util.h" namespace webrtc { #if defined(_WIN32) struct reference_point { FILETIME file_time; LARGE_INTEGER counterMS; }; struct WindowsHelpTimer { volatile LONG _timeInMs; volatile LONG _numWrapTimeInMs; reference_point _ref_point; volatile LONG _sync_flag; }; void Synchronize(WindowsHelpTimer* help_timer) { const LONG start_value = 0; const LONG new_value = 1; const LONG synchronized_value = 2; LONG compare_flag = new_value; while (help_timer->_sync_flag == start_value) { const LONG new_value = 1; compare_flag = InterlockedCompareExchange( &help_timer->_sync_flag, new_value, start_value); } if (compare_flag != start_value) { // This thread was not the one that incremented the sync flag. // Block until synchronization finishes. while (compare_flag != synchronized_value) { ::Sleep(0); } return; } // Only the synchronizing thread gets here so this part can be // considered single threaded. // set timer accuracy to 1 ms timeBeginPeriod(1); FILETIME ft0 = { 0, 0 }, ft1 = { 0, 0 }; // // Spin waiting for a change in system time. Get the matching // performance counter value for that time. // ::GetSystemTimeAsFileTime(&ft0); do { ::GetSystemTimeAsFileTime(&ft1); help_timer->_ref_point.counterMS.QuadPart = ::timeGetTime(); ::Sleep(0); } while ((ft0.dwHighDateTime == ft1.dwHighDateTime) && (ft0.dwLowDateTime == ft1.dwLowDateTime)); help_timer->_ref_point.file_time = ft1; } void get_time(WindowsHelpTimer* help_timer, FILETIME& current_time) { // we can't use query performance counter due to speed stepping DWORD t = timeGetTime(); // NOTE: we have a missmatch in sign between _timeInMs(LONG) and // (DWORD) however we only use it here without +- etc volatile LONG* timeInMsPtr = &help_timer->_timeInMs; // Make sure that we only inc wrapper once. DWORD old = InterlockedExchange(timeInMsPtr, t); if(old > t) { // wrap help_timer->_numWrapTimeInMs++; } LARGE_INTEGER elapsedMS; elapsedMS.HighPart = help_timer->_numWrapTimeInMs; elapsedMS.LowPart = t; elapsedMS.QuadPart = elapsedMS.QuadPart - help_timer->_ref_point.counterMS.QuadPart; // Translate to 100-nanoseconds intervals (FILETIME resolution) // and add to reference FILETIME to get current FILETIME. ULARGE_INTEGER filetime_ref_as_ul; filetime_ref_as_ul.HighPart = help_timer->_ref_point.file_time.dwHighDateTime; filetime_ref_as_ul.LowPart = help_timer->_ref_point.file_time.dwLowDateTime; filetime_ref_as_ul.QuadPart += (ULONGLONG)((elapsedMS.QuadPart)*1000*10); // Copy to result current_time.dwHighDateTime = filetime_ref_as_ul.HighPart; current_time.dwLowDateTime = filetime_ref_as_ul.LowPart; } #endif class RealTimeClock : public Clock { // Return a timestamp in milliseconds relative to some arbitrary source; the // source is fixed for this clock. virtual int64_t TimeInMilliseconds() { return TickTime::MillisecondTimestamp(); } // Return a timestamp in microseconds relative to some arbitrary source; the // source is fixed for this clock. virtual int64_t TimeInMicroseconds() { return TickTime::MicrosecondTimestamp(); } }; #if defined(_WIN32) class WindowsRealTimeClock : public RealTimeClock { public: WindowsRealTimeClock(WindowsHelpTimer* helpTimer) : _helpTimer(helpTimer) {} virtual ~WindowsRealTimeClock() {} // Retrieve an NTP absolute timestamp. virtual void CurrentNtp(uint32_t& seconds, uint32_t& fractions) { const WebRtc_UWord64 FILETIME_1970 = 0x019db1ded53e8000; FILETIME StartTime; WebRtc_UWord64 Time; struct timeval tv; // We can't use query performance counter since they can change depending on // speed steping get_time(_helpTimer, StartTime); Time = (((WebRtc_UWord64) StartTime.dwHighDateTime) << 32) + (WebRtc_UWord64) StartTime.dwLowDateTime; // Convert the hecto-nano second time to tv format Time -= FILETIME_1970; tv.tv_sec = (WebRtc_UWord32)(Time / (WebRtc_UWord64)10000000); tv.tv_usec = (WebRtc_UWord32)((Time % (WebRtc_UWord64)10000000) / 10); double dtemp; seconds = tv.tv_sec + kNtpJan1970; dtemp = tv.tv_usec / 1e6; if (dtemp >= 1) { dtemp -= 1; seconds++; } else if (dtemp < -1) { dtemp += 1; seconds--; } dtemp *= kMagicNtpFractionalUnit; fractions = (WebRtc_UWord32)dtemp; } private: WindowsHelpTimer* _helpTimer; }; #elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC)) class UnixRealTimeClock : public RealTimeClock { public: UnixRealTimeClock() {} virtual ~UnixRealTimeClock() {} // Retrieve an NTP absolute timestamp. virtual void CurrentNtp(uint32_t& seconds, uint32_t& fractions) { double dtemp; struct timeval tv; struct timezone tz; tz.tz_minuteswest = 0; tz.tz_dsttime = 0; gettimeofday(&tv, &tz); seconds = tv.tv_sec + kNtpJan1970; dtemp = tv.tv_usec / 1e6; if (dtemp >= 1) { dtemp -= 1; seconds++; } else if (dtemp < -1) { dtemp += 1; seconds--; } dtemp *= kMagicNtpFractionalUnit; fractions = (WebRtc_UWord32)dtemp; } }; #endif #if defined(_WIN32) // Keeps the global state for the Windows implementation of RtpRtcpClock. // Note that this is a POD. Only PODs are allowed to have static storage // duration according to the Google Style guide. static WindowsHelpTimer global_help_timer = {0, 0, {{ 0, 0}, 0}, 0}; #endif Clock* Clock::GetRealTimeClock() { #if defined(_WIN32) return new WindowsRealTimeClock(&global_help_timer); #elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) return new UnixRealTimeClock(); #else return NULL; #endif } SimulatedClock::SimulatedClock() : time_us_(0) {} SimulatedClock::SimulatedClock(int64_t initial_time_us) : time_us_(initial_time_us) {} int64_t SimulatedClock::TimeInMilliseconds() { return (time_us_ + 500) / 1000; } int64_t SimulatedClock::TimeInMicroseconds() { return time_us_; } void SimulatedClock::CurrentNtp(uint32_t& seconds, uint32_t& fractions) { seconds = (TimeInMilliseconds() / 1000) + kNtpJan1970; fractions = (uint32_t)((TimeInMilliseconds() % 1000) * kMagicNtpFractionalUnit / 1000); } void SimulatedClock::AdvanceTimeMs(int64_t milliseconds) { AdvanceTimeUs(1000 * milliseconds); } void SimulatedClock::AdvanceTimeUs(int64_t microseconds) { time_us_ += microseconds; } }; // namespace webrtc <commit_msg>Adding timeEndPeriod to Synchronize function, see bug for details.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/clock.h" #if defined(_WIN32) #include <Windows.h> #include <WinSock.h> #include <MMSystem.h> #elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC)) #include <sys/time.h> #include <time.h> #endif #include "webrtc/system_wrappers/interface/tick_util.h" namespace webrtc { #if defined(_WIN32) struct reference_point { FILETIME file_time; LARGE_INTEGER counterMS; }; struct WindowsHelpTimer { volatile LONG _timeInMs; volatile LONG _numWrapTimeInMs; reference_point _ref_point; volatile LONG _sync_flag; }; void Synchronize(WindowsHelpTimer* help_timer) { const LONG start_value = 0; const LONG new_value = 1; const LONG synchronized_value = 2; LONG compare_flag = new_value; while (help_timer->_sync_flag == start_value) { const LONG new_value = 1; compare_flag = InterlockedCompareExchange( &help_timer->_sync_flag, new_value, start_value); } if (compare_flag != start_value) { // This thread was not the one that incremented the sync flag. // Block until synchronization finishes. while (compare_flag != synchronized_value) { ::Sleep(0); } return; } // Only the synchronizing thread gets here so this part can be // considered single threaded. // set timer accuracy to 1 ms timeBeginPeriod(1); FILETIME ft0 = { 0, 0 }, ft1 = { 0, 0 }; // // Spin waiting for a change in system time. Get the matching // performance counter value for that time. // ::GetSystemTimeAsFileTime(&ft0); do { ::GetSystemTimeAsFileTime(&ft1); help_timer->_ref_point.counterMS.QuadPart = ::timeGetTime(); ::Sleep(0); } while ((ft0.dwHighDateTime == ft1.dwHighDateTime) && (ft0.dwLowDateTime == ft1.dwLowDateTime)); help_timer->_ref_point.file_time = ft1; timeEndPeriod(1); } void get_time(WindowsHelpTimer* help_timer, FILETIME& current_time) { // we can't use query performance counter due to speed stepping DWORD t = timeGetTime(); // NOTE: we have a missmatch in sign between _timeInMs(LONG) and // (DWORD) however we only use it here without +- etc volatile LONG* timeInMsPtr = &help_timer->_timeInMs; // Make sure that we only inc wrapper once. DWORD old = InterlockedExchange(timeInMsPtr, t); if(old > t) { // wrap help_timer->_numWrapTimeInMs++; } LARGE_INTEGER elapsedMS; elapsedMS.HighPart = help_timer->_numWrapTimeInMs; elapsedMS.LowPart = t; elapsedMS.QuadPart = elapsedMS.QuadPart - help_timer->_ref_point.counterMS.QuadPart; // Translate to 100-nanoseconds intervals (FILETIME resolution) // and add to reference FILETIME to get current FILETIME. ULARGE_INTEGER filetime_ref_as_ul; filetime_ref_as_ul.HighPart = help_timer->_ref_point.file_time.dwHighDateTime; filetime_ref_as_ul.LowPart = help_timer->_ref_point.file_time.dwLowDateTime; filetime_ref_as_ul.QuadPart += (ULONGLONG)((elapsedMS.QuadPart)*1000*10); // Copy to result current_time.dwHighDateTime = filetime_ref_as_ul.HighPart; current_time.dwLowDateTime = filetime_ref_as_ul.LowPart; } #endif class RealTimeClock : public Clock { // Return a timestamp in milliseconds relative to some arbitrary source; the // source is fixed for this clock. virtual int64_t TimeInMilliseconds() { return TickTime::MillisecondTimestamp(); } // Return a timestamp in microseconds relative to some arbitrary source; the // source is fixed for this clock. virtual int64_t TimeInMicroseconds() { return TickTime::MicrosecondTimestamp(); } }; #if defined(_WIN32) class WindowsRealTimeClock : public RealTimeClock { public: WindowsRealTimeClock(WindowsHelpTimer* helpTimer) : _helpTimer(helpTimer) {} virtual ~WindowsRealTimeClock() {} // Retrieve an NTP absolute timestamp. virtual void CurrentNtp(uint32_t& seconds, uint32_t& fractions) { const WebRtc_UWord64 FILETIME_1970 = 0x019db1ded53e8000; FILETIME StartTime; WebRtc_UWord64 Time; struct timeval tv; // We can't use query performance counter since they can change depending on // speed steping get_time(_helpTimer, StartTime); Time = (((WebRtc_UWord64) StartTime.dwHighDateTime) << 32) + (WebRtc_UWord64) StartTime.dwLowDateTime; // Convert the hecto-nano second time to tv format Time -= FILETIME_1970; tv.tv_sec = (WebRtc_UWord32)(Time / (WebRtc_UWord64)10000000); tv.tv_usec = (WebRtc_UWord32)((Time % (WebRtc_UWord64)10000000) / 10); double dtemp; seconds = tv.tv_sec + kNtpJan1970; dtemp = tv.tv_usec / 1e6; if (dtemp >= 1) { dtemp -= 1; seconds++; } else if (dtemp < -1) { dtemp += 1; seconds--; } dtemp *= kMagicNtpFractionalUnit; fractions = (WebRtc_UWord32)dtemp; } private: WindowsHelpTimer* _helpTimer; }; #elif ((defined WEBRTC_LINUX) || (defined WEBRTC_MAC)) class UnixRealTimeClock : public RealTimeClock { public: UnixRealTimeClock() {} virtual ~UnixRealTimeClock() {} // Retrieve an NTP absolute timestamp. virtual void CurrentNtp(uint32_t& seconds, uint32_t& fractions) { double dtemp; struct timeval tv; struct timezone tz; tz.tz_minuteswest = 0; tz.tz_dsttime = 0; gettimeofday(&tv, &tz); seconds = tv.tv_sec + kNtpJan1970; dtemp = tv.tv_usec / 1e6; if (dtemp >= 1) { dtemp -= 1; seconds++; } else if (dtemp < -1) { dtemp += 1; seconds--; } dtemp *= kMagicNtpFractionalUnit; fractions = (WebRtc_UWord32)dtemp; } }; #endif #if defined(_WIN32) // Keeps the global state for the Windows implementation of RtpRtcpClock. // Note that this is a POD. Only PODs are allowed to have static storage // duration according to the Google Style guide. static WindowsHelpTimer global_help_timer = {0, 0, {{ 0, 0}, 0}, 0}; #endif Clock* Clock::GetRealTimeClock() { #if defined(_WIN32) return new WindowsRealTimeClock(&global_help_timer); #elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC) return new UnixRealTimeClock(); #else return NULL; #endif } SimulatedClock::SimulatedClock() : time_us_(0) {} SimulatedClock::SimulatedClock(int64_t initial_time_us) : time_us_(initial_time_us) {} int64_t SimulatedClock::TimeInMilliseconds() { return (time_us_ + 500) / 1000; } int64_t SimulatedClock::TimeInMicroseconds() { return time_us_; } void SimulatedClock::CurrentNtp(uint32_t& seconds, uint32_t& fractions) { seconds = (TimeInMilliseconds() / 1000) + kNtpJan1970; fractions = (uint32_t)((TimeInMilliseconds() % 1000) * kMagicNtpFractionalUnit / 1000); } void SimulatedClock::AdvanceTimeMs(int64_t milliseconds) { AdvanceTimeUs(1000 * milliseconds); } void SimulatedClock::AdvanceTimeUs(int64_t microseconds) { time_us_ += microseconds; } }; // namespace webrtc <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <smsclnt.h> #include <smuthdr.h> // CSmsHeader #include <rsendas.h> #include <rsendasmessage.h> #include <f32file.h> #include <mmsconst.h> #include <utf.h> // CnvUtfConverter #include "qmessageservice.h" #include "qmessageservice_symbian_p.h" #include "qmtmengine_symbian_p.h" #include "qmessage_symbian_p.h" #include "symbianhelpers_p.h" #ifdef FREESTYLEMAILUSED #include "qfsengine_symbian_p.h" #endif QTM_BEGIN_NAMESPACE QMessageServicePrivate::QMessageServicePrivate(QMessageService* parent) : q_ptr(parent), _state(QMessageService::InactiveState), _active(false) { } QMessageServicePrivate::~QMessageServicePrivate() { } bool QMessageServicePrivate::sendSMS(QMessage &message) { return CMTMEngine::instance()->sendSMS(message); } bool QMessageServicePrivate::sendMMS(QMessage &message) { return CMTMEngine::instance()->sendMMS(message); } bool QMessageServicePrivate::sendEmail(QMessage &message) { if (SymbianHelpers::isFreestyleAccount(message.parentAccountId())) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->sendEmail(message); #else return false; #endif } else return CMTMEngine::instance()->sendEmail(message); } bool QMessageServicePrivate::show(const QMessageId& id) { QMessageId fsId = id; if (SymbianHelpers::isFreestyleMessage(fsId)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->showMessage(id); #else return false; #endif } else return CMTMEngine::instance()->showMessage(id); } bool QMessageServicePrivate::compose(const QMessage &message) { return CMTMEngine::instance()->composeMessage(message); } bool QMessageServicePrivate::queryMessages(const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { //return CMTMEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, sortOrder, limit, offset); return CFSEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, sortOrder, limit, offset); } bool QMessageServicePrivate::queryMessages(const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { return CMTMEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, body, matchFlags, sortOrder, limit, offset); } bool QMessageServicePrivate::countMessages(const QMessageFilter &filter) { return CMTMEngine::instance()->countMessages((QMessageServicePrivate&)*this, filter); } bool QMessageServicePrivate::retrieve(const QMessageId &messageId, const QMessageContentContainerId &id) { if (SymbianHelpers::isFreestyleMessage(messageId)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->retrieve(messageId, id); #else return false; #endif } else return CMTMEngine::instance()->retrieve(messageId, id); } bool QMessageServicePrivate::retrieveBody(const QMessageId& id) { if (SymbianHelpers::isFreestyleMessage(id)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->retrieveBody(id); #else return false; #endif } else return CMTMEngine::instance()->retrieveBody(id); } bool QMessageServicePrivate::retrieveHeader(const QMessageId& id) { if (SymbianHelpers::isFreestyleMessage(id)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->retrieveHeader(id); #else return false; #endif } else return CMTMEngine::instance()->retrieveHeader(id); } bool QMessageServicePrivate::exportUpdates(const QMessageAccountId &id) { // if (SymbianHelpers::isFreestyleMessage(id)) // return CFSEngine::instance()->exportUpdates(id); // else return CMTMEngine::instance()->exportUpdates(id); } void QMessageServicePrivate::setFinished(bool successful) { if (!successful && (_error == QMessageManager::NoError)) { // We must report an error of some sort _error = QMessageManager::RequestIncomplete; } _state = QMessageService::FinishedState; emit q_ptr->stateChanged(_state); _active = false; } QMessageService::QMessageService(QObject *parent) : QObject(parent), d_ptr(new QMessageServicePrivate(this)) { connect(d_ptr, SIGNAL(stateChanged(QMessageService::State)), this, SIGNAL(stateChanged(QMessageService::State))); connect(d_ptr, SIGNAL(messagesFound(const QMessageIdList&)), this, SIGNAL(messagesFound(const QMessageIdList&))); connect(d_ptr, SIGNAL(messagesCounted(int)), this, SIGNAL(messagesCounted(int))); connect(d_ptr, SIGNAL(progressChanged(uint, uint)), this, SIGNAL(progressChanged(uint, uint))); } QMessageService::~QMessageService() { } bool QMessageService::queryMessages(const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; if (d_ptr->queryMessages(filter, sortOrder, limit, offset)) { d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); } else { d_ptr->setFinished(false); } return d_ptr->_active; } bool QMessageService::queryMessages(const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; if (d_ptr->queryMessages(filter, body, matchFlags, sortOrder, limit, offset)) { d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); } else { d_ptr->setFinished(false); } return d_ptr->_active; } bool QMessageService::countMessages(const QMessageFilter &filter) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; if (d_ptr->countMessages(filter)) { d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); } else { d_ptr->setFinished(false); } return d_ptr->_active; } bool QMessageService::send(QMessage &message) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); QMessageAccountId accountId = message.parentAccountId(); QMessage::Type msgType = QMessage::NoType; // Check message type if (message.type() == QMessage::AnyType || message.type() == QMessage::NoType) { QMessage::TypeFlags types = QMessage::NoType; if (accountId.isValid()) { // ParentAccountId was defined => Message type can be read // from parent account QMessageAccount account = QMessageAccount(accountId); QMessage::TypeFlags types = account.messageTypes(); if (types & QMessage::Sms) { msgType = QMessage::Sms; } else if (types & QMessage::Mms) { msgType = QMessage::Mms; } else if (types & QMessage::Email) { msgType = QMessage::Email; } } if (msgType == QMessage::NoType) { d_ptr->_error = QMessageManager::ConstraintFailure; retVal = false; } } if (retVal) { // Check account if (!accountId.isValid()) { accountId = QMessageAccount::defaultAccount(message.type()); if (!accountId.isValid()) { d_ptr->_error = QMessageManager::InvalidId; retVal = false; } } } QMessageAccount account(accountId); if (retVal) { // Check account/message type compatibility if (!(account.messageTypes() & message.type()) && (msgType == QMessage::NoType)) { d_ptr->_error = QMessageManager::ConstraintFailure; retVal = false; } } if (retVal) { // Check recipients QMessageAddressList recipients = message.to() + message.bcc() + message.cc(); if (recipients.isEmpty()) { d_ptr->_error = QMessageManager::ConstraintFailure; return false; } } if (retVal) { QMessage outgoing(message); // Set default account if unset if (!outgoing.parentAccountId().isValid()) { outgoing.setParentAccountId(accountId); } if (outgoing.type() == QMessage::AnyType || outgoing.type() == QMessage::NoType) { outgoing.setType(msgType); } if (account.messageTypes() & QMessage::Sms) { retVal = d_ptr->sendSMS(outgoing); } else if (account.messageTypes() & QMessage::Mms) { retVal = d_ptr->sendMMS(outgoing); } else if (account.messageTypes() & QMessage::Email) { retVal = d_ptr->sendEmail(outgoing); } } d_ptr->setFinished(retVal); return retVal; } bool QMessageService::compose(const QMessage &message) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->compose(message); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::retrieveHeader(const QMessageId& id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->retrieveHeader(id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::retrieveBody(const QMessageId& id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->retrieveBody(id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::retrieve(const QMessageId &messageId, const QMessageContentContainerId& id) { if (d_ptr->_active) { return false; } if (!messageId.isValid() || !id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->retrieve(messageId, id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::show(const QMessageId& id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->show(id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::exportUpdates(const QMessageAccountId &id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->exportUpdates(id); d_ptr->setFinished(retVal); return retVal; } QMessageService::State QMessageService::state() const { return d_ptr->_state; } void QMessageService::cancel() { } QMessageManager::Error QMessageService::error() const { return d_ptr->_error; } #include "moc_qmessageservice_symbian_p.cpp" QTM_END_NAMESPACE <commit_msg>Symbian: FSEngine calls defined with FREESTYLEMAILUSED in qmessageservice_symbian.cpp<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <smsclnt.h> #include <smuthdr.h> // CSmsHeader #include <rsendas.h> #include <rsendasmessage.h> #include <f32file.h> #include <mmsconst.h> #include <utf.h> // CnvUtfConverter #include "qmessageservice.h" #include "qmessageservice_symbian_p.h" #include "qmtmengine_symbian_p.h" #include "qmessage_symbian_p.h" #include "symbianhelpers_p.h" #ifdef FREESTYLEMAILUSED #include "qfsengine_symbian_p.h" #endif QTM_BEGIN_NAMESPACE QMessageServicePrivate::QMessageServicePrivate(QMessageService* parent) : q_ptr(parent), _state(QMessageService::InactiveState), _active(false) { } QMessageServicePrivate::~QMessageServicePrivate() { } bool QMessageServicePrivate::sendSMS(QMessage &message) { return CMTMEngine::instance()->sendSMS(message); } bool QMessageServicePrivate::sendMMS(QMessage &message) { return CMTMEngine::instance()->sendMMS(message); } bool QMessageServicePrivate::sendEmail(QMessage &message) { if (SymbianHelpers::isFreestyleAccount(message.parentAccountId())) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->sendEmail(message); #else return false; #endif } else return CMTMEngine::instance()->sendEmail(message); } bool QMessageServicePrivate::show(const QMessageId& id) { QMessageId fsId = id; if (SymbianHelpers::isFreestyleMessage(fsId)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->showMessage(id); #else return false; #endif } else return CMTMEngine::instance()->showMessage(id); } bool QMessageServicePrivate::compose(const QMessage &message) { return CMTMEngine::instance()->composeMessage(message); } bool QMessageServicePrivate::queryMessages(const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, sortOrder, limit, offset); #endif return CMTMEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, sortOrder, limit, offset); } bool QMessageServicePrivate::queryMessages(const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, body, matchFlags, sortOrder, limit, offset); #endif return CMTMEngine::instance()->queryMessages((QMessageServicePrivate&)*this, filter, body, matchFlags, sortOrder, limit, offset); } bool QMessageServicePrivate::countMessages(const QMessageFilter &filter) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->countMessages((QMessageServicePrivate&)*this, filter); #endif return CMTMEngine::instance()->countMessages((QMessageServicePrivate&)*this, filter); } bool QMessageServicePrivate::retrieve(const QMessageId &messageId, const QMessageContentContainerId &id) { if (SymbianHelpers::isFreestyleMessage(messageId)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->retrieve(messageId, id); #else return false; #endif } else return CMTMEngine::instance()->retrieve(messageId, id); } bool QMessageServicePrivate::retrieveBody(const QMessageId& id) { if (SymbianHelpers::isFreestyleMessage(id)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->retrieveBody(id); #else return false; #endif } else return CMTMEngine::instance()->retrieveBody(id); } bool QMessageServicePrivate::retrieveHeader(const QMessageId& id) { if (SymbianHelpers::isFreestyleMessage(id)) { #ifdef FREESTYLEMAILUSED return CFSEngine::instance()->retrieveHeader(id); #else return false; #endif } else return CMTMEngine::instance()->retrieveHeader(id); } bool QMessageServicePrivate::exportUpdates(const QMessageAccountId &id) { // if (SymbianHelpers::isFreestyleMessage(id)) // return CFSEngine::instance()->exportUpdates(id); // else return CMTMEngine::instance()->exportUpdates(id); } void QMessageServicePrivate::setFinished(bool successful) { if (!successful && (_error == QMessageManager::NoError)) { // We must report an error of some sort _error = QMessageManager::RequestIncomplete; } _state = QMessageService::FinishedState; emit q_ptr->stateChanged(_state); _active = false; } QMessageService::QMessageService(QObject *parent) : QObject(parent), d_ptr(new QMessageServicePrivate(this)) { connect(d_ptr, SIGNAL(stateChanged(QMessageService::State)), this, SIGNAL(stateChanged(QMessageService::State))); connect(d_ptr, SIGNAL(messagesFound(const QMessageIdList&)), this, SIGNAL(messagesFound(const QMessageIdList&))); connect(d_ptr, SIGNAL(messagesCounted(int)), this, SIGNAL(messagesCounted(int))); connect(d_ptr, SIGNAL(progressChanged(uint, uint)), this, SIGNAL(progressChanged(uint, uint))); } QMessageService::~QMessageService() { } bool QMessageService::queryMessages(const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; if (d_ptr->queryMessages(filter, sortOrder, limit, offset)) { d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); } else { d_ptr->setFinished(false); } return d_ptr->_active; } bool QMessageService::queryMessages(const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; if (d_ptr->queryMessages(filter, body, matchFlags, sortOrder, limit, offset)) { d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); } else { d_ptr->setFinished(false); } return d_ptr->_active; } bool QMessageService::countMessages(const QMessageFilter &filter) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; if (d_ptr->countMessages(filter)) { d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); } else { d_ptr->setFinished(false); } return d_ptr->_active; } bool QMessageService::send(QMessage &message) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); QMessageAccountId accountId = message.parentAccountId(); QMessage::Type msgType = QMessage::NoType; // Check message type if (message.type() == QMessage::AnyType || message.type() == QMessage::NoType) { QMessage::TypeFlags types = QMessage::NoType; if (accountId.isValid()) { // ParentAccountId was defined => Message type can be read // from parent account QMessageAccount account = QMessageAccount(accountId); QMessage::TypeFlags types = account.messageTypes(); if (types & QMessage::Sms) { msgType = QMessage::Sms; } else if (types & QMessage::Mms) { msgType = QMessage::Mms; } else if (types & QMessage::Email) { msgType = QMessage::Email; } } if (msgType == QMessage::NoType) { d_ptr->_error = QMessageManager::ConstraintFailure; retVal = false; } } if (retVal) { // Check account if (!accountId.isValid()) { accountId = QMessageAccount::defaultAccount(message.type()); if (!accountId.isValid()) { d_ptr->_error = QMessageManager::InvalidId; retVal = false; } } } QMessageAccount account(accountId); if (retVal) { // Check account/message type compatibility if (!(account.messageTypes() & message.type()) && (msgType == QMessage::NoType)) { d_ptr->_error = QMessageManager::ConstraintFailure; retVal = false; } } if (retVal) { // Check recipients QMessageAddressList recipients = message.to() + message.bcc() + message.cc(); if (recipients.isEmpty()) { d_ptr->_error = QMessageManager::ConstraintFailure; return false; } } if (retVal) { QMessage outgoing(message); // Set default account if unset if (!outgoing.parentAccountId().isValid()) { outgoing.setParentAccountId(accountId); } if (outgoing.type() == QMessage::AnyType || outgoing.type() == QMessage::NoType) { outgoing.setType(msgType); } if (account.messageTypes() & QMessage::Sms) { retVal = d_ptr->sendSMS(outgoing); } else if (account.messageTypes() & QMessage::Mms) { retVal = d_ptr->sendMMS(outgoing); } else if (account.messageTypes() & QMessage::Email) { retVal = d_ptr->sendEmail(outgoing); } } d_ptr->setFinished(retVal); return retVal; } bool QMessageService::compose(const QMessage &message) { if (d_ptr->_active) { return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->compose(message); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::retrieveHeader(const QMessageId& id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->retrieveHeader(id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::retrieveBody(const QMessageId& id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->retrieveBody(id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::retrieve(const QMessageId &messageId, const QMessageContentContainerId& id) { if (d_ptr->_active) { return false; } if (!messageId.isValid() || !id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->retrieve(messageId, id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::show(const QMessageId& id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->show(id); d_ptr->setFinished(retVal); return retVal; } bool QMessageService::exportUpdates(const QMessageAccountId &id) { if (d_ptr->_active) { return false; } if (!id.isValid()) { d_ptr->_error = QMessageManager::InvalidId; return false; } d_ptr->_active = true; d_ptr->_error = QMessageManager::NoError; bool retVal = true; d_ptr->_state = QMessageService::ActiveState; emit stateChanged(d_ptr->_state); retVal = d_ptr->exportUpdates(id); d_ptr->setFinished(retVal); return retVal; } QMessageService::State QMessageService::state() const { return d_ptr->_state; } void QMessageService::cancel() { } QMessageManager::Error QMessageService::error() const { return d_ptr->_error; } #include "moc_qmessageservice_symbian_p.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>// TreeHierarchyDlg.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "TreeHierarchyDlg.h" #include "TestRunnerModel.h" #include "ResourceLoaders.h" #include <algorithm> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // TreeHierarchyDlg dialog TreeHierarchyDlg::TreeHierarchyDlg(CWnd* pParent ) : cdxCDynamicDialog(_T("CPP_UNIT_TEST_RUNNER_IDD_DIALOG_TEST_HIERARCHY"), pParent) , m_selectedTest( NULL ) { ModifyFlags( flSWPCopyBits, 0 ); // anti-flickering option for resizing //{{AFX_DATA_INIT(TreeHierarchyDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void TreeHierarchyDlg::DoDataExchange(CDataExchange* pDX) { cdxCDynamicDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(TreeHierarchyDlg) DDX_Control(pDX, IDC_TREE_TEST, m_treeTests); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(TreeHierarchyDlg, cdxCDynamicDialog) //{{AFX_MSG_MAP(TreeHierarchyDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() void TreeHierarchyDlg::setRootTest( CPPUNIT_NS::Test *test ) { m_rootTest = test; } BOOL TreeHierarchyDlg::OnInitDialog() { cdxCDynamicDialog::OnInitDialog(); fillTree(); initializeLayout(); RestoreWindowPosition( TestRunnerModel::settingKey, TestRunnerModel::settingBrowseDialogKey ); return TRUE; } void TreeHierarchyDlg::initializeLayout() { // see DynamicWindow/doc for documentation AddSzControl( IDC_TREE_TEST, mdResize, mdResize ); AddSzControl( IDOK, mdRepos, mdNone ); AddSzControl( IDCANCEL, mdRepos, mdNone ); } void TreeHierarchyDlg::fillTree() { VERIFY( m_imageList.Create( _T("CPP_UNIT_TEST_RUNNER_IDB_TEST_TYPE"), 16, 1, RGB( 255,0,255 ) ) ); m_treeTests.SetImageList( &m_imageList, TVSIL_NORMAL ); HTREEITEM hSuite = addTest( m_rootTest, TVI_ROOT ); m_treeTests.Expand( hSuite, TVE_EXPAND ); } HTREEITEM TreeHierarchyDlg::addTest( CPPUNIT_NS::Test *test, HTREEITEM hParent ) { int testType = isSuite( test ) ? imgSuite : imgUnitTest; HTREEITEM hItem = m_treeTests.InsertItem( CString(test->getName().c_str()), testType, testType, hParent ); if ( hItem != NULL ) { VERIFY( m_treeTests.SetItemData( hItem, (DWORD)test ) ); if ( isSuite( test ) ) addTestSuiteChildrenTo( test, hItem ); } return hItem; } void TreeHierarchyDlg::addTestSuiteChildrenTo( CPPUNIT_NS::Test *suite, HTREEITEM hItemSuite ) { Tests tests; int childIndex = 0; for ( ; childIndex < suite->getChildTestCount(); ++childIndex ) tests.push_back( suite->getChildTestAt( childIndex ) ); sortByName( tests ); for ( childIndex = 0; childIndex < suite->getChildTestCount(); ++childIndex ) addTest( suite->getChildTestAt( childIndex ), hItemSuite ); } bool TreeHierarchyDlg::isSuite( CPPUNIT_NS::Test *test ) { return ( test->getChildTestCount() > 0 || // suite with test test->countTestCases() == 0 ); // empty suite } struct PredSortTest { bool operator()( CPPUNIT_NS::Test *test1, CPPUNIT_NS::Test *test2 ) const { bool isTest1Suite = TreeHierarchyDlg::isSuite( test1 ); bool isTest2Suite = TreeHierarchyDlg::isSuite( test2 ); if ( isTest1Suite && !isTest2Suite ) return true; if ( isTest1Suite && isTest2Suite ) return test1->getName() < test2->getName(); return false; } }; void TreeHierarchyDlg::sortByName( Tests &tests ) const { std::stable_sort( tests.begin(), tests.end(), PredSortTest() ); } void TreeHierarchyDlg::OnOK() { CPPUNIT_NS::Test *test = findSelectedTest(); if ( test == NULL ) { AfxMessageBox( loadCString(IDS_ERROR_SELECT_TEST), MB_OK ); return; } m_selectedTest = test; storeDialogBounds(); cdxCDynamicDialog::OnOK(); } void TreeHierarchyDlg::OnCancel() { storeDialogBounds(); cdxCDynamicDialog::OnCancel(); } CPPUNIT_NS::Test * TreeHierarchyDlg::findSelectedTest() { HTREEITEM hItem = m_treeTests.GetSelectedItem(); if ( hItem != NULL ) { DWORD data; VERIFY( data = m_treeTests.GetItemData( hItem ) ); return reinterpret_cast<CPPUNIT_NS::Test *>( data ); } return NULL; } CPPUNIT_NS::Test * TreeHierarchyDlg::getSelectedTest() const { return m_selectedTest; } void TreeHierarchyDlg::storeDialogBounds() { StoreWindowPosition( TestRunnerModel::settingKey, TestRunnerModel::settingBrowseDialogKey ); } <commit_msg>fix crash with WIN64 in testrunner<commit_after>// TreeHierarchyDlg.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "TreeHierarchyDlg.h" #include "TestRunnerModel.h" #include "ResourceLoaders.h" #include <algorithm> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // TreeHierarchyDlg dialog TreeHierarchyDlg::TreeHierarchyDlg(CWnd* pParent ) : cdxCDynamicDialog(_T("CPP_UNIT_TEST_RUNNER_IDD_DIALOG_TEST_HIERARCHY"), pParent) , m_selectedTest( NULL ) { ModifyFlags( flSWPCopyBits, 0 ); // anti-flickering option for resizing //{{AFX_DATA_INIT(TreeHierarchyDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void TreeHierarchyDlg::DoDataExchange(CDataExchange* pDX) { cdxCDynamicDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(TreeHierarchyDlg) DDX_Control(pDX, IDC_TREE_TEST, m_treeTests); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(TreeHierarchyDlg, cdxCDynamicDialog) //{{AFX_MSG_MAP(TreeHierarchyDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() void TreeHierarchyDlg::setRootTest( CPPUNIT_NS::Test *test ) { m_rootTest = test; } BOOL TreeHierarchyDlg::OnInitDialog() { cdxCDynamicDialog::OnInitDialog(); fillTree(); initializeLayout(); RestoreWindowPosition( TestRunnerModel::settingKey, TestRunnerModel::settingBrowseDialogKey ); return TRUE; } void TreeHierarchyDlg::initializeLayout() { // see DynamicWindow/doc for documentation AddSzControl( IDC_TREE_TEST, mdResize, mdResize ); AddSzControl( IDOK, mdRepos, mdNone ); AddSzControl( IDCANCEL, mdRepos, mdNone ); } void TreeHierarchyDlg::fillTree() { VERIFY( m_imageList.Create( _T("CPP_UNIT_TEST_RUNNER_IDB_TEST_TYPE"), 16, 1, RGB( 255,0,255 ) ) ); m_treeTests.SetImageList( &m_imageList, TVSIL_NORMAL ); HTREEITEM hSuite = addTest( m_rootTest, TVI_ROOT ); m_treeTests.Expand( hSuite, TVE_EXPAND ); } HTREEITEM TreeHierarchyDlg::addTest( CPPUNIT_NS::Test *test, HTREEITEM hParent ) { int testType = isSuite( test ) ? imgSuite : imgUnitTest; HTREEITEM hItem = m_treeTests.InsertItem( CString(test->getName().c_str()), testType, testType, hParent ); if ( hItem != NULL ) { VERIFY( m_treeTests.SetItemData( hItem, (DWORD_PTR)test ) ); if ( isSuite( test ) ) addTestSuiteChildrenTo( test, hItem ); } return hItem; } void TreeHierarchyDlg::addTestSuiteChildrenTo( CPPUNIT_NS::Test *suite, HTREEITEM hItemSuite ) { Tests tests; int childIndex = 0; for ( ; childIndex < suite->getChildTestCount(); ++childIndex ) tests.push_back( suite->getChildTestAt( childIndex ) ); sortByName( tests ); for ( childIndex = 0; childIndex < suite->getChildTestCount(); ++childIndex ) addTest( suite->getChildTestAt( childIndex ), hItemSuite ); } bool TreeHierarchyDlg::isSuite( CPPUNIT_NS::Test *test ) { return ( test->getChildTestCount() > 0 || // suite with test test->countTestCases() == 0 ); // empty suite } struct PredSortTest { bool operator()( CPPUNIT_NS::Test *test1, CPPUNIT_NS::Test *test2 ) const { bool isTest1Suite = TreeHierarchyDlg::isSuite( test1 ); bool isTest2Suite = TreeHierarchyDlg::isSuite( test2 ); if ( isTest1Suite && !isTest2Suite ) return true; if ( isTest1Suite && isTest2Suite ) return test1->getName() < test2->getName(); return false; } }; void TreeHierarchyDlg::sortByName( Tests &tests ) const { std::stable_sort( tests.begin(), tests.end(), PredSortTest() ); } void TreeHierarchyDlg::OnOK() { CPPUNIT_NS::Test *test = findSelectedTest(); if ( test == NULL ) { AfxMessageBox( loadCString(IDS_ERROR_SELECT_TEST), MB_OK ); return; } m_selectedTest = test; storeDialogBounds(); cdxCDynamicDialog::OnOK(); } void TreeHierarchyDlg::OnCancel() { storeDialogBounds(); cdxCDynamicDialog::OnCancel(); } CPPUNIT_NS::Test * TreeHierarchyDlg::findSelectedTest() { HTREEITEM hItem = m_treeTests.GetSelectedItem(); if ( hItem != NULL ) { DWORD_PTR data; VERIFY( data = m_treeTests.GetItemData( hItem ) ); return reinterpret_cast<CPPUNIT_NS::Test *>( data ); } return NULL; } CPPUNIT_NS::Test * TreeHierarchyDlg::getSelectedTest() const { return m_selectedTest; } void TreeHierarchyDlg::storeDialogBounds() { StoreWindowPosition( TestRunnerModel::settingKey, TestRunnerModel::settingBrowseDialogKey ); } <|endoftext|>
<commit_before>/* * Copyright 2017 The Android Open Source Project * * 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 <cassert> #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include "oboe/AudioStreamBuilder.h" #include "AudioInputStreamOpenSLES.h" #include "AudioStreamOpenSLES.h" #include "OpenSLESUtilities.h" using namespace oboe; AudioInputStreamOpenSLES::AudioInputStreamOpenSLES(const AudioStreamBuilder &builder) : AudioStreamOpenSLES(builder) { } AudioInputStreamOpenSLES::~AudioInputStreamOpenSLES() { } #define AUDIO_CHANNEL_COUNT_MAX 30u #define SL_ANDROID_UNKNOWN_CHANNELMASK 0 int AudioInputStreamOpenSLES::chanCountToChanMask(int channelCount) { // from internal sles_channel_in_mask_from_count(chanCount); switch (channelCount) { case 1: return SL_SPEAKER_FRONT_LEFT; case 2: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; default: { if (channelCount > AUDIO_CHANNEL_COUNT_MAX) { return SL_ANDROID_UNKNOWN_CHANNELMASK; } else { SLuint32 bitfield = (1 << channelCount) - 1; return SL_ANDROID_MAKE_INDEXED_CHANNEL_MASK(bitfield); } } } } Result AudioInputStreamOpenSLES::open() { Result oboeResult = AudioStreamOpenSLES::open(); if (Result::OK != oboeResult) return oboeResult; SLuint32 bitsPerSample = getBytesPerSample() * kBitsPerByte; // configure audio sink SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, // locatorType static_cast<SLuint32>(kBufferQueueLength)}; // numBuffers // Define the audio data format. SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, // formatType (SLuint32) mChannelCount, // numChannels (SLuint32) (mSampleRate * kMillisPerSecond), // milliSamplesPerSec bitsPerSample, // bitsPerSample bitsPerSample, // containerSize; (SLuint32) chanCountToChanMask(mChannelCount), // channelMask getDefaultByteOrder(), }; SLDataSink audioSink = {&loc_bufq, &format_pcm}; /** * API 21 (Lollipop) introduced support for floating-point data representation and an extended * data format type: SLAndroidDataFormat_PCM_EX. If running on API 21+ use this newer format * type, creating it from our original format. */ SLAndroidDataFormat_PCM_EX format_pcm_ex; if (__ANDROID_API__ >= __ANDROID_API_L__) { SLuint32 representation = OpenSLES_ConvertFormatToRepresentation(getFormat()); // Fill in the format structure. format_pcm_ex = OpenSLES_createExtendedFormat(format_pcm, representation); // Use in place of the previous format. audioSink.pFormat = &format_pcm_ex; } // configure audio source SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, NULL }; SLDataSource audioSrc = {&loc_dev, NULL }; SLresult result = EngineOpenSLES::getInstance().createAudioRecorder(&mObjectInterface, &audioSrc, &audioSink); if (SL_RESULT_SUCCESS != result) { LOGE("createAudioRecorder() result:%s", getSLErrStr(result)); goto error; } // Configure the voice recognition preset, which has no // signal processing, for lower latency. SLAndroidConfigurationItf inputConfig; result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_ANDROIDCONFIGURATION, &inputConfig); if (SL_RESULT_SUCCESS == result) { SLuint32 presetValue = SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION; (*inputConfig)->SetConfiguration(inputConfig, SL_ANDROID_KEY_RECORDING_PRESET, &presetValue, sizeof(SLuint32)); } result = (*mObjectInterface)->Realize(mObjectInterface, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { LOGE("Realize recorder object result:%s", getSLErrStr(result)); goto error; } result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_RECORD, &mRecordInterface); if (SL_RESULT_SUCCESS != result) { LOGE("GetInterface RECORD result:%s", getSLErrStr(result)); goto error; } result = AudioStreamOpenSLES::registerBufferQueueCallback(); if (SL_RESULT_SUCCESS != result) { goto error; } allocateFifo(); return Result::OK; error: return Result::ErrorInternal; // TODO convert error from SLES to OBOE } Result AudioInputStreamOpenSLES::close() { requestStop(); mRecordInterface = NULL; return AudioStreamOpenSLES::close(); } Result AudioInputStreamOpenSLES::setRecordState(SLuint32 newState) { Result result = Result::OK; LOGD("AudioInputStreamOpenSLES::setRecordState(%d)", newState); if (mRecordInterface == nullptr) { LOGE("AudioInputStreamOpenSLES::SetRecordState() mRecordInterface is null"); return Result::ErrorInvalidState; } SLresult slResult = (*mRecordInterface)->SetRecordState(mRecordInterface, newState); if(SL_RESULT_SUCCESS != slResult) { LOGE("AudioInputStreamOpenSLES::SetRecordState() returned %s", getSLErrStr(slResult)); result = Result::ErrorInvalidState; // TODO review } else { setState(StreamState::Pausing); } return result; } Result AudioInputStreamOpenSLES::requestStart() { LOGD("AudioInputStreamOpenSLES::requestStart()"); Result result = setRecordState(SL_RECORDSTATE_RECORDING); if(result == Result::OK) { // Enqueue the first buffer so that we have data ready in the callback. enqueueCallbackBuffer(mSimpleBufferQueueInterface); setState(StreamState::Starting); } return result; } Result AudioInputStreamOpenSLES::requestPause() { LOGD("AudioInputStreamOpenSLES::requestStop()"); Result result = setRecordState(SL_RECORDSTATE_PAUSED); if(result != Result::OK) { result = Result::ErrorInvalidState; // TODO review } else { setState(StreamState::Pausing); mPositionMillis.reset32(); // OpenSL ES resets its millisecond position when paused. } return result; } Result AudioInputStreamOpenSLES::requestFlush() { return Result::ErrorUnimplemented; // TODO } Result AudioInputStreamOpenSLES::requestStop() { LOGD("AudioInputStreamOpenSLES::requestStop()"); Result result = setRecordState(SL_RECORDSTATE_STOPPED); if(result != Result::OK) { result = Result::ErrorInvalidState; // TODO review } else { setState(StreamState::Stopping); mPositionMillis.reset32(); // OpenSL ES resets its millisecond position when stopped. } return result; } int64_t AudioInputStreamOpenSLES::getFramesWritten() const { return getFramesProcessedByServer(); } Result AudioInputStreamOpenSLES::waitForStateChange(StreamState currentState, StreamState *nextState, int64_t timeoutNanoseconds) { LOGD("AudioInputStreamOpenSLES::waitForStateChange()"); if (mRecordInterface == NULL) { return Result::ErrorInvalidState; } return Result::ErrorUnimplemented; // TODO } Result AudioInputStreamOpenSLES::updateServiceFrameCounter() { if (mRecordInterface == NULL) { return Result::ErrorNull; } SLmillisecond msec = 0; SLresult slResult = (*mRecordInterface)->GetPosition(mRecordInterface, &msec); Result result = Result::OK; if(SL_RESULT_SUCCESS != slResult) { LOGD("%s(): GetPosition() returned %s", __func__, getSLErrStr(slResult)); // set result based on SLresult result = Result::ErrorInternal; } else { mPositionMillis.update32(msec); } return result; } <commit_msg>opensl input preset to UNPROCESSED, or VOICE_RECOGNITION as fallback; AS auto formatted some code<commit_after>/* * Copyright 2017 The Android Open Source Project * * 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 <cassert> #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include "oboe/AudioStreamBuilder.h" #include "AudioInputStreamOpenSLES.h" #include "AudioStreamOpenSLES.h" #include "OpenSLESUtilities.h" using namespace oboe; AudioInputStreamOpenSLES::AudioInputStreamOpenSLES(const AudioStreamBuilder &builder) : AudioStreamOpenSLES(builder) { } AudioInputStreamOpenSLES::~AudioInputStreamOpenSLES() { } #define AUDIO_CHANNEL_COUNT_MAX 30u #define SL_ANDROID_UNKNOWN_CHANNELMASK 0 int AudioInputStreamOpenSLES::chanCountToChanMask(int channelCount) { // from internal sles_channel_in_mask_from_count(chanCount); switch (channelCount) { case 1: return SL_SPEAKER_FRONT_LEFT; case 2: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; default: { if (channelCount > AUDIO_CHANNEL_COUNT_MAX) { return SL_ANDROID_UNKNOWN_CHANNELMASK; } else { SLuint32 bitfield = (1 << channelCount) - 1; return SL_ANDROID_MAKE_INDEXED_CHANNEL_MASK(bitfield); } } } } Result AudioInputStreamOpenSLES::open() { Result oboeResult = AudioStreamOpenSLES::open(); if (Result::OK != oboeResult) return oboeResult; SLuint32 bitsPerSample = getBytesPerSample() * kBitsPerByte; // configure audio sink SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, // locatorType static_cast<SLuint32>(kBufferQueueLength)}; // numBuffers // Define the audio data format. SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, // formatType (SLuint32) mChannelCount, // numChannels (SLuint32) (mSampleRate * kMillisPerSecond), // milliSamplesPerSec bitsPerSample, // bitsPerSample bitsPerSample, // containerSize; (SLuint32) chanCountToChanMask(mChannelCount), // channelMask getDefaultByteOrder(), }; SLDataSink audioSink = {&loc_bufq, &format_pcm}; /** * API 21 (Lollipop) introduced support for floating-point data representation and an extended * data format type: SLAndroidDataFormat_PCM_EX. If running on API 21+ use this newer format * type, creating it from our original format. */ SLAndroidDataFormat_PCM_EX format_pcm_ex; if (__ANDROID_API__ >= __ANDROID_API_L__) { SLuint32 representation = OpenSLES_ConvertFormatToRepresentation(getFormat()); // Fill in the format structure. format_pcm_ex = OpenSLES_createExtendedFormat(format_pcm, representation); // Use in place of the previous format. audioSink.pFormat = &format_pcm_ex; } // configure audio source SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; SLDataSource audioSrc = {&loc_dev, NULL}; SLresult result = EngineOpenSLES::getInstance().createAudioRecorder(&mObjectInterface, &audioSrc, &audioSink); if (SL_RESULT_SUCCESS != result) { LOGE("createAudioRecorder() result:%s", getSLErrStr(result)); goto error; } // Configure the unprocessed preset // or voice recognition as fallback, which has no // signal processing, for lower latency. SLAndroidConfigurationItf inputConfig; result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_ANDROIDCONFIGURATION, &inputConfig); if (SL_RESULT_SUCCESS == result) { SLuint32 presetValue = SL_ANDROID_RECORDING_PRESET_UNPROCESSED; result = (*inputConfig)->SetConfiguration(inputConfig, SL_ANDROID_KEY_RECORDING_PRESET, &presetValue, sizeof(SLuint32)); if (SL_RESULT_SUCCESS != result) { presetValue = SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION; (*inputConfig)->SetConfiguration(inputConfig, SL_ANDROID_KEY_RECORDING_PRESET, &presetValue, sizeof(SLuint32)); } } result = (*mObjectInterface)->Realize(mObjectInterface, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { LOGE("Realize recorder object result:%s", getSLErrStr(result)); goto error; } result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_RECORD, &mRecordInterface); if (SL_RESULT_SUCCESS != result) { LOGE("GetInterface RECORD result:%s", getSLErrStr(result)); goto error; } result = AudioStreamOpenSLES::registerBufferQueueCallback(); if (SL_RESULT_SUCCESS != result) { goto error; } allocateFifo(); return Result::OK; error: return Result::ErrorInternal; // TODO convert error from SLES to OBOE } Result AudioInputStreamOpenSLES::close() { requestStop(); mRecordInterface = NULL; return AudioStreamOpenSLES::close(); } Result AudioInputStreamOpenSLES::setRecordState(SLuint32 newState) { Result result = Result::OK; LOGD("AudioInputStreamOpenSLES::setRecordState(%d)", newState); if (mRecordInterface == nullptr) { LOGE("AudioInputStreamOpenSLES::SetRecordState() mRecordInterface is null"); return Result::ErrorInvalidState; } SLresult slResult = (*mRecordInterface)->SetRecordState(mRecordInterface, newState); if (SL_RESULT_SUCCESS != slResult) { LOGE("AudioInputStreamOpenSLES::SetRecordState() returned %s", getSLErrStr(slResult)); result = Result::ErrorInvalidState; // TODO review } else { setState(StreamState::Pausing); } return result; } Result AudioInputStreamOpenSLES::requestStart() { LOGD("AudioInputStreamOpenSLES::requestStart()"); Result result = setRecordState(SL_RECORDSTATE_RECORDING); if (result == Result::OK) { // Enqueue the first buffer so that we have data ready in the callback. enqueueCallbackBuffer(mSimpleBufferQueueInterface); setState(StreamState::Starting); } return result; } Result AudioInputStreamOpenSLES::requestPause() { LOGD("AudioInputStreamOpenSLES::requestStop()"); Result result = setRecordState(SL_RECORDSTATE_PAUSED); if (result != Result::OK) { result = Result::ErrorInvalidState; // TODO review } else { setState(StreamState::Pausing); mPositionMillis.reset32(); // OpenSL ES resets its millisecond position when paused. } return result; } Result AudioInputStreamOpenSLES::requestFlush() { return Result::ErrorUnimplemented; // TODO } Result AudioInputStreamOpenSLES::requestStop() { LOGD("AudioInputStreamOpenSLES::requestStop()"); Result result = setRecordState(SL_RECORDSTATE_STOPPED); if (result != Result::OK) { result = Result::ErrorInvalidState; // TODO review } else { setState(StreamState::Stopping); mPositionMillis.reset32(); // OpenSL ES resets its millisecond position when stopped. } return result; } int64_t AudioInputStreamOpenSLES::getFramesWritten() const { return getFramesProcessedByServer(); } Result AudioInputStreamOpenSLES::waitForStateChange(StreamState currentState, StreamState *nextState, int64_t timeoutNanoseconds) { LOGD("AudioInputStreamOpenSLES::waitForStateChange()"); if (mRecordInterface == NULL) { return Result::ErrorInvalidState; } return Result::ErrorUnimplemented; // TODO } Result AudioInputStreamOpenSLES::updateServiceFrameCounter() { if (mRecordInterface == NULL) { return Result::ErrorNull; } SLmillisecond msec = 0; SLresult slResult = (*mRecordInterface)->GetPosition(mRecordInterface, &msec); Result result = Result::OK; if(SL_RESULT_SUCCESS != slResult) { LOGD("%s(): GetPosition() returned %s", __func__, getSLErrStr(slResult)); // set result based on SLresult result = Result::ErrorInternal; } else { mPositionMillis.update32(msec); } return result; } <|endoftext|>
<commit_before> // Standard includes #include <iostream> #include <cstdlib> #include <unistd.h> #include <cmath> #include <string.h> #include <inttypes.h> #include <fstream> // Serial includes #include <stdio.h> /* Standard input/output definitions */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ # #ifdef __linux #include <sys/ioctl.h> #endif // Latency Benchmarking #include <sys/time.h> #include <time.h> #include "common.h" #include "read_thread.h" #include "serial_port.h" #include "commander.h" using std::string; using namespace std; /* whether or not we have received a heartbeat from the pixhawk */ bool heartbeatReceived = false; /* whether or not we are currently in hunt mode */ bool hunting = false; /* whether or not we are currently rotating */ bool rotating = false; void parse_heartbeat(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_heartbeat_t heartbeat; mavlink_msg_heartbeat_decode(message, &heartbeat); uavRead->type = heartbeat.type; uavRead->autopilot = heartbeat.autopilot; uavRead->base_mode = heartbeat.base_mode; uavRead->custom_mode = heartbeat.custom_mode; uavRead->status = heartbeat.system_status; // so we don't keep rewriting known values that stay constant // realizing not really doing anything with this.... heartbeatReceived = true; } void parse_sys_status(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_sys_status_t sysStatus; mavlink_msg_sys_status_decode(message, &sysStatus); uavRead->battery_voltage = (float) sysStatus.voltage_battery/1000.0f; uavRead->battery_current = (float) sysStatus.current_battery/100.0f; } // custom mavlink parsers /* void parse_apnt_gps_status(const mavlink_message_t *message, MAVInfo *uavRead) { // the new way of doing it mavlink_msg_apnt_gps_status_decode(message, &(uavRead->apnt_gps_status)); } void parse_apnt_site_status(const mavlink_message_t *message, MAVInfo *uavRead) { // the new way of doing it mavlink_msg_apnt_site_status_decode(message, &(uavRead->apnt_site_status)); } */ void parse_current_cmd_id(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_hunt_mission_current_t hunt_mission_current; mavlink_msg_hunt_mission_current_decode(message, &hunt_mission_current); uavRead->current_cmd_id = hunt_mission_current.current_cmd_id; } void parse_last_cmd_finished_id(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_hunt_mission_reached_t hunt_mission_reached; mavlink_msg_hunt_mission_reached_decode(message, &hunt_mission_reached); // only update this if this confirms the last command sent (anything else will be assumed to be // delayed or just wrong) if (uavRead->current_cmd_id == hunt_mission_reached.reached_cmd_id) { uavRead->last_cmd_finished_id = hunt_mission_reached.reached_cmd_id; } // TODO: add call to generate command // sendNextCommand(); } void handle_message(const mavlink_message_t *message, MAVInfo *uavRead) { switch (message->msgid) { //normal messages case MAVLINK_MSG_ID_HEARTBEAT: // #0 { parse_heartbeat(message, uavRead); break; } case MAVLINK_MSG_ID_SYS_STATUS: { parse_sys_status(message, uavRead); break; } case MAVLINK_MSG_ID_HIGHRES_IMU: { mavlink_msg_highres_imu_decode(message, &(uavRead->highres_imu)); break; } case MAVLINK_MSG_ID_ATTITUDE: { mavlink_msg_attitude_decode(message, &(uavRead->attitude)); // cout << "heading: " << uavRead->attitude.yaw*180/3.14 << "\n"; break; } case MAVLINK_MSG_ID_VFR_HUD: { mavlink_msg_vfr_hud_decode(message, &(uavRead->vfr_hud)); // cout << "heading: " << uavRead->vfr_hud.heading << "\n"; break; } case MAVLINK_MSG_ID_GLOBAL_POSITION_INT: { mavlink_msg_global_position_int_decode(message, &(uavRead->gps_position)); break; } case MAVLINK_MSG_ID_POSITION_TARGET_GLOBAL_INT: { mavlink_msg_position_target_global_int_decode(message, &(uavRead->position_target_gps)); break; } case MAVLINK_MSG_ID_ATTITUDE_TARGET: { mavlink_msg_attitude_target_decode(message, &(uavRead->attitude_target)); break; } // tracking specific messages case MAVLINK_MSG_ID_TRACKING_STATUS: { mavlink_msg_tracking_status_decode(message, &(uavRead->tracking_status)); // need to check to see if we have changed into waiting for the first time if (!hunting && uavRead->tracking_status.hunt_mode_state > TRACKING_HUNT_STATE_OFF) { hunting = true; // this is the first time we have triggered into hunting uavRead->last_cmd_finished_id = -1; // set the last cmd id to -1, so that when we run get next cmd it sends the correct one // command the vehicle to rotate sendRotateCommand(); // mark that we are now rotating rotating = true; } /* if the pixhawk is in wait mode, send a rotate command */ if (!rotating && uavRead->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) { sendRotateCommand(); // mark that we are now rotating rotating = true; } else { // finishing the rotation rotating = false; // TODO: this is where we will want to calculate the bearing.... // NOTE: wifly thread is currently doing bearing calculations } break; } case MAVLINK_MSG_ID_TRACKING_CMD: { mavlink_msg_tracking_cmd_decode(message, &(uavRead->last_tracking_cmd)); break; } case MAVLINK_MSG_ID_HUNT_MISSION_CURRENT: { parse_current_cmd_id(message, uavRead); break; } case MAVLINK_MSG_ID_HUNT_MISSION_REACHED: { parse_last_cmd_finished_id(message, uavRead); break; } // TODO add all the needed stuff for louis /* // COMMENTING OUT APNT MESSAGES FOR NOW case MAVLINK_MSG_ID_APNT_GPS_STATUS: { parse_apnt_gps_status(&message, uavRead); break; } case MAVLINK_MSG_ID_APNT_SITE_STATUS: { parse_apnt_site_status(&message, uavRead); break; } */ } // end of switch } uint8_t read_from_serial(mavlink_status_t *lastStatus, mavlink_message_t *message) { // variables needed for the message reading uint8_t cp; // not sure mavlink_status_t status; // current message status uint8_t msgReceived = false; // whether or not a message was correctly received // read in from the file if (read(fd, &cp, 1) > 0) { // Check if a message could be decoded, return the message in case yes msgReceived = mavlink_parse_char(MAVLINK_COMM_1, cp, message, &status); // check the packet drop count to see if there was a packet dropped during this message reading if (lastStatus->packet_rx_drop_count != status.packet_rx_drop_count) { // print out some error information containing dropped packet indo if (verbose || debug) printf("ERROR: DROPPED %d PACKETS\n", status.packet_rx_drop_count); // print out the characters of the packets themselves if (debug) { unsigned char v=cp; fprintf(stderr,"%02x ", v); } } // update the last message status *lastStatus = status; } else { // means unable to read from the serial device // print out error as needed if (verbose) fprintf(stderr, "ERROR: Could not read from fd %d\n", fd); } // return whether or not the message was received return msgReceived; } /** * function to read from the serial device * right now only looks for the apnt_gps_status message and prints out * the current status (which happens to also be sent from this script) */ void *read_thread(void *param) { // retrieve the MAVInfo struct that is sent to this function as a parameter struct MAVInfo *uavRead = (struct MAVInfo *)param; // variables to hold information about the connection health mavlink_status_t lastStatus; lastStatus.packet_rx_drop_count = 0; // initialize to 0 just for the first pass // run this infinite loop (as long as RUNNING_FLAG == 1) which reads messages as they come in while (RUNNING_FLAG) { // variables needed for the message reading mavlink_message_t message; // the message itself // read from serial, if message received, will be written to message variable uint8_t msgReceived = read_from_serial(&lastStatus, &message); // If a message could be decoded, handle it // TODO: only need to do this once if(msgReceived) { if (!heartbeatReceived) { uavRead->systemId = message.sysid; uavRead->compId = message.compid; } // handle what need to happen with the message handle_message(&message, uavRead); } } cout << "read ending\n"; return NULL; } <commit_msg>add some debugging printing<commit_after> // Standard includes #include <iostream> #include <cstdlib> #include <unistd.h> #include <cmath> #include <string.h> #include <inttypes.h> #include <fstream> // Serial includes #include <stdio.h> /* Standard input/output definitions */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ # #ifdef __linux #include <sys/ioctl.h> #endif // Latency Benchmarking #include <sys/time.h> #include <time.h> #include "common.h" #include "read_thread.h" #include "serial_port.h" #include "commander.h" using std::string; using namespace std; /* whether or not we have received a heartbeat from the pixhawk */ bool heartbeatReceived = false; /* whether or not we are currently in hunt mode */ bool hunting = false; /* whether or not we are currently rotating */ bool rotating = false; void parse_heartbeat(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_heartbeat_t heartbeat; mavlink_msg_heartbeat_decode(message, &heartbeat); uavRead->type = heartbeat.type; uavRead->autopilot = heartbeat.autopilot; uavRead->base_mode = heartbeat.base_mode; uavRead->custom_mode = heartbeat.custom_mode; uavRead->status = heartbeat.system_status; // so we don't keep rewriting known values that stay constant // realizing not really doing anything with this.... heartbeatReceived = true; } void parse_sys_status(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_sys_status_t sysStatus; mavlink_msg_sys_status_decode(message, &sysStatus); uavRead->battery_voltage = (float) sysStatus.voltage_battery/1000.0f; uavRead->battery_current = (float) sysStatus.current_battery/100.0f; } // custom mavlink parsers /* void parse_apnt_gps_status(const mavlink_message_t *message, MAVInfo *uavRead) { // the new way of doing it mavlink_msg_apnt_gps_status_decode(message, &(uavRead->apnt_gps_status)); } void parse_apnt_site_status(const mavlink_message_t *message, MAVInfo *uavRead) { // the new way of doing it mavlink_msg_apnt_site_status_decode(message, &(uavRead->apnt_site_status)); } */ void parse_current_cmd_id(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_hunt_mission_current_t hunt_mission_current; mavlink_msg_hunt_mission_current_decode(message, &hunt_mission_current); uavRead->current_cmd_id = hunt_mission_current.current_cmd_id; } void parse_last_cmd_finished_id(const mavlink_message_t *message, MAVInfo *uavRead) { mavlink_hunt_mission_reached_t hunt_mission_reached; mavlink_msg_hunt_mission_reached_decode(message, &hunt_mission_reached); // only update this if this confirms the last command sent (anything else will be assumed to be // delayed or just wrong) if (uavRead->current_cmd_id == hunt_mission_reached.reached_cmd_id) { uavRead->last_cmd_finished_id = hunt_mission_reached.reached_cmd_id; } // TODO: add call to generate command // sendNextCommand(); } void handle_message(const mavlink_message_t *message, MAVInfo *uavRead) { switch (message->msgid) { //normal messages case MAVLINK_MSG_ID_HEARTBEAT: // #0 { parse_heartbeat(message, uavRead); break; } case MAVLINK_MSG_ID_SYS_STATUS: { parse_sys_status(message, uavRead); break; } case MAVLINK_MSG_ID_HIGHRES_IMU: { mavlink_msg_highres_imu_decode(message, &(uavRead->highres_imu)); break; } case MAVLINK_MSG_ID_ATTITUDE: { mavlink_msg_attitude_decode(message, &(uavRead->attitude)); // cout << "heading: " << uavRead->attitude.yaw*180/3.14 << "\n"; break; } case MAVLINK_MSG_ID_VFR_HUD: { mavlink_msg_vfr_hud_decode(message, &(uavRead->vfr_hud)); // cout << "heading: " << uavRead->vfr_hud.heading << "\n"; break; } case MAVLINK_MSG_ID_GLOBAL_POSITION_INT: { mavlink_msg_global_position_int_decode(message, &(uavRead->gps_position)); break; } case MAVLINK_MSG_ID_POSITION_TARGET_GLOBAL_INT: { mavlink_msg_position_target_global_int_decode(message, &(uavRead->position_target_gps)); break; } case MAVLINK_MSG_ID_ATTITUDE_TARGET: { mavlink_msg_attitude_target_decode(message, &(uavRead->attitude_target)); break; } // tracking specific messages case MAVLINK_MSG_ID_TRACKING_STATUS: { mavlink_msg_tracking_status_decode(message, &(uavRead->tracking_status)); cout << "HUNT STATE changed to: " << uavRead->tracking_status.hunt_mode_state << "\n"; // need to check to see if we have changed into waiting for the first time if (!hunting && uavRead->tracking_status.hunt_mode_state > TRACKING_HUNT_STATE_OFF) { hunting = true; // this is the first time we have triggered into hunting uavRead->last_cmd_finished_id = -1; // set the last cmd id to -1, so that when we run get next cmd it sends the correct one // command the vehicle to rotate sendRotateCommand(); // mark that we are now rotating rotating = true; } /* if the pixhawk is in wait mode, send a rotate command */ if (!rotating && uavRead->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) { sendRotateCommand(); // mark that we are now rotating rotating = true; } else { // finishing the rotation rotating = false; // TODO: this is where we will want to calculate the bearing.... // NOTE: wifly thread is currently doing bearing calculations } break; } case MAVLINK_MSG_ID_TRACKING_CMD: { mavlink_msg_tracking_cmd_decode(message, &(uavRead->last_tracking_cmd)); break; } case MAVLINK_MSG_ID_HUNT_MISSION_CURRENT: { parse_current_cmd_id(message, uavRead); break; } case MAVLINK_MSG_ID_HUNT_MISSION_REACHED: { parse_last_cmd_finished_id(message, uavRead); break; } // TODO add all the needed stuff for louis /* // COMMENTING OUT APNT MESSAGES FOR NOW case MAVLINK_MSG_ID_APNT_GPS_STATUS: { parse_apnt_gps_status(&message, uavRead); break; } case MAVLINK_MSG_ID_APNT_SITE_STATUS: { parse_apnt_site_status(&message, uavRead); break; } */ } // end of switch } uint8_t read_from_serial(mavlink_status_t *lastStatus, mavlink_message_t *message) { // variables needed for the message reading uint8_t cp; // not sure mavlink_status_t status; // current message status uint8_t msgReceived = false; // whether or not a message was correctly received // read in from the file if (read(fd, &cp, 1) > 0) { // Check if a message could be decoded, return the message in case yes msgReceived = mavlink_parse_char(MAVLINK_COMM_1, cp, message, &status); // check the packet drop count to see if there was a packet dropped during this message reading if (lastStatus->packet_rx_drop_count != status.packet_rx_drop_count) { // print out some error information containing dropped packet indo if (verbose || debug) printf("ERROR: DROPPED %d PACKETS\n", status.packet_rx_drop_count); // print out the characters of the packets themselves if (debug) { unsigned char v=cp; fprintf(stderr,"%02x ", v); } } // update the last message status *lastStatus = status; } else { // means unable to read from the serial device // print out error as needed if (verbose) fprintf(stderr, "ERROR: Could not read from fd %d\n", fd); } // return whether or not the message was received return msgReceived; } /** * function to read from the serial device * right now only looks for the apnt_gps_status message and prints out * the current status (which happens to also be sent from this script) */ void *read_thread(void *param) { // retrieve the MAVInfo struct that is sent to this function as a parameter struct MAVInfo *uavRead = (struct MAVInfo *)param; // variables to hold information about the connection health mavlink_status_t lastStatus; lastStatus.packet_rx_drop_count = 0; // initialize to 0 just for the first pass // run this infinite loop (as long as RUNNING_FLAG == 1) which reads messages as they come in while (RUNNING_FLAG) { // variables needed for the message reading mavlink_message_t message; // the message itself // read from serial, if message received, will be written to message variable uint8_t msgReceived = read_from_serial(&lastStatus, &message); // If a message could be decoded, handle it // TODO: only need to do this once if(msgReceived) { if (!heartbeatReceived) { uavRead->systemId = message.sysid; uavRead->compId = message.compid; } // handle what need to happen with the message handle_message(&message, uavRead); } } cout << "read ending\n"; return NULL; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "iwizardfactory.h" #include "actionmanager/actionmanager.h" #include "documentmanager.h" #include "icore.h" #include "featureprovider.h" #include <extensionsystem/pluginspec.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QAction> /*! \class Core::IWizardFactory \mainclass \brief The class IWizardFactory is the base class for all wizard factories (for example shown in \gui {File | New}). The wizard interface is a very thin abstraction for the \gui{New...} wizards. Basically it defines what to show to the user in the wizard selection dialogs, and a hook that is called if the user selects the wizard. Wizards can then perform any operations they like, including showing dialogs and creating files. Often it is not necessary to create your own wizard from scratch, instead use one of the predefined wizards and adapt it to your needs. To make your wizard known to the system, add your IWizardFactory instance to the plugin manager's object pool in your plugin's initialize function: \code bool MyPlugin::initialize(const QStringList &arguments, QString *errorString) { // ... do setup addAutoReleasedObject(new MyWizardFactory); // ... do more setup } \endcode \sa Core::BaseFileWizard \sa Core::StandardFileWizard */ /*! \enum Core::IWizardFactory::WizardKind Used to specify what kind of objects the wizard creates. This information is used to show e.g. only wizards that create projects when selecting a \gui{New Project} menu item. \value FileWizard The wizard creates one or more files. \value ClassWizard The wizard creates a new class (e.g. source+header files). \value ProjectWizard The wizard creates a new project. */ /*! \fn IWizardFactory::IWizardFactory(QObject *parent) \internal */ /*! \fn IWizardFactory::~IWizardFactory() \internal */ /*! \fn Kind IWizardFactory::kind() const Returns what kind of objects are created by the wizard. \sa Kind */ /*! \fn QIcon IWizardFactory::icon() const Returns an icon to show in the wizard selection dialog. */ /*! \fn QString IWizardFactory::description() const Returns a translated description to show when this wizard is selected in the dialog. */ /*! \fn QString IWizardFactory::displayName() const Returns the translated name of the wizard, how it should appear in the dialog. */ /*! \fn QString IWizardFactory::id() const Returns an arbitrary id that is used for sorting within the category. */ /*! \fn QString IWizardFactory::category() const Returns a category ID to add the wizard to. */ /*! \fn QString IWizardFactory::displayCategory() const Returns the translated string of the category, how it should appear in the dialog. */ /*! \fn void IWizardFactory::runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &variables) This function is executed when the wizard has been selected by the user for execution. Any dialogs the wizard opens should use the given \a parent. The \a path argument is a suggestion for the location where files should be created. The wizard should fill this in its path selection elements as a default path. */ using namespace Core; namespace { static QList<IFeatureProvider *> s_providerList; QList<IWizardFactory *> s_allFactories; QList<IWizardFactory::FactoryCreator> s_factoryCreators; bool s_areFactoriesLoaded = false; } /* A utility to find all wizards supporting a view mode and matching a predicate */ template <class Predicate> QList<IWizardFactory*> findWizardFactories(Predicate predicate) { // Filter all wizards const QList<IWizardFactory*> allFactories = IWizardFactory::allWizardFactories(); QList<IWizardFactory*> rc; const QList<IWizardFactory*>::const_iterator cend = allFactories.constEnd(); for (QList<IWizardFactory*>::const_iterator it = allFactories.constBegin(); it != cend; ++it) if (predicate(*(*it))) rc.push_back(*it); return rc; } static Id actionId(const IWizardFactory *factory) { return factory->id().withPrefix("Wizard.Impl."); } QList<IWizardFactory*> IWizardFactory::allWizardFactories() { if (!s_areFactoriesLoaded) { QTC_ASSERT(s_allFactories.isEmpty(), return s_allFactories); s_areFactoriesLoaded = true; QHash<Id, IWizardFactory *> sanityCheck; foreach (const FactoryCreator &fc, s_factoryCreators) { QList<IWizardFactory *> tmp = fc(); foreach (IWizardFactory *newFactory, tmp) { QTC_ASSERT(newFactory, continue); IWizardFactory *existingFactory = sanityCheck.value(newFactory->id()); QTC_ASSERT(existingFactory != newFactory, continue); if (existingFactory) { qWarning("%s", qPrintable(tr("Factory with id=\"%1\" already registered. Deleting.") .arg(existingFactory->id().toString()))); delete newFactory; continue; } QTC_ASSERT(!newFactory->m_action, continue); newFactory->m_action = new QAction(newFactory->displayName(), newFactory); ActionManager::registerAction(newFactory->m_action, actionId(newFactory)); connect(newFactory->m_action, &QAction::triggered, newFactory, [newFactory]() { QString path = newFactory->runPath(QString()); newFactory->runWizard(path, ICore::dialogParent(), QString(), QVariantMap()); }); sanityCheck.insert(newFactory->id(), newFactory); s_allFactories << newFactory; } } } return s_allFactories; } // Utility to find all registered wizards of a certain kind class WizardKindPredicate { public: WizardKindPredicate(IWizardFactory::WizardKind kind) : m_kind(kind) {} bool operator()(const IWizardFactory &w) const { return w.kind() == m_kind; } private: const IWizardFactory::WizardKind m_kind; }; QList<IWizardFactory*> IWizardFactory::wizardFactoriesOfKind(WizardKind kind) { return findWizardFactories(WizardKindPredicate(kind)); } QString IWizardFactory::runPath(const QString &defaultPath) { QString path = defaultPath; if (path.isEmpty()) { switch (kind()) { case IWizardFactory::ProjectWizard: // Project wizards: Check for projects directory or // use last visited directory of file dialog. Never start // at current. path = DocumentManager::useProjectsDirectory() ? DocumentManager::projectsDirectory() : DocumentManager::fileDialogLastVisitedDirectory(); break; default: path = DocumentManager::fileDialogInitialDirectory(); break; } } return path; } bool IWizardFactory::isAvailable(const QString &platformName) const { return availableFeatures(platformName).contains(requiredFeatures()); } QStringList IWizardFactory::supportedPlatforms() const { QStringList stringList; foreach (const QString &platform, allAvailablePlatforms()) { if (isAvailable(platform)) stringList.append(platform); } return stringList; } void IWizardFactory::registerFactoryCreator(const IWizardFactory::FactoryCreator &creator) { s_factoryCreators << creator; } QStringList IWizardFactory::allAvailablePlatforms() { QStringList platforms; foreach (const IFeatureProvider *featureManager, s_providerList) platforms.append(featureManager->availablePlatforms()); return platforms; } QString IWizardFactory::displayNameForPlatform(const QString &string) { foreach (const IFeatureProvider *featureManager, s_providerList) { QString displayName = featureManager->displayNameForPlatform(string); if (!displayName.isEmpty()) return displayName; } return QString(); } void IWizardFactory::registerFeatureProvider(IFeatureProvider *provider) { QTC_ASSERT(!s_providerList.contains(provider), return); s_providerList.append(provider); } void IWizardFactory::destroyFeatureProvider() { qDeleteAll(s_providerList); s_providerList.clear(); } void IWizardFactory::clearWizardFactories() { foreach (IWizardFactory *factory, s_allFactories) ActionManager::unregisterAction(factory->m_action, actionId(factory)); qDeleteAll(s_allFactories); s_allFactories.clear(); s_areFactoriesLoaded = false; } FeatureSet IWizardFactory::pluginFeatures() const { static FeatureSet plugins; if (plugins.isEmpty()) { QStringList list; // Implicitly create a feature for each plugin loaded: foreach (ExtensionSystem::PluginSpec *s, ExtensionSystem::PluginManager::plugins()) { if (s->state() == ExtensionSystem::PluginSpec::Running) list.append(s->name()); } plugins = FeatureSet::fromStringList(list); } return plugins; } FeatureSet IWizardFactory::availableFeatures(const QString &platformName) const { FeatureSet availableFeatures = pluginFeatures(); foreach (const IFeatureProvider *featureManager, s_providerList) availableFeatures |= featureManager->availableFeatures(platformName); return availableFeatures; } void IWizardFactory::initialize() { connect(ICore::instance(), &ICore::coreAboutToClose, &IWizardFactory::clearWizardFactories); auto resetAction = new QAction(tr("Reload All Wizards"), ActionManager::instance()); ActionManager::registerAction(resetAction, "Wizard.Factory.Reset"); connect(resetAction, &QAction::triggered, &IWizardFactory::clearWizardFactories); } <commit_msg>Wizards: Do not list json wizards that go with plugins that are not loaded<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "iwizardfactory.h" #include "actionmanager/actionmanager.h" #include "documentmanager.h" #include "icore.h" #include "featureprovider.h" #include <extensionsystem/pluginspec.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QAction> /*! \class Core::IWizardFactory \mainclass \brief The class IWizardFactory is the base class for all wizard factories (for example shown in \gui {File | New}). The wizard interface is a very thin abstraction for the \gui{New...} wizards. Basically it defines what to show to the user in the wizard selection dialogs, and a hook that is called if the user selects the wizard. Wizards can then perform any operations they like, including showing dialogs and creating files. Often it is not necessary to create your own wizard from scratch, instead use one of the predefined wizards and adapt it to your needs. To make your wizard known to the system, add your IWizardFactory instance to the plugin manager's object pool in your plugin's initialize function: \code bool MyPlugin::initialize(const QStringList &arguments, QString *errorString) { // ... do setup addAutoReleasedObject(new MyWizardFactory); // ... do more setup } \endcode \sa Core::BaseFileWizard \sa Core::StandardFileWizard */ /*! \enum Core::IWizardFactory::WizardKind Used to specify what kind of objects the wizard creates. This information is used to show e.g. only wizards that create projects when selecting a \gui{New Project} menu item. \value FileWizard The wizard creates one or more files. \value ClassWizard The wizard creates a new class (e.g. source+header files). \value ProjectWizard The wizard creates a new project. */ /*! \fn IWizardFactory::IWizardFactory(QObject *parent) \internal */ /*! \fn IWizardFactory::~IWizardFactory() \internal */ /*! \fn Kind IWizardFactory::kind() const Returns what kind of objects are created by the wizard. \sa Kind */ /*! \fn QIcon IWizardFactory::icon() const Returns an icon to show in the wizard selection dialog. */ /*! \fn QString IWizardFactory::description() const Returns a translated description to show when this wizard is selected in the dialog. */ /*! \fn QString IWizardFactory::displayName() const Returns the translated name of the wizard, how it should appear in the dialog. */ /*! \fn QString IWizardFactory::id() const Returns an arbitrary id that is used for sorting within the category. */ /*! \fn QString IWizardFactory::category() const Returns a category ID to add the wizard to. */ /*! \fn QString IWizardFactory::displayCategory() const Returns the translated string of the category, how it should appear in the dialog. */ /*! \fn void IWizardFactory::runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &variables) This function is executed when the wizard has been selected by the user for execution. Any dialogs the wizard opens should use the given \a parent. The \a path argument is a suggestion for the location where files should be created. The wizard should fill this in its path selection elements as a default path. */ using namespace Core; namespace { static QList<IFeatureProvider *> s_providerList; QList<IWizardFactory *> s_allFactories; QList<IWizardFactory::FactoryCreator> s_factoryCreators; bool s_areFactoriesLoaded = false; } /* A utility to find all wizards supporting a view mode and matching a predicate */ template <class Predicate> QList<IWizardFactory*> findWizardFactories(Predicate predicate) { // Filter all wizards const QList<IWizardFactory*> allFactories = IWizardFactory::allWizardFactories(); QList<IWizardFactory*> rc; const QList<IWizardFactory*>::const_iterator cend = allFactories.constEnd(); for (QList<IWizardFactory*>::const_iterator it = allFactories.constBegin(); it != cend; ++it) if (predicate(*(*it))) rc.push_back(*it); return rc; } static Id actionId(const IWizardFactory *factory) { return factory->id().withPrefix("Wizard.Impl."); } QList<IWizardFactory*> IWizardFactory::allWizardFactories() { if (!s_areFactoriesLoaded) { QTC_ASSERT(s_allFactories.isEmpty(), return s_allFactories); s_areFactoriesLoaded = true; QHash<Id, IWizardFactory *> sanityCheck; foreach (const FactoryCreator &fc, s_factoryCreators) { QList<IWizardFactory *> tmp = fc(); foreach (IWizardFactory *newFactory, tmp) { QTC_ASSERT(newFactory, continue); IWizardFactory *existingFactory = sanityCheck.value(newFactory->id()); QTC_ASSERT(existingFactory != newFactory, continue); if (existingFactory) { qWarning("%s", qPrintable(tr("Factory with id=\"%1\" already registered. Deleting.") .arg(existingFactory->id().toString()))); delete newFactory; continue; } QTC_ASSERT(!newFactory->m_action, continue); newFactory->m_action = new QAction(newFactory->displayName(), newFactory); ActionManager::registerAction(newFactory->m_action, actionId(newFactory)); connect(newFactory->m_action, &QAction::triggered, newFactory, [newFactory]() { QString path = newFactory->runPath(QString()); newFactory->runWizard(path, ICore::dialogParent(), QString(), QVariantMap()); }); sanityCheck.insert(newFactory->id(), newFactory); s_allFactories << newFactory; } } } return s_allFactories; } // Utility to find all registered wizards of a certain kind class WizardKindPredicate { public: WizardKindPredicate(IWizardFactory::WizardKind kind) : m_kind(kind) {} bool operator()(const IWizardFactory &w) const { return w.kind() == m_kind; } private: const IWizardFactory::WizardKind m_kind; }; QList<IWizardFactory*> IWizardFactory::wizardFactoriesOfKind(WizardKind kind) { return findWizardFactories(WizardKindPredicate(kind)); } QString IWizardFactory::runPath(const QString &defaultPath) { QString path = defaultPath; if (path.isEmpty()) { switch (kind()) { case IWizardFactory::ProjectWizard: // Project wizards: Check for projects directory or // use last visited directory of file dialog. Never start // at current. path = DocumentManager::useProjectsDirectory() ? DocumentManager::projectsDirectory() : DocumentManager::fileDialogLastVisitedDirectory(); break; default: path = DocumentManager::fileDialogInitialDirectory(); break; } } return path; } bool IWizardFactory::isAvailable(const QString &platformName) const { if (platformName.isEmpty()) return true; return availableFeatures(platformName).contains(requiredFeatures()); } QStringList IWizardFactory::supportedPlatforms() const { QStringList stringList; foreach (const QString &platform, allAvailablePlatforms()) { if (isAvailable(platform)) stringList.append(platform); } return stringList; } void IWizardFactory::registerFactoryCreator(const IWizardFactory::FactoryCreator &creator) { s_factoryCreators << creator; } QStringList IWizardFactory::allAvailablePlatforms() { QStringList platforms; foreach (const IFeatureProvider *featureManager, s_providerList) platforms.append(featureManager->availablePlatforms()); return platforms; } QString IWizardFactory::displayNameForPlatform(const QString &string) { foreach (const IFeatureProvider *featureManager, s_providerList) { QString displayName = featureManager->displayNameForPlatform(string); if (!displayName.isEmpty()) return displayName; } return QString(); } void IWizardFactory::registerFeatureProvider(IFeatureProvider *provider) { QTC_ASSERT(!s_providerList.contains(provider), return); s_providerList.append(provider); } void IWizardFactory::destroyFeatureProvider() { qDeleteAll(s_providerList); s_providerList.clear(); } void IWizardFactory::clearWizardFactories() { foreach (IWizardFactory *factory, s_allFactories) ActionManager::unregisterAction(factory->m_action, actionId(factory)); qDeleteAll(s_allFactories); s_allFactories.clear(); s_areFactoriesLoaded = false; } FeatureSet IWizardFactory::pluginFeatures() const { static FeatureSet plugins; if (plugins.isEmpty()) { QStringList list; // Implicitly create a feature for each plugin loaded: foreach (ExtensionSystem::PluginSpec *s, ExtensionSystem::PluginManager::plugins()) { if (s->state() == ExtensionSystem::PluginSpec::Running) list.append(s->name()); } plugins = FeatureSet::fromStringList(list); } return plugins; } FeatureSet IWizardFactory::availableFeatures(const QString &platformName) const { FeatureSet availableFeatures = pluginFeatures(); foreach (const IFeatureProvider *featureManager, s_providerList) availableFeatures |= featureManager->availableFeatures(platformName); return availableFeatures; } void IWizardFactory::initialize() { connect(ICore::instance(), &ICore::coreAboutToClose, &IWizardFactory::clearWizardFactories); auto resetAction = new QAction(tr("Reload All Wizards"), ActionManager::instance()); ActionManager::registerAction(resetAction, "Wizard.Factory.Reset"); connect(resetAction, &QAction::triggered, &IWizardFactory::clearWizardFactories); } <|endoftext|>
<commit_before>// include google test #include <gtest/gtest.h> // include classes to test #include <common/Kmer.hpp> // templated test function template<typename kmer_word_type, typename input_word_type, unsigned int kmer_size=31, unsigned int bits_per_char=2> void test_kmer_with_word_type(input_word_type* kmer_data, uint64_t* kmer_ex) { typedef typename bliss::Kmer<kmer_size, bits_per_char, kmer_word_type> kmer_type; // create (fill) Kmer kmer_type kmer; input_word_type* kmer_pointer = kmer_data; // fill first kmer kmer.fillFromPaddedStream(kmer_pointer); kmer_type kmer_ex_0(reinterpret_cast<kmer_word_type*>(kmer_ex)); EXPECT_EQ(kmer, kmer_ex_0) << "Kmer from stream should be equal to kmer from non-stream"; // get offset const unsigned int kmer_bits = kmer_size * bits_per_char; unsigned int offset = kmer_bits % (sizeof(input_word_type)*8); kmer_pointer += kmer_bits / (sizeof(input_word_type)*8); unsigned int step_factor = bits_per_char / 2; // generate more kmers for (unsigned int i = step_factor; i < 25; i += step_factor) { kmer.nextKmerFromPaddedStream(kmer_pointer, offset); kmer_type kmer_ex_i(reinterpret_cast<kmer_word_type*>(kmer_ex+i)); EXPECT_EQ(kmer_ex_i, kmer) << "Kmer compare unequal for sizeof(input)="<< sizeof(input_word_type) << ", sizeof(kmer_word)=" << sizeof(kmer_word_type) << ", size=" << kmer_size << ", bits=" << bits_per_char << " i = " << i; } } template<typename input_word_type, unsigned int kmer_size=31, unsigned int bits_per_char=2> void test_kmers_with_input_type(input_word_type* kmer_data, uint64_t* kmer_ex) { test_kmer_with_word_type<uint8_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex); test_kmer_with_word_type<uint16_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex); test_kmer_with_word_type<uint32_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex); test_kmer_with_word_type<uint64_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex); } template<typename input_word_type> void test_kmers(input_word_type* kmer_data, uint64_t* kmer_ex) { // test for bits per character: 2, 4, and 8 (no padding only!) test_kmers_with_input_type<input_word_type, 31, 2>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 28, 2>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 13, 2>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 4, 2>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 1, 2>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 10, 4>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 13, 4>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 7, 8>(kmer_data, kmer_ex); test_kmers_with_input_type<input_word_type, 5, 8>(kmer_data, kmer_ex); } TEST(KmerGeneration, TestKmerGenerationUnpadded) { // test sequence: 0xabba56781234deadbeef01c0ffee // expected kmers: // generated by the python commands (thank you python for integrated bigints) /* * val = 0xabba56781234deadbeef01c0ffee * print(",\n".join([" "*24 + "0x" + hex(val >> 2*i)[-16:] for i in range(0,25)])) */ uint64_t kmer_ex[25] = {0xdeadbeef01c0ffee, 0x37ab6fbbc0703ffb, 0x4deadbeef01c0ffe, 0xd37ab6fbbc0703ff, 0x34deadbeef01c0ff, 0x8d37ab6fbbc0703f, 0x234deadbeef01c0f, 0x48d37ab6fbbc0703, 0x1234deadbeef01c0, 0x048d37ab6fbbc070, 0x81234deadbeef01c, 0xe048d37ab6fbbc07, 0x781234deadbeef01, 0x9e048d37ab6fbbc0, 0x6781234deadbeef0, 0x59e048d37ab6fbbc, 0x56781234deadbeef, 0x959e048d37ab6fbb, 0xa56781234deadbee, 0xe959e048d37ab6fb, 0xba56781234deadbe, 0xee959e048d37ab6f, 0xbba56781234deadb, 0xaee959e048d37ab6, 0xabba56781234dead}; // unpadded stream (bits_per_char is 2 => no padding) uint16_t kmer_data[8] = {0xffee, 0x01c0, 0xbeef, 0xdead, 0x1234, 0x5678, 0xabba, 0x0000}; // test with this data test_kmers<uint16_t>(kmer_data, kmer_ex); // NO padding, therefore we can test for different input types as well // 8 bit input test_kmers<uint8_t>(reinterpret_cast<uint8_t*>(kmer_data), kmer_ex); // 32 bit input test_kmers<uint32_t>(reinterpret_cast<uint32_t*>(kmer_data), kmer_ex); // 64 bit input test_kmers<uint64_t>(reinterpret_cast<uint64_t*>(kmer_data), kmer_ex); }<commit_msg>more test cases, FIXME: fails for 5<commit_after>// include google test #include <gtest/gtest.h> #include <boost/concept_check.hpp> // include classes to test #include <common/Kmer.hpp> // templated test function template<typename kmer_word_type, typename input_word_type, unsigned int kmer_size=31, unsigned int bits_per_char=2> void test_kmer_with_word_type(input_word_type* kmer_data, uint64_t* kmer_ex, unsigned int nkmers, unsigned step=1) { typedef typename bliss::Kmer<kmer_size, bits_per_char, kmer_word_type> kmer_type; // create (fill) Kmer kmer_type kmer; input_word_type* kmer_pointer = kmer_data; // fill first kmer kmer.fillFromPaddedStream(kmer_pointer); kmer_type kmer_ex_0(reinterpret_cast<kmer_word_type*>(kmer_ex)); EXPECT_EQ(kmer, kmer_ex_0) << "Kmer from stream should be equal to kmer from non-stream"; // get offset const unsigned int kmer_bits = kmer_size * bits_per_char; const unsigned int data_bits = bliss::PaddingTraits<input_word_type, bits_per_char>::data_bits; unsigned int offset = kmer_bits % data_bits; kmer_pointer += kmer_bits / data_bits; // generate more kmers for (unsigned int i = step; i < nkmers; i += step) { kmer.nextKmerFromPaddedStream(kmer_pointer, offset); kmer_type kmer_ex_i(reinterpret_cast<kmer_word_type*>(kmer_ex+i)); EXPECT_EQ(kmer_ex_i, kmer) << "Kmer compare unequal for sizeof(input)="<< sizeof(input_word_type) << ", sizeof(kmer_word)=" << sizeof(kmer_word_type) << ", size=" << kmer_size << ", bits=" << bits_per_char << " i = " << i; } } template<typename input_word_type, unsigned int kmer_size=31, unsigned int bits_per_char=2> void test_kmers_with_input_type(input_word_type* kmer_data, uint64_t* kmer_ex, unsigned int nkmers, unsigned int step=1) { // test with various kmer base types test_kmer_with_word_type<uint8_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex, nkmers, step); test_kmer_with_word_type<uint16_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex, nkmers, step); test_kmer_with_word_type<uint32_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex, nkmers, step); test_kmer_with_word_type<uint64_t, input_word_type, kmer_size, bits_per_char>(reinterpret_cast<input_word_type*>(kmer_data), kmer_ex, nkmers, step); } template<typename input_word_type> void test_kmers(input_word_type* kmer_data, uint64_t* kmer_ex, unsigned int nkmers) { // test for bits per character: 2, 4, and 8 (no padding only!) test_kmers_with_input_type<input_word_type, 31, 2>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 28, 2>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 13, 2>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 4, 2>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 1, 2>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 10, 4>(kmer_data, kmer_ex, nkmers, 2); test_kmers_with_input_type<input_word_type, 13, 4>(kmer_data, kmer_ex, nkmers, 2); test_kmers_with_input_type<input_word_type, 7, 8>(kmer_data, kmer_ex, nkmers, 4); test_kmers_with_input_type<input_word_type, 5, 8>(kmer_data, kmer_ex, nkmers, 4); } template<typename input_word_type> void test_kmers_3(input_word_type* kmer_data, uint64_t* kmer_ex, unsigned int nkmers) { // maximum in 64 bits is 21 test_kmers_with_input_type<input_word_type, 21, 3>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 20, 3>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 13, 3>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 9, 3>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 1, 3>(kmer_data, kmer_ex, nkmers); } template<typename input_word_type> void test_kmers_5(input_word_type* kmer_data, uint64_t* kmer_ex, unsigned int nkmers) { // maximum in 64 bits is 12 test_kmers_with_input_type<input_word_type, 12, 5>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 11, 5>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 10, 5>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 9, 5>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 5, 5>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 3, 5>(kmer_data, kmer_ex, nkmers); test_kmers_with_input_type<input_word_type, 1, 5>(kmer_data, kmer_ex, nkmers); } TEST(KmerGeneration, TestKmerGenerationUnpadded) { // test sequence: 0xabba56781234deadbeef01c0ffee // expected kmers: // generated by the python commands (thank you python for integrated bigints) /* * val = 0xabba56781234deadbeef01c0ffee * print(",\n".join([" "*24 + "0x" + hex(val >> 2*i)[-16:] for i in range(0,25)])) */ uint64_t kmer_ex[25] = {0xdeadbeef01c0ffee, 0x37ab6fbbc0703ffb, 0x4deadbeef01c0ffe, 0xd37ab6fbbc0703ff, 0x34deadbeef01c0ff, 0x8d37ab6fbbc0703f, 0x234deadbeef01c0f, 0x48d37ab6fbbc0703, 0x1234deadbeef01c0, 0x048d37ab6fbbc070, 0x81234deadbeef01c, 0xe048d37ab6fbbc07, 0x781234deadbeef01, 0x9e048d37ab6fbbc0, 0x6781234deadbeef0, 0x59e048d37ab6fbbc, 0x56781234deadbeef, 0x959e048d37ab6fbb, 0xa56781234deadbee, 0xe959e048d37ab6fb, 0xba56781234deadbe, 0xee959e048d37ab6f, 0xbba56781234deadb, 0xaee959e048d37ab6, 0xabba56781234dead}; // unpadded stream (bits_per_char is 2 => no padding) /* python: * ", ".join("0x" + hex((val >> i*16) & 0xffff) for i in range(0, 8)) */ uint16_t kmer_data[8] = {0xffee, 0x01c0, 0xbeef, 0xdead, 0x1234, 0x5678, 0xabba, 0x0000}; // test with this data test_kmers<uint16_t>(kmer_data, kmer_ex, 25); // NO padding, therefore we can test for different input types as well // 8 bit input test_kmers<uint8_t>(reinterpret_cast<uint8_t*>(kmer_data), kmer_ex, 25); // 32 bit input test_kmers<uint32_t>(reinterpret_cast<uint32_t*>(kmer_data), kmer_ex, 25); // 64 bit input test_kmers<uint64_t>(reinterpret_cast<uint64_t*>(kmer_data), kmer_ex, 25); } /** * Test k-mer generation with 3 bits and thus padded input */ TEST(KmerGeneration, TestKmerGenerationPadded3) { // test sequence: 0xabba56781234deadbeef01c0ffee // expected kmers: // generated by the python commands (thank you python for integrated bigints) /* * val = 0xabba56781234deadbeef01c0ffee * print(",\n".join([" "*24 + "0x" + hex(val >> 3*i)[-16:] for i in range(0,17)])) */ uint64_t kmer_ex[17] = {0xdeadbeef01c0ffee, 0x9bd5b7dde0381ffd, 0xd37ab6fbbc0703ff, 0x1a6f56df7780e07f, 0x234deadbeef01c0f, 0x2469bd5b7dde0381, 0x048d37ab6fbbc070, 0xc091a6f56df7780e, 0x781234deadbeef01, 0xcf02469bd5b7dde0, 0x59e048d37ab6fbbc, 0x2b3c091a6f56df77, 0xa56781234deadbee, 0x74acf02469bd5b7d, 0xee959e048d37ab6f, 0x5dd2b3c091a6f56d, 0xabba56781234dead}; // unpadded stream (bits_per_char is 3 => 1 bit padding) /* python: * ", ".join(hex((val >> i*15) & 0x7fff) for i in range(0, 9)) */ uint16_t kmer_data[9] = {0x7fee, 0x381, 0x7bbc, 0x756d, 0x234d, 0x4f02, 0x6e95, 0x55, 0x0}; // test with this data test_kmers_3<uint16_t>(kmer_data, kmer_ex, 17); /* python: * ", ".join(hex((val >> i*6) & 0x3f) for i in range(0, 20)) */ uint8_t kmer_data_8[20] = {0x2e, 0x3f, 0xf, 0x30, 0x1, 0x3c, 0x2e, 0x2f, 0x2d, 0x3a, 0xd, 0xd, 0x12, 0x20, 0x27, 0x15, 0x3a, 0x2e, 0xa, 0x0}; // test with 8 bit (padded by 2 bits) test_kmers_3<uint8_t>(kmer_data_8, kmer_ex, 17); /* python: * ", ".join(hex((val >> i*30) & 0x3fffffff) for i in range(0, 5)) */ // 32 bits: uint32_t kmer_data_32[5] = {0x1c0ffee, 0x3ab6fbbc, 0x2781234d, 0x2aee95, 0x0}; test_kmers_3<uint32_t>(kmer_data_32, kmer_ex, 17); /* python: * ", ".join(hex((val >> i*63) & 0x7fffffffffffffff) for i in range(0, 3)) */ // 64 bits: uint64_t kmer_data_64[3] = {0x5eadbeef01c0ffee, 0x15774acf02469, 0x0}; test_kmers_3<uint64_t>(kmer_data_64, kmer_ex, 17); } /** * Test k-mer generation with 5 bits and thus padded input */ TEST(KmerGeneration, TestKmerGenerationPadded5) { // test sequence: 0xabba56781234deadbeef01c0ffee // expected kmers: // generated by the python commands (thank you python for integrated bigints) /* * val = 0xabba56781234deadbeef01c0ffee * print(",\n".join([" "*24 + "0x" + hex(val >> 5*i)[-16:] for i in range(0,11)])) */ uint64_t kmer_ex[11] = {0xdeadbeef01c0ffee, 0xa6f56df7780e07ff, 0x8d37ab6fbbc0703f, 0x2469bd5b7dde0381, 0x81234deadbeef01c, 0x3c091a6f56df7780, 0x59e048d37ab6fbbc, 0x4acf02469bd5b7dd, 0xba56781234deadbe, 0x5dd2b3c091a6f56d, 0x2aee959e048d37ab}; // unpadded stream (bits_per_char is 5 => 1 bit padding) /* python: * ", ".join(hex((val >> i*15) & 0x7fff) for i in range(0, 9)) */ uint16_t kmer_data[9] = {0x7fee, 0x381, 0x7bbc, 0x756d, 0x234d, 0x4f02, 0x6e95, 0x55, 0x0}; // test with this data test_kmers_5<uint16_t>(kmer_data, kmer_ex, 11); /* python: * ", ".join(hex((val >> i*5) & 0x1f) for i in range(0, 24)) */ uint8_t kmer_data_8[24] = {0xe, 0x1f, 0x1f, 0x1, 0x1c, 0x0, 0x1c, 0x1d, 0x1e, 0xd, 0xb, 0x1d, 0xd, 0x1a, 0x8, 0x2, 0x18, 0x13, 0x15, 0x14, 0x1b, 0x15, 0x2, 0x0}; // test with 8 bit (padded by 3 bits) test_kmers_5<uint8_t>(kmer_data_8, kmer_ex, 11); /* python: * ", ".join(hex((val >> i*30) & 0x3fffffff) for i in range(0, 5)) */ // 32 bits (2 bits padding) uint32_t kmer_data_32[5] = {0x1c0ffee, 0x3ab6fbbc, 0x2781234d, 0x2aee95, 0x0}; test_kmers_5<uint32_t>(kmer_data_32, kmer_ex, 11); /* python: * ", ".join(hex((val >> i*60) & 0x0fffffffffffffff) for i in range(0, 3)) */ // 64 bits (4 bits padding) uint64_t kmer_data_64[3] = {0xeadbeef01c0ffee, 0xabba56781234d, 0x0}; test_kmers_5<uint64_t>(kmer_data_64, kmer_ex, 11); }<|endoftext|>
<commit_before>#include "Utility.h" #include <string> #include <fstream> #ifdef WIN32 #include <shlwapi.h> #else #ifdef __APPLE_ #include <mach-o/dyld.h> #endif #include <sstream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <fstream> #include <signal.h> #endif namespace util { #ifdef WIN32 std::string getModuleDirectory(void* module) { std::string result; char path[2048]; int length = GetModuleFileName((HMODULE) module, path, 2048); if (length > 0 && length <= 2048) { if (PathRemoveFileSpec(path)) { result.assign(path); } } return result; } #else std::string getModuleDirectory(void* module) { std::string result; #ifdef __APPLE__ char pathbuf[PATH_MAX + 1]; uint32_t bufsize = sizeof(pathbuf); _NSGetExecutablePath(pathbuf, &bufsize); char *resolved = realpath(pathbuf, NULL); result.assign(resolved); free(resolved); size_t last = result.find_last_of("/"); return result.substr(0, last); /* remove filename component */ #else std::stringstream ss; ss << "/proc/" << (int) getpid() << "/exe"; std::string pathToProc = ss.str(); char pathbuf[4096 + 1]; readlink(pathToProc.c_str(), pathbuf, 4096); result.assign(pathbuf); size_t last = result.find_last_of("/"); return result.substr(0, last); /* remove filename component */ #endif } #endif #ifdef WIN32 void sleep(long long millis) { Sleep((DWORD) millis); } #else void sleep(long long millis) { usleep(millis * 1000); } #endif #ifndef WIN32 static const std::string PID_FILENAME = "/tmp/projectM_musikcube.pid"; void writeExePidFile() { std::ofstream out(PID_FILENAME); out << (int) getpid(); out.close(); } int readExePidFile() { int result = 0; std::ifstream in(PID_FILENAME); if (in.is_open()) { in >> result; } return result; } bool isExeRunning() { int pid = readExePidFile(); if (pid != 0) { return kill((pid_t) pid, 0) == 0; } return false; } #endif } <commit_msg>Fixed macOS preprocessor macro.<commit_after>#include "Utility.h" #include <string> #include <fstream> #ifdef WIN32 #include <shlwapi.h> #else #ifdef __APPLE__ #include <mach-o/dyld.h> #endif #include <sstream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <fstream> #include <signal.h> #endif namespace util { #ifdef WIN32 std::string getModuleDirectory(void* module) { std::string result; char path[2048]; int length = GetModuleFileName((HMODULE) module, path, 2048); if (length > 0 && length <= 2048) { if (PathRemoveFileSpec(path)) { result.assign(path); } } return result; } #else std::string getModuleDirectory(void* module) { std::string result; #ifdef __APPLE__ char pathbuf[PATH_MAX + 1]; uint32_t bufsize = sizeof(pathbuf); _NSGetExecutablePath(pathbuf, &bufsize); char *resolved = realpath(pathbuf, NULL); result.assign(resolved); free(resolved); size_t last = result.find_last_of("/"); return result.substr(0, last); /* remove filename component */ #else std::stringstream ss; ss << "/proc/" << (int) getpid() << "/exe"; std::string pathToProc = ss.str(); char pathbuf[4096 + 1]; readlink(pathToProc.c_str(), pathbuf, 4096); result.assign(pathbuf); size_t last = result.find_last_of("/"); return result.substr(0, last); /* remove filename component */ #endif } #endif #ifdef WIN32 void sleep(long long millis) { Sleep((DWORD) millis); } #else void sleep(long long millis) { usleep(millis * 1000); } #endif #ifndef WIN32 static const std::string PID_FILENAME = "/tmp/projectM_musikcube.pid"; void writeExePidFile() { std::ofstream out(PID_FILENAME); out << (int) getpid(); out.close(); } int readExePidFile() { int result = 0; std::ifstream in(PID_FILENAME); if (in.is_open()) { in >> result; } return result; } bool isExeRunning() { int pid = readExePidFile(); if (pid != 0) { return kill((pid_t) pid, 0) == 0; } return false; } #endif } <|endoftext|>
<commit_before>// Copyright (c) 2015-2016 The Khronos Group 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. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #include <stdio.h> // Need fileno #include <unistd.h> #endif #include <cstdio> #include <cstring> #include <string> #include <vector> #include "spirv-tools/libspirv.h" #include "tools/io.h" static void print_usage(char* argv0) { printf( R"(%s - Disassemble a SPIR-V binary module Usage: %s [options] [<filename>] The SPIR-V binary is read from <filename>. If no file is specified, or if the filename is "-", then the binary is read from standard input. Options: -h, --help Print this help. --version Display disassembler version information. -o <filename> Set the output filename. Output goes to standard output if this option is not specified, or if the filename is "-". --no-color Don't print in color. The default when output goes to something other than a terminal (e.g. a file, a pipe, or a shell redirection). --no-indent Don't indent instructions. --no-header Don't output the header as leading comments. --raw-id Show raw Id values instead of friendly names. --offsets Show byte offsets for each instruction. )", argv0, argv0); } static const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_2; int main(int argc, char** argv) { const char* inFile = nullptr; const char* outFile = nullptr; bool allow_color = false; #ifdef SPIRV_COLOR_TERMINAL allow_color = true; #endif bool allow_indent = true; bool show_byte_offsets = false; bool no_header = false; bool friendly_names = true; for (int argi = 1; argi < argc; ++argi) { if ('-' == argv[argi][0]) { switch (argv[argi][1]) { case 'h': print_usage(argv[0]); return 0; case 'o': { if (!outFile && argi + 1 < argc) { outFile = argv[++argi]; } else { print_usage(argv[0]); return 1; } } break; case '-': { // Long options if (0 == strcmp(argv[argi], "--no-color")) { allow_color = false; } else if (0 == strcmp(argv[argi], "--no-indent")) { allow_indent = false; } else if (0 == strcmp(argv[argi], "--offsets")) { show_byte_offsets = true; } else if (0 == strcmp(argv[argi], "--no-header")) { no_header = true; } else if (0 == strcmp(argv[argi], "--raw-id")) { friendly_names = false; } else if (0 == strcmp(argv[argi], "--help")) { print_usage(argv[0]); return 0; } else if (0 == strcmp(argv[argi], "--version")) { printf("%s\n", spvSoftwareVersionDetailsString()); printf("Target: %s\n", spvTargetEnvDescription(kDefaultEnvironment)); return 0; } else { print_usage(argv[0]); return 1; } } break; case 0: { // Setting a filename of "-" to indicate stdin. if (!inFile) { inFile = argv[argi]; } else { fprintf(stderr, "error: More than one input file specified\n"); return 1; } } break; default: print_usage(argv[0]); return 1; } } else { if (!inFile) { inFile = argv[argi]; } else { fprintf(stderr, "error: More than one input file specified\n"); return 1; } } } uint32_t options = SPV_BINARY_TO_TEXT_OPTION_NONE; if (allow_indent) options |= SPV_BINARY_TO_TEXT_OPTION_INDENT; if (show_byte_offsets) options |= SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET; if (no_header) options |= SPV_BINARY_TO_TEXT_OPTION_NO_HEADER; if (friendly_names) options |= SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES; if (!outFile || (0 == strcmp("-", outFile))) { // Print to standard output. options |= SPV_BINARY_TO_TEXT_OPTION_PRINT; bool output_is_tty = true; #if defined(_POSIX_VERSION) output_is_tty = isatty(fileno(stdout)); #endif if (allow_color && output_is_tty) { options |= SPV_BINARY_TO_TEXT_OPTION_COLOR; } } // Read the input binary. std::vector<uint32_t> contents; if (!ReadFile<uint32_t>(inFile, "rb", &contents)) return 1; // If printing to standard output, then spvBinaryToText should // do the printing. In particular, colour printing on Windows is // controlled by modifying console objects synchronously while // outputting to the stream rather than by injecting escape codes // into the output stream. // If the printing option is off, then save the text in memory, so // it can be emitted later in this function. const bool print_to_stdout = SPV_BINARY_TO_TEXT_OPTION_PRINT & options; spv_text text = nullptr; spv_text* textOrNull = print_to_stdout ? nullptr : &text; spv_diagnostic diagnostic = nullptr; spv_context context = spvContextCreate(kDefaultEnvironment); spv_result_t error = spvBinaryToText(context, contents.data(), contents.size(), options, textOrNull, &diagnostic); spvContextDestroy(context); if (error) { spvDiagnosticPrint(diagnostic); spvDiagnosticDestroy(diagnostic); return error; } if (!print_to_stdout) { if (!WriteFile<char>(outFile, "w", text->str, text->length)) { spvTextDestroy(text); return 1; } } spvTextDestroy(text); return 0; } <commit_msg>spirv-dis: Add --color option to force color disassembly<commit_after>// Copyright (c) 2015-2016 The Khronos Group 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. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #include <stdio.h> // Need fileno #include <unistd.h> #endif #include <cstdio> #include <cstring> #include <string> #include <vector> #include "spirv-tools/libspirv.h" #include "tools/io.h" static void print_usage(char* argv0) { printf( R"(%s - Disassemble a SPIR-V binary module Usage: %s [options] [<filename>] The SPIR-V binary is read from <filename>. If no file is specified, or if the filename is "-", then the binary is read from standard input. Options: -h, --help Print this help. --version Display disassembler version information. -o <filename> Set the output filename. Output goes to standard output if this option is not specified, or if the filename is "-". --color Force color output. The default when printing to a terminal. Overrides a previous --no-color option. --no-color Don't print in color. Overrides a previous --color option. The default when output goes to something other than a terminal (e.g. a file, a pipe, or a shell redirection). --no-indent Don't indent instructions. --no-header Don't output the header as leading comments. --raw-id Show raw Id values instead of friendly names. --offsets Show byte offsets for each instruction. )", argv0, argv0); } static const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_2; int main(int argc, char** argv) { const char* inFile = nullptr; const char* outFile = nullptr; bool color_is_possible = #if SPIRV_COLOR_TERMINAL true; #else false; #endif bool force_color = false; bool force_no_color = false; bool allow_indent = true; bool show_byte_offsets = false; bool no_header = false; bool friendly_names = true; for (int argi = 1; argi < argc; ++argi) { if ('-' == argv[argi][0]) { switch (argv[argi][1]) { case 'h': print_usage(argv[0]); return 0; case 'o': { if (!outFile && argi + 1 < argc) { outFile = argv[++argi]; } else { print_usage(argv[0]); return 1; } } break; case '-': { // Long options if (0 == strcmp(argv[argi], "--no-color")) { force_no_color = true; force_color = false; } else if (0 == strcmp(argv[argi], "--color")) { force_no_color = false; force_color = true; } else if (0 == strcmp(argv[argi], "--no-indent")) { allow_indent = false; } else if (0 == strcmp(argv[argi], "--offsets")) { show_byte_offsets = true; } else if (0 == strcmp(argv[argi], "--no-header")) { no_header = true; } else if (0 == strcmp(argv[argi], "--raw-id")) { friendly_names = false; } else if (0 == strcmp(argv[argi], "--help")) { print_usage(argv[0]); return 0; } else if (0 == strcmp(argv[argi], "--version")) { printf("%s\n", spvSoftwareVersionDetailsString()); printf("Target: %s\n", spvTargetEnvDescription(kDefaultEnvironment)); return 0; } else { print_usage(argv[0]); return 1; } } break; case 0: { // Setting a filename of "-" to indicate stdin. if (!inFile) { inFile = argv[argi]; } else { fprintf(stderr, "error: More than one input file specified\n"); return 1; } } break; default: print_usage(argv[0]); return 1; } } else { if (!inFile) { inFile = argv[argi]; } else { fprintf(stderr, "error: More than one input file specified\n"); return 1; } } } uint32_t options = SPV_BINARY_TO_TEXT_OPTION_NONE; if (allow_indent) options |= SPV_BINARY_TO_TEXT_OPTION_INDENT; if (show_byte_offsets) options |= SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET; if (no_header) options |= SPV_BINARY_TO_TEXT_OPTION_NO_HEADER; if (friendly_names) options |= SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES; if (!outFile || (0 == strcmp("-", outFile))) { // Print to standard output. options |= SPV_BINARY_TO_TEXT_OPTION_PRINT; if (color_is_possible && !force_no_color) { bool output_is_tty = true; #if defined(_POSIX_VERSION) output_is_tty = isatty(fileno(stdout)); #endif if (output_is_tty || force_color) { options |= SPV_BINARY_TO_TEXT_OPTION_COLOR; } } } // Read the input binary. std::vector<uint32_t> contents; if (!ReadFile<uint32_t>(inFile, "rb", &contents)) return 1; // If printing to standard output, then spvBinaryToText should // do the printing. In particular, colour printing on Windows is // controlled by modifying console objects synchronously while // outputting to the stream rather than by injecting escape codes // into the output stream. // If the printing option is off, then save the text in memory, so // it can be emitted later in this function. const bool print_to_stdout = SPV_BINARY_TO_TEXT_OPTION_PRINT & options; spv_text text = nullptr; spv_text* textOrNull = print_to_stdout ? nullptr : &text; spv_diagnostic diagnostic = nullptr; spv_context context = spvContextCreate(kDefaultEnvironment); spv_result_t error = spvBinaryToText(context, contents.data(), contents.size(), options, textOrNull, &diagnostic); spvContextDestroy(context); if (error) { spvDiagnosticPrint(diagnostic); spvDiagnosticDestroy(diagnostic); return error; } if (!print_to_stdout) { if (!WriteFile<char>(outFile, "w", text->str, text->length)) { spvTextDestroy(text); return 1; } } spvTextDestroy(text); return 0; } <|endoftext|>
<commit_before>#include "toolversion.h" #include "json.h" #include <iostream> #include <string> #include <functional> #include <jwtxx/jwt.h> #include <jwtxx/version.h> #include <cstring> #include <cerrno> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> namespace { std::string baseName(const std::string& path) { auto pos = path.find_last_of('/'); if (pos != std::string::npos) return path.substr(pos + 1, path.length() - pos - 1); return path; } void showHelp(const std::string& self) { std::cout << "Usage: " << baseName(self) << " [option]...\n" << "Generate or verify JWT.\n\n" << "Options:\n\n" << "\t-h, --help show help and exit\n" << "\t-v, --version show version and exit\n" << "\t-a, --alg <algorithm> use the specified digital signature algorithm\n" << "\t-k, --key <filename> use the specified file as a key for digital signature\n" << "\t-s, --sign <token> sign data and produce a JWT\n" << "\t-V, --verify <token> verify the supplied JWT\n" << "\t-p, --print <token> show token contents\n"; } void showVersion(const std::string& self) { std::cout << baseName(self) << " " << JWTTool::version << "\n" << "libjwtxx " << JWTXX::version << "\n"; } std::string modeName(mode_t mode) { switch (mode) { case S_IFSOCK: return "a socket"; case S_IFLNK: return "a symbolic link"; case S_IFREG: return "a regilar file"; case S_IFBLK: return "a block device"; case S_IFDIR: return "a directory"; case S_IFCHR: return "a character device"; case S_IFIFO: return "a FIFO"; } return "unknown filesystem entity with mode " + std::to_string(mode); } int noAction(JWTXX::Algorithm /*alg*/, const std::string& /*keyFile*/, const std::string& /*data*/) { std::cerr << "No action specified. Use -s (--sign) to sign a token or -V (--verify) to verify a token.\n"; return -1; } int sign(JWTXX::Algorithm alg, const std::string& keyFile, const std::string& data) { try { auto source = JWTXX::fromJSON(data); JWTXX::JWT jwt(alg, source); std::cout << jwt.token(keyFile) << "\n"; return 0; } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } int verify(JWTXX::Algorithm alg, const std::string& keyFile, const std::string& data) { try { auto res = JWTXX::JWT::verify(data, JWTXX::Key(alg, keyFile)); if (res) { std::cout << "The token is valid.\n"; return 0; } std::cout << "The token is invalid. " << res.message() << "\n"; return -1; } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } int print(JWTXX::Algorithm /*alg*/, const std::string& /*keyFile*/, const std::string& data) { try { auto res = JWTXX::JWT::parse(data); std::cout << "{\n"; bool first = true; for (const auto& header : res.header()) { if (first) first = false; else std::cout << ",\n"; std::cout << "\t\"" << header.first << "\": \"" << header.second << "\""; } std::cout << "\n}\n.\n{\n"; first = true; for (const auto& claim : res.claims()) { if (first) first = false; else std::cout << ",\n"; std::cout << "\t\"" << claim.first << "\": \"" << claim.second << "\""; } std::cout << "\n}\n"; return 0; } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } typedef std::function<int (JWTXX::Algorithm, const std::string&, const std::string&)> Action; } int main(int argc, char* argv[]) { JWTXX::Algorithm alg = JWTXX::Algorithm::none; std::string keyFile; std::string data; Action action = noAction; for (int i = 0; i < argc; ++i) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { showHelp(argv[0]); return 0; } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) { showVersion(argv[0]); return 0; } else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--alg") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - algorithm name.\n"; return -1; } try { alg = JWTXX::stringToAlg(argv[++i]); } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } else if (strcmp(argv[i], "-k") == 0 || strcmp(argv[i], "--key") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - key file name.\n"; return -1; } keyFile = argv[++i]; struct stat sb; if (stat(keyFile.c_str(), &sb) == -1) { std::cerr << "Can't access file '" << keyFile << "'. Error: " << strerror(errno) << "\n"; return -1; } if ((sb.st_mode & S_IFMT) != S_IFREG) { std::cerr << "Key file should be a regular file. '" << keyFile << "' is a " << modeName(sb.st_mode & S_IFMT) << ".\n"; return -1; } } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--sign") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - a token.\n"; return -1; } data = argv[++i]; action = sign; } else if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--verify") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - a token.\n"; return -1; } data = argv[++i]; action = verify; } else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--print") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - a token.\n"; return -1; } data = argv[++i]; action = print; } } return action(alg, keyFile, data); } <commit_msg>Fix error message when no command is specified.<commit_after>#include "toolversion.h" #include "json.h" #include <iostream> #include <string> #include <functional> #include <jwtxx/jwt.h> #include <jwtxx/version.h> #include <cstring> #include <cerrno> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> namespace { std::string baseName(const std::string& path) { auto pos = path.find_last_of('/'); if (pos != std::string::npos) return path.substr(pos + 1, path.length() - pos - 1); return path; } void showHelp(const std::string& self) { std::cout << "Usage: " << baseName(self) << " [option]...\n" << "Generate or verify JWT.\n\n" << "Options:\n\n" << "\t-h, --help show help and exit\n" << "\t-v, --version show version and exit\n" << "\t-a, --alg <algorithm> use the specified digital signature algorithm\n" << "\t-k, --key <filename> use the specified file as a key for digital signature\n" << "\t-s, --sign <token> sign data and produce a JWT\n" << "\t-V, --verify <token> verify the supplied JWT\n" << "\t-p, --print <token> show token contents\n"; } void showVersion(const std::string& self) { std::cout << baseName(self) << " " << JWTTool::version << "\n" << "libjwtxx " << JWTXX::version << "\n"; } std::string modeName(mode_t mode) { switch (mode) { case S_IFSOCK: return "a socket"; case S_IFLNK: return "a symbolic link"; case S_IFREG: return "a regilar file"; case S_IFBLK: return "a block device"; case S_IFDIR: return "a directory"; case S_IFCHR: return "a character device"; case S_IFIFO: return "a FIFO"; } return "unknown filesystem entity with mode " + std::to_string(mode); } int noAction(JWTXX::Algorithm /*alg*/, const std::string& /*keyFile*/, const std::string& /*data*/) { std::cerr << "No action specified. Use -s (--sign) to sign a token or -V (--verify) to verify a token or -p (--print) to print a token.\n"; return -1; } int sign(JWTXX::Algorithm alg, const std::string& keyFile, const std::string& data) { try { auto source = JWTXX::fromJSON(data); JWTXX::JWT jwt(alg, source); std::cout << jwt.token(keyFile) << "\n"; return 0; } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } int verify(JWTXX::Algorithm alg, const std::string& keyFile, const std::string& data) { try { auto res = JWTXX::JWT::verify(data, JWTXX::Key(alg, keyFile)); if (res) { std::cout << "The token is valid.\n"; return 0; } std::cout << "The token is invalid. " << res.message() << "\n"; return -1; } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } int print(JWTXX::Algorithm /*alg*/, const std::string& /*keyFile*/, const std::string& data) { try { auto res = JWTXX::JWT::parse(data); std::cout << "{\n"; bool first = true; for (const auto& header : res.header()) { if (first) first = false; else std::cout << ",\n"; std::cout << "\t\"" << header.first << "\": \"" << header.second << "\""; } std::cout << "\n}\n.\n{\n"; first = true; for (const auto& claim : res.claims()) { if (first) first = false; else std::cout << ",\n"; std::cout << "\t\"" << claim.first << "\": \"" << claim.second << "\""; } std::cout << "\n}\n"; return 0; } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } typedef std::function<int (JWTXX::Algorithm, const std::string&, const std::string&)> Action; } int main(int argc, char* argv[]) { JWTXX::Algorithm alg = JWTXX::Algorithm::none; std::string keyFile; std::string data; Action action = noAction; for (int i = 0; i < argc; ++i) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { showHelp(argv[0]); return 0; } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) { showVersion(argv[0]); return 0; } else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--alg") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - algorithm name.\n"; return -1; } try { alg = JWTXX::stringToAlg(argv[++i]); } catch (const JWTXX::Error& ex) { std::cerr << ex.what() << "\n"; return -1; } } else if (strcmp(argv[i], "-k") == 0 || strcmp(argv[i], "--key") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - key file name.\n"; return -1; } keyFile = argv[++i]; struct stat sb; if (stat(keyFile.c_str(), &sb) == -1) { std::cerr << "Can't access file '" << keyFile << "'. Error: " << strerror(errno) << "\n"; return -1; } if ((sb.st_mode & S_IFMT) != S_IFREG) { std::cerr << "Key file should be a regular file. '" << keyFile << "' is a " << modeName(sb.st_mode & S_IFMT) << ".\n"; return -1; } } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--sign") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - a token.\n"; return -1; } data = argv[++i]; action = sign; } else if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--verify") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - a token.\n"; return -1; } data = argv[++i]; action = verify; } else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--print") == 0) { if (i + 1 == argc) { std::cerr << argv[i] << " needs and argument - a token.\n"; return -1; } data = argv[++i]; action = print; } } return action(alg, keyFile, data); } <|endoftext|>
<commit_before>/* * Part of Jari Komppa's zx spectrum suite * https://github.com/jarikomppa/speccy * released under the unlicense, see http://unlicense.org * (practically public domain) */ #include <stdio.h> #include <stdlib.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" int main(int parc, char ** pars) { int x, y, comp; stbi_uc * raw = stbi_load("s.png", &x, &y, &comp, 4); printf("%d %d %d\n", x, y, comp); unsigned int *p = (unsigned int *)raw; FILE * f = fopen("png.bin","wb"); int i; int d = 0; for (i = 0; i < x*y; i++) { d <<= 1; d |= (p[i] & 0xffffff) == 0; if (i % 8 == 7) { fputc(d, f); d = 0; } } fclose(f); return 0; }<commit_msg>instead of hardcoded filename, use parameter (still far from robust)<commit_after>/* * Part of Jari Komppa's zx spectrum suite * https://github.com/jarikomppa/speccy * released under the unlicense, see http://unlicense.org * (practically public domain) */ #include <stdio.h> #include <stdlib.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" int main(int parc, char ** pars) { int x, y, comp; stbi_uc * raw = stbi_load(pars[1], &x, &y, &comp, 4); printf("%d %d %d\n", x, y, comp); unsigned int *p = (unsigned int *)raw; FILE * f = fopen("png.bin","wb"); int i; int d = 0; for (i = 0; i < x*y; i++) { d <<= 1; d |= p[i] == p[0]; if (i % 8 == 7) { fputc(d, f); d = 0; } } fclose(f); return 0; }<|endoftext|>
<commit_before>// main.cc (2017-12-17) // Yan Gaofeng ([email protected]) #include <iostream> #define LPCSTR char * #define UINT unsigned int class CObject; struct CRuntimeClass { // Attributes LPCSTR m_lpszClassName; int m_nObjectSize; UINT m_wSchema; // schema number of the loaded class CObject* (* m_pfnCreateObject)(); // NULL => abstract class CRuntimeClass* m_pBaseClass; // CRuntimeClass objects linked together in simple list static CRuntimeClass* pFirstClass; // start of class list CRuntimeClass* m_pNextClass; // linked list of registered classes }; CRuntimeClass* CRuntimeClass::pFirstClass = NULL; // 不是宏, 是结构体 struct AFX_CLASSINIT { AFX_CLASSINIT(CRuntimeClass *pNewClass); }; // 构造函数, 不是宏 AFX_CLASSINIT::AFX_CLASSINIT(CRuntimeClass *pNewClass) { pNewClass->m_pNextClass = CRuntimeClass::pFirstClass; CRuntimeClass::pFirstClass = pNewClass; } #define RUNTIME_CLASS(class_name) \ (&class_name::class##class_name) #define DECLARE_DYNAMIC(class_name) \ public: \ static CRuntimeClass class##class_name; \ virtual CRuntimeClass* GetRuntimeClass() const; #define _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, wSchema, pfnNew) \ static char _lpsz##class_name[] = #class_name; \ CRuntimeClass class_name::class##class_name = { \ _lpsz##class_name, sizeof(class_name), wSchema, pfnNew, \ RUNTIME_CLASS(base_class_name), NULL }; \ static AFX_CLASSINIT _init_##class_name(&class_name::class##class_name); \ CRuntimeClass* class_name::GetRuntimeClass() const \ { return &class_name::class##class_name; } \ #define IMPLEMENT_DYNAMIC(class_name, base_class_name) \ _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, 0xFFFF, NULL) // CObject, 表头, 需要特殊构造, 不能直接套用宏 class CObject { public: // 定义成虚函数是因为派生类会改写 virtual CRuntimeClass *GetRuntimeClass() const; bool IsKindOf(const CRuntimeClass *pClass) const; public: static CRuntimeClass classCObject; }; // 判断派生类是否是pClass bool CObject::IsKindOf(const CRuntimeClass *pClass) const { // 获取自身的CRuntimeClass, 如 classWinThread // GetRuntimeClass是虚函数, 派生类会改写 CRuntimeClass *pClassThis = GetRuntimeClass(); while (pClassThis != NULL) { if (pClassThis == pClass) { return true; } // 找基类 pClassThis = pClassThis->m_pBaseClass; } return false; } // 以全局变量的方式定义RTTI static char szCObject[] = "CObject"; struct CRuntimeClass CObject::classCObject = { szCObject, sizeof(CObject), 0xFFFF, NULL, NULL }; static AFX_CLASSINIT _init_CObject(&CObject::classCObject); // CObject成员函数 CRuntimeClass *CObject::GetRuntimeClass() const { return &CObject::classCObject; } // CObject 表头构造结束 // CCmdTarget class CCmdTarget : public CObject { DECLARE_DYNAMIC(CCmdTarget) }; // CWinThread class CWinThread: public CCmdTarget { DECLARE_DYNAMIC(CWinThread) }; IMPLEMENT_DYNAMIC(CCmdTarget, CObject) IMPLEMENT_DYNAMIC(CWinThread, CCmdTarget) void PrintAllClasses() { CRuntimeClass *pClass; for (pClass = CRuntimeClass::pFirstClass; pClass != NULL; pClass = pClass->m_pNextClass) { std::cout << pClass->m_lpszClassName << "\n"; std::cout << pClass->m_nObjectSize << "\n"; std::cout << pClass->m_wSchema << "\n"; } } int main() { PrintAllClasses(); CWinThread o; bool ok = o.IsKindOf(RUNTIME_CLASS(CCmdTarget)); if (ok) { std::cout << "CWinThread is s CCmdTarget" << "\n"; } return 0; } <commit_msg>update mfc/rtti, add dynamic create example<commit_after>// main.cc (2017-12-17) // Yan Gaofeng ([email protected]) #include <iostream> #include <stdio.h> #include <string.h> #define LPCSTR char * #define UINT unsigned int class CObject; struct CRuntimeClass { // Attributes LPCSTR m_lpszClassName; int m_nObjectSize; // schema number of the loaded class UINT m_wSchema; // 由IMPLEMENT_DYNCREATE宏指定 CObject* (* m_pfnCreateObject)(); // NULL => abstract class CRuntimeClass* m_pBaseClass; // 会使用 m_pfnCreateObject 创建具体的对象 CObject* CreateObject(); // CRuntimeClass 有, 其它类没有 static CRuntimeClass* Load(); // CRuntimeClass objects linked together in simple list static CRuntimeClass* pFirstClass; // start of class list CRuntimeClass* m_pNextClass; // linked list of registered classes }; CRuntimeClass* CRuntimeClass::pFirstClass = NULL; // 不是宏, 是结构体 struct AFX_CLASSINIT { AFX_CLASSINIT(CRuntimeClass *pNewClass); }; // 构造函数, 不是宏 AFX_CLASSINIT::AFX_CLASSINIT(CRuntimeClass *pNewClass) { pNewClass->m_pNextClass = CRuntimeClass::pFirstClass; CRuntimeClass::pFirstClass = pNewClass; } #define RUNTIME_CLASS(class_name) \ (&class_name::class##class_name) #define DECLARE_DYNAMIC(class_name) \ public: \ static CRuntimeClass class##class_name; \ virtual CRuntimeClass* GetRuntimeClass() const; #define _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, wSchema, pfnNew) \ static char _lpsz##class_name[] = #class_name; \ CRuntimeClass class_name::class##class_name = { \ _lpsz##class_name, sizeof(class_name), wSchema, pfnNew, \ RUNTIME_CLASS(base_class_name), NULL }; \ static AFX_CLASSINIT _init_##class_name(&class_name::class##class_name); \ CRuntimeClass* class_name::GetRuntimeClass() const \ { return &class_name::class##class_name; } \ #define IMPLEMENT_DYNAMIC(class_name, base_class_name) \ _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, 0xFFFF, NULL) // 动态创建 #define DECLARE_DYNCREATE(class_name) \ DECLARE_DYNAMIC(class_name) \ static CObject* CreateObject(); #define IMPLEMENT_DYNCREATE(class_name, base_class_name) \ CObject* class_name::CreateObject() \ { return new class_name; } \ _IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, 0xFFFF, \ class_name::CreateObject) // CObject, 表头, 需要特殊构造, 不能直接套用宏 class CObject { public: // 定义成虚函数是因为派生类会改写 virtual CRuntimeClass *GetRuntimeClass() const; bool IsKindOf(const CRuntimeClass *pClass) const; virtual void SayHello() { std::cout << "Hello Object\n"; } public: static CRuntimeClass classCObject; }; // 判断派生类是否是pClass bool CObject::IsKindOf(const CRuntimeClass *pClass) const { // 获取自身的CRuntimeClass, 如 classWinThread // GetRuntimeClass是虚函数, 派生类会改写 CRuntimeClass *pClassThis = GetRuntimeClass(); while (pClassThis != NULL) { if (pClassThis == pClass) { return true; } // 找基类 pClassThis = pClassThis->m_pBaseClass; } return false; } // 以全局变量的方式定义RTTI static char szCObject[] = "CObject"; struct CRuntimeClass CObject::classCObject = { szCObject, sizeof(CObject), 0xFFFF, NULL, NULL }; static AFX_CLASSINIT _init_CObject(&CObject::classCObject); // CObject成员函数 CRuntimeClass *CObject::GetRuntimeClass() const { return &CObject::classCObject; } // CObject 表头构造结束 CObject* CRuntimeClass::CreateObject() { if (m_pfnCreateObject == NULL) { printf("Error: Trying to create object which is not " "DECLARE_DYNCREATE \nor DECLARE_SERIAL: %hs.\n", m_lpszClassName); return NULL; } CObject* pObject = NULL; // 调用具体类的创建函数 pObject = (*m_pfnCreateObject)(); return pObject; } // 模拟用的, 从命令行创建类 CRuntimeClass* CRuntimeClass::Load() { char szClassName[64]; CRuntimeClass* pClass; // JJHOU : instead of Load from file, we Load from cin. std::cout << "enter a class name... "; std::cin >> szClassName; for (pClass = pFirstClass; pClass != NULL; pClass = pClass->m_pNextClass) { if (strcmp(szClassName, pClass->m_lpszClassName) == 0) return pClass; } printf("Error: Class not found: %s \n", szClassName); return NULL; // not found } // CCmdTarget class CCmdTarget : public CObject { DECLARE_DYNAMIC(CCmdTarget) }; // CWinThread class CWinThread: public CCmdTarget { DECLARE_DYNAMIC(CWinThread) }; // CWind class CWnd: public CCmdTarget { DECLARE_DYNCREATE(CWnd) public: void SayHello() { std::cout << "Hello CWnd \n"; } }; IMPLEMENT_DYNAMIC(CCmdTarget, CObject) IMPLEMENT_DYNAMIC(CWinThread, CCmdTarget) IMPLEMENT_DYNCREATE(CWnd, CCmdTarget) void PrintAllClasses() { CRuntimeClass *pClass; for (pClass = CRuntimeClass::pFirstClass; pClass != NULL; pClass = pClass->m_pNextClass) { std::cout << pClass->m_lpszClassName << "\n"; std::cout << pClass->m_nObjectSize << "\n"; std::cout << pClass->m_wSchema << "\n"; } } int main() { PrintAllClasses(); // 演示运行时类型识别 CWinThread o; bool ok = o.IsKindOf(RUNTIME_CLASS(CCmdTarget)); if (ok) { std::cout << "CWinThread is s CCmdTarget" << "\n"; } // 演示动态创建, 请在命令行输入"CWnd" CRuntimeClass *pClassRef; CObject *pOb; while(1) { if ((pClassRef = CRuntimeClass::Load()) == NULL) { break; } pOb = pClassRef->CreateObject(); if (pOb != NULL) { pOb->SayHello(); } } return 0; } <|endoftext|>
<commit_before>#include "../../include/kit/net/net.h" #include "../../include/kit/log/log.h" #include <iostream> #include <memory> #include <boost/lexical_cast.hpp> using namespace std; int main(int argc, char** argv) { unsigned short port = 1337; try{ if(argc > 1) port = boost::lexical_cast<short>(argv[1]); }catch(...){} auto server = make_shared<TCPSocket>(); server->open(); server->bind(port); server->listen(); int num_clients = 0; auto fut = MX[0].coro<void>([&num_clients, server]{ for(;;) { LOG("awaiting connection"); auto client = make_shared<TCPSocket>(AWAIT(server->accept())); MX[0].coro<void>([&num_clients, client]{ int client_id = num_clients; LOGf("client %s connected", client_id); ++num_clients; try{ string msg; for(;;) { msg = AWAIT(client->recv()); cout << msg << endl; client->send(msg); } }catch(const socket_exception& e){ LOGf("client %s disconnected (%s)", client_id % e.what()); } --num_clients; }); } }); fut.get(); return 0; } <commit_msg>echo server removed local echo for testing<commit_after>#include "../../include/kit/net/net.h" #include "../../include/kit/log/log.h" #include <iostream> #include <memory> #include <boost/lexical_cast.hpp> using namespace std; int main(int argc, char** argv) { unsigned short port = 1337; try{ if(argc > 1) port = boost::lexical_cast<short>(argv[1]); }catch(...){} auto server = make_shared<TCPSocket>(); server->open(); server->bind(port); server->listen(); int num_clients = 0; auto fut = MX[0].coro<void>([&num_clients, server]{ for(;;) { LOG("awaiting connection"); auto client = make_shared<TCPSocket>(AWAIT(server->accept())); MX[0].coro<void>([&num_clients, client]{ int client_id = num_clients; LOGf("client %s connected", client_id); ++num_clients; try{ for(;;) client->send(AWAIT(client->recv())); }catch(const socket_exception& e){ LOGf("client %s disconnected (%s)", client_id % e.what()); } --num_clients; }); } }); fut.get(); return 0; } <|endoftext|>
<commit_before> /* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <[email protected]> * @date 2014 * Tests for the Solidity optimizer. */ #include <string> #include <tuple> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <test/solidityExecutionFramework.h> using namespace std; namespace dev { namespace solidity { namespace test { class OptimizerTestFramework: public ExecutionFramework { public: OptimizerTestFramework() { } /// Compiles the source code with and without optimizing. void compileBothVersions(unsigned _expectedSizeDecrease, std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") { m_optimize = false; bytes nonOptimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); m_nonOptimizedContract = m_contractAddress; m_optimize = true; bytes optimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); int sizeDiff = nonOptimizedBytecode.size() - optimizedBytecode.size(); BOOST_CHECK_MESSAGE(sizeDiff == int(_expectedSizeDecrease), "Bytecode shrank by " + boost::lexical_cast<string>(sizeDiff) + " bytes, expected: " + boost::lexical_cast<string>(_expectedSizeDecrease)); m_optimizedContract = m_contractAddress; } template <class... Args> void compareVersions(std::string _sig, Args const&... _arguments) { m_contractAddress = m_nonOptimizedContract; bytes nonOptimizedOutput = callContractFunction(_sig, _arguments...); m_contractAddress = m_optimizedContract; bytes optimizedOutput = callContractFunction(_sig, _arguments...); BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match." "\nNon-Optimized: " + toHex(nonOptimizedOutput) + "\nOptimized: " + toHex(optimizedOutput)); } protected: Address m_optimizedContract; Address m_nonOptimizedContract; }; BOOST_FIXTURE_TEST_SUITE(SolidityOptimizer, OptimizerTestFramework) BOOST_AUTO_TEST_CASE(smoke_test) { char const* sourceCode = R"( contract test { function f(uint a) returns (uint b) { return a; } })"; compileBothVersions(29, sourceCode); compareVersions("f(uint256)", u256(7)); } BOOST_AUTO_TEST_CASE(large_integers) { char const* sourceCode = R"( contract test { function f() returns (uint a, uint b) { a = 0x234234872642837426347000000; b = 0x10000000000000000000000002; } })"; compileBothVersions(53, sourceCode); compareVersions("f()"); } BOOST_AUTO_TEST_CASE(invariants) { char const* sourceCode = R"( contract test { function f(int a) returns (int b) { return int(0) | (int(1) * (int(0) ^ (0 + a))); } })"; compileBothVersions(53, sourceCode); compareVersions("f(uint256)", u256(0x12334664)); } BOOST_AUTO_TEST_CASE(unused_expressions) { char const* sourceCode = R"( contract test { uint data; function f() returns (uint a, uint b) { 10 + 20; data; } })"; compileBothVersions(36, sourceCode); compareVersions("f()"); } BOOST_AUTO_TEST_CASE(constant_folding_both_sides) { // if constants involving the same associative and commutative operator are applied from both // sides, the operator should be applied only once, because the expression compiler pushes // literals as late as possible char const* sourceCode = R"( contract test { function f(uint x) returns (uint y) { return 98 ^ (7 * ((1 | (x | 1000)) * 40) ^ 102); } })"; compileBothVersions(56, sourceCode); compareVersions("f(uint256)"); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>adjusting byte difference in optimizer large integers test<commit_after> /* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <[email protected]> * @date 2014 * Tests for the Solidity optimizer. */ #include <string> #include <tuple> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <test/solidityExecutionFramework.h> using namespace std; namespace dev { namespace solidity { namespace test { class OptimizerTestFramework: public ExecutionFramework { public: OptimizerTestFramework() { } /// Compiles the source code with and without optimizing. void compileBothVersions(unsigned _expectedSizeDecrease, std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") { m_optimize = false; bytes nonOptimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); m_nonOptimizedContract = m_contractAddress; m_optimize = true; bytes optimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); int sizeDiff = nonOptimizedBytecode.size() - optimizedBytecode.size(); BOOST_CHECK_MESSAGE(sizeDiff == int(_expectedSizeDecrease), "Bytecode shrank by " + boost::lexical_cast<string>(sizeDiff) + " bytes, expected: " + boost::lexical_cast<string>(_expectedSizeDecrease)); m_optimizedContract = m_contractAddress; } template <class... Args> void compareVersions(std::string _sig, Args const&... _arguments) { m_contractAddress = m_nonOptimizedContract; bytes nonOptimizedOutput = callContractFunction(_sig, _arguments...); m_contractAddress = m_optimizedContract; bytes optimizedOutput = callContractFunction(_sig, _arguments...); BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match." "\nNon-Optimized: " + toHex(nonOptimizedOutput) + "\nOptimized: " + toHex(optimizedOutput)); } protected: Address m_optimizedContract; Address m_nonOptimizedContract; }; BOOST_FIXTURE_TEST_SUITE(SolidityOptimizer, OptimizerTestFramework) BOOST_AUTO_TEST_CASE(smoke_test) { char const* sourceCode = R"( contract test { function f(uint a) returns (uint b) { return a; } })"; compileBothVersions(29, sourceCode); compareVersions("f(uint256)", u256(7)); } BOOST_AUTO_TEST_CASE(large_integers) { char const* sourceCode = R"( contract test { function f() returns (uint a, uint b) { a = 0x234234872642837426347000000; b = 0x10000000000000000000000002; } })"; compileBothVersions(58, sourceCode); compareVersions("f()"); } BOOST_AUTO_TEST_CASE(invariants) { char const* sourceCode = R"( contract test { function f(int a) returns (int b) { return int(0) | (int(1) * (int(0) ^ (0 + a))); } })"; compileBothVersions(53, sourceCode); compareVersions("f(uint256)", u256(0x12334664)); } BOOST_AUTO_TEST_CASE(unused_expressions) { char const* sourceCode = R"( contract test { uint data; function f() returns (uint a, uint b) { 10 + 20; data; } })"; compileBothVersions(36, sourceCode); compareVersions("f()"); } BOOST_AUTO_TEST_CASE(constant_folding_both_sides) { // if constants involving the same associative and commutative operator are applied from both // sides, the operator should be applied only once, because the expression compiler pushes // literals as late as possible char const* sourceCode = R"( contract test { function f(uint x) returns (uint y) { return 98 ^ (7 * ((1 | (x | 1000)) * 40) ^ 102); } })"; compileBothVersions(56, sourceCode); compareVersions("f(uint256)"); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "distributorcomponent.h" #include <vespa/storage/common/bucketoperationlogger.h> #include <vespa/storageapi/messageapi/storagereply.h> #include <vespa/vdslib/distribution/distribution.h> #include "distributor_bucket_space_repo.h" #include "distributor_bucket_space.h" #include <vespa/log/log.h> LOG_SETUP(".distributorstoragelink"); using document::BucketSpace; namespace storage { namespace distributor { DistributorComponent::DistributorComponent( DistributorInterface& distributor, DistributorBucketSpaceRepo &bucketSpaceRepo, DistributorComponentRegister& compReg, const std::string& name) : storage::DistributorComponent(compReg, name), _distributor(distributor), _bucketSpaceRepo(bucketSpaceRepo) { } DistributorComponent::~DistributorComponent() {} void DistributorComponent::sendDown(const api::StorageMessage::SP& msg) { _distributor.getMessageSender().sendDown(msg); } void DistributorComponent::sendUp(const api::StorageMessage::SP& msg) { _distributor.getMessageSender().sendUp(msg); } const lib::ClusterState& DistributorComponent::getClusterState() const { return _distributor.getClusterState(); }; std::vector<uint16_t> DistributorComponent::getIdealNodes(const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return bucketSpace.getDistribution().getIdealStorageNodes( getClusterState(), bucket.getBucketId(), _distributor.getStorageNodeUpStates()); } BucketOwnership DistributorComponent::checkOwnershipInPendingAndGivenState( const lib::Distribution& distribution, const lib::ClusterState& clusterState, const document::Bucket &bucket) const { try { BucketOwnership pendingRes( _distributor.checkOwnershipInPendingState(bucket)); if (!pendingRes.isOwned()) { return pendingRes; } uint16_t distributor = distribution.getIdealDistributorNode( clusterState, bucket.getBucketId()); if (getIndex() == distributor) { return BucketOwnership::createOwned(); } else { return BucketOwnership::createNotOwnedInState(clusterState); } } catch (lib::TooFewBucketBitsInUseException& e) { return BucketOwnership::createNotOwnedInState(clusterState); } catch (lib::NoDistributorsAvailableException& e) { return BucketOwnership::createNotOwnedInState(clusterState); } } BucketOwnership DistributorComponent::checkOwnershipInPendingAndCurrentState( const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return checkOwnershipInPendingAndGivenState( bucketSpace.getDistribution(), getClusterState(), bucket); } bool DistributorComponent::ownsBucketInState( const lib::Distribution& distribution, const lib::ClusterState& clusterState, const document::Bucket &bucket) const { LOG(spam, "checking bucket %s in state %s with distr %s", bucket.toString().c_str(), clusterState.toString().c_str(), distribution.getNodeGraph().getDistributionConfigHash().c_str()); try { uint16_t distributor = distribution.getIdealDistributorNode( clusterState, bucket.getBucketId()); return (getIndex() == distributor); } catch (lib::TooFewBucketBitsInUseException& e) { return false; } catch (lib::NoDistributorsAvailableException& e) { return false; } } bool DistributorComponent::ownsBucketInState( const lib::ClusterState& clusterState, const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return ownsBucketInState(bucketSpace.getDistribution(), clusterState, bucket); } bool DistributorComponent::ownsBucketInCurrentState(const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return ownsBucketInState(bucketSpace.getDistribution(), getClusterState(), bucket); } api::StorageMessageAddress DistributorComponent::nodeAddress(uint16_t nodeIndex) const { return api::StorageMessageAddress( getClusterName(), lib::NodeType::STORAGE, nodeIndex); } bool DistributorComponent::checkDistribution( api::StorageCommand &cmd, const document::Bucket &bucket) { BucketOwnership bo(checkOwnershipInPendingAndCurrentState(bucket)); if (!bo.isOwned()) { std::string systemStateStr = bo.getNonOwnedState().toString(); LOG(debug, "Got message with wrong distribution, " "bucket %s sending back state '%s'", bucket.toString().c_str(), systemStateStr.c_str()); api::StorageReply::UP reply(cmd.makeReply()); api::ReturnCode ret( api::ReturnCode::WRONG_DISTRIBUTION, systemStateStr); reply->setResult(ret); sendUp(std::shared_ptr<api::StorageMessage>(reply.release())); return false; } return true; } void DistributorComponent::removeNodesFromDB(const document::Bucket &bucket, const std::vector<uint16_t>& nodes) { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); BucketDatabase::Entry dbentry = bucketSpace.getBucketDatabase().get(bucket.getBucketId()); if (dbentry.valid()) { for (uint32_t i = 0; i < nodes.size(); ++i) { if (dbentry->removeNode(nodes[i])) { LOG(debug, "Removed node %d from bucket %s. %u copies remaining", nodes[i], bucket.toString().c_str(), dbentry->getNodeCount()); } } if (dbentry->getNodeCount() != 0) { bucketSpace.getBucketDatabase().update(dbentry); } else { LOG(debug, "After update, bucket %s now has no copies. " "Removing from database.", bucket.toString().c_str()); bucketSpace.getBucketDatabase().remove(bucket.getBucketId()); } } } std::vector<uint16_t> DistributorComponent::enumerateDownNodes( const lib::ClusterState& s, const document::Bucket &bucket, const std::vector<BucketCopy>& candidates) const { std::vector<uint16_t> downNodes; for (uint32_t i = 0; i < candidates.size(); ++i) { const BucketCopy& copy(candidates[i]); const lib::NodeState& ns( s.getNodeState(lib::Node(lib::NodeType::STORAGE, copy.getNode()))); if (ns.getState() == lib::State::DOWN) { LOG(debug, "Trying to add a bucket copy to %s whose node is marked as " "down in the cluster state: %s. Ignoring it since no zombies " "are allowed!", bucket.toString().c_str(), copy.toString().c_str()); downNodes.push_back(copy.getNode()); } } return downNodes; } void DistributorComponent::updateBucketDatabase( const document::Bucket &bucket, const std::vector<BucketCopy>& changedNodes, uint32_t updateFlags) { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); assert(!(bucket.getBucketId() == document::BucketId())); BucketDatabase::Entry dbentry = bucketSpace.getBucketDatabase().get(bucket.getBucketId()); BucketOwnership ownership(checkOwnershipInPendingAndCurrentState(bucket)); if (!ownership.isOwned()) { LOG(debug, "Trying to add %s to database that we do not own according to " "cluster state '%s' - ignoring!", bucket.toString().c_str(), ownership.getNonOwnedState().toString().c_str()); LOG_BUCKET_OPERATION_NO_LOCK(bucketId, "Ignoring database insert since " "we do not own the bucket"); return; } if (!dbentry.valid()) { if (updateFlags & DatabaseUpdate::CREATE_IF_NONEXISTING) { dbentry = BucketDatabase::Entry(bucket.getBucketId(), BucketInfo()); } else { return; } } // 0 implies bucket was just added. Since we don't know if any other // distributor has run GC on it, we just have to assume this and set the // timestamp to the current time to avoid duplicate work. if (dbentry->getLastGarbageCollectionTime() == 0) { dbentry->setLastGarbageCollectionTime( getClock().getTimeInSeconds().getTime()); } // Ensure that we're not trying to bring any zombie copies into the // bucket database (i.e. copies on nodes that are actually down). std::vector<uint16_t> downNodes( enumerateDownNodes(getClusterState(), bucket, changedNodes)); // Optimize for common case where we don't have to create a new // bucket copy vector if (downNodes.empty()) { dbentry->addNodes(changedNodes, getIdealNodes(bucket)); } else { std::vector<BucketCopy> upNodes; for (uint32_t i = 0; i < changedNodes.size(); ++i) { const BucketCopy& copy(changedNodes[i]); if (std::find(downNodes.begin(), downNodes.end(), copy.getNode()) == downNodes.end()) { upNodes.push_back(copy); } } dbentry->addNodes(upNodes, getIdealNodes(bucket)); } if (updateFlags & DatabaseUpdate::RESET_TRUSTED) { dbentry->resetTrusted(); } bucketSpace.getBucketDatabase().update(dbentry); } void DistributorComponent::recheckBucketInfo(uint16_t nodeIdx, const document::Bucket &bucket) { _distributor.recheckBucketInfo(nodeIdx, bucket); } document::BucketId DistributorComponent::getBucketId(const document::DocumentId& docId) const { document::BucketId id(getBucketIdFactory().getBucketId(docId)); id.setUsedBits(_distributor.getConfig().getMinimalBucketSplit()); return id.stripUnused(); } bool DistributorComponent::storageNodeIsUp(uint32_t nodeIndex) const { const lib::NodeState& ns = getClusterState().getNodeState( lib::Node(lib::NodeType::STORAGE, nodeIndex)); return ns.getState().oneOf(_distributor.getStorageNodeUpStates()); } document::BucketId DistributorComponent::getSibling(const document::BucketId& bid) const { document::BucketId zeroBucket; document::BucketId oneBucket; if (bid.getUsedBits() == 1) { zeroBucket = document::BucketId(1, 0); oneBucket = document::BucketId(1, 1); } else { document::BucketId joinedBucket = document::BucketId( bid.getUsedBits() - 1, bid.getId()); zeroBucket = document::BucketId( bid.getUsedBits(), joinedBucket.getId()); uint64_t hiBit = 1; hiBit <<= (bid.getUsedBits() - 1); oneBucket = document::BucketId( bid.getUsedBits(), joinedBucket.getId() | hiBit); } return (zeroBucket == bid) ? oneBucket : zeroBucket; }; BucketDatabase::Entry DistributorComponent::createAppropriateBucket(const document::Bucket &bucket) { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return bucketSpace.getBucketDatabase().createAppropriateBucket( _distributor.getConfig().getMinimalBucketSplit(), bucket.getBucketId()); } bool DistributorComponent::initializing() const { return _distributor.initializing(); } } } <commit_msg>guard against empty set of nodes<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "distributorcomponent.h" #include <vespa/storage/common/bucketoperationlogger.h> #include <vespa/storageapi/messageapi/storagereply.h> #include <vespa/vdslib/distribution/distribution.h> #include "distributor_bucket_space_repo.h" #include "distributor_bucket_space.h" #include <vespa/log/log.h> LOG_SETUP(".distributorstoragelink"); using document::BucketSpace; namespace storage { namespace distributor { DistributorComponent::DistributorComponent( DistributorInterface& distributor, DistributorBucketSpaceRepo &bucketSpaceRepo, DistributorComponentRegister& compReg, const std::string& name) : storage::DistributorComponent(compReg, name), _distributor(distributor), _bucketSpaceRepo(bucketSpaceRepo) { } DistributorComponent::~DistributorComponent() {} void DistributorComponent::sendDown(const api::StorageMessage::SP& msg) { _distributor.getMessageSender().sendDown(msg); } void DistributorComponent::sendUp(const api::StorageMessage::SP& msg) { _distributor.getMessageSender().sendUp(msg); } const lib::ClusterState& DistributorComponent::getClusterState() const { return _distributor.getClusterState(); }; std::vector<uint16_t> DistributorComponent::getIdealNodes(const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return bucketSpace.getDistribution().getIdealStorageNodes( getClusterState(), bucket.getBucketId(), _distributor.getStorageNodeUpStates()); } BucketOwnership DistributorComponent::checkOwnershipInPendingAndGivenState( const lib::Distribution& distribution, const lib::ClusterState& clusterState, const document::Bucket &bucket) const { try { BucketOwnership pendingRes( _distributor.checkOwnershipInPendingState(bucket)); if (!pendingRes.isOwned()) { return pendingRes; } uint16_t distributor = distribution.getIdealDistributorNode( clusterState, bucket.getBucketId()); if (getIndex() == distributor) { return BucketOwnership::createOwned(); } else { return BucketOwnership::createNotOwnedInState(clusterState); } } catch (lib::TooFewBucketBitsInUseException& e) { return BucketOwnership::createNotOwnedInState(clusterState); } catch (lib::NoDistributorsAvailableException& e) { return BucketOwnership::createNotOwnedInState(clusterState); } } BucketOwnership DistributorComponent::checkOwnershipInPendingAndCurrentState( const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return checkOwnershipInPendingAndGivenState( bucketSpace.getDistribution(), getClusterState(), bucket); } bool DistributorComponent::ownsBucketInState( const lib::Distribution& distribution, const lib::ClusterState& clusterState, const document::Bucket &bucket) const { LOG(spam, "checking bucket %s in state %s with distr %s", bucket.toString().c_str(), clusterState.toString().c_str(), distribution.getNodeGraph().getDistributionConfigHash().c_str()); try { uint16_t distributor = distribution.getIdealDistributorNode( clusterState, bucket.getBucketId()); return (getIndex() == distributor); } catch (lib::TooFewBucketBitsInUseException& e) { return false; } catch (lib::NoDistributorsAvailableException& e) { return false; } } bool DistributorComponent::ownsBucketInState( const lib::ClusterState& clusterState, const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return ownsBucketInState(bucketSpace.getDistribution(), clusterState, bucket); } bool DistributorComponent::ownsBucketInCurrentState(const document::Bucket &bucket) const { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return ownsBucketInState(bucketSpace.getDistribution(), getClusterState(), bucket); } api::StorageMessageAddress DistributorComponent::nodeAddress(uint16_t nodeIndex) const { return api::StorageMessageAddress( getClusterName(), lib::NodeType::STORAGE, nodeIndex); } bool DistributorComponent::checkDistribution( api::StorageCommand &cmd, const document::Bucket &bucket) { BucketOwnership bo(checkOwnershipInPendingAndCurrentState(bucket)); if (!bo.isOwned()) { std::string systemStateStr = bo.getNonOwnedState().toString(); LOG(debug, "Got message with wrong distribution, " "bucket %s sending back state '%s'", bucket.toString().c_str(), systemStateStr.c_str()); api::StorageReply::UP reply(cmd.makeReply()); api::ReturnCode ret( api::ReturnCode::WRONG_DISTRIBUTION, systemStateStr); reply->setResult(ret); sendUp(std::shared_ptr<api::StorageMessage>(reply.release())); return false; } return true; } void DistributorComponent::removeNodesFromDB(const document::Bucket &bucket, const std::vector<uint16_t>& nodes) { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); BucketDatabase::Entry dbentry = bucketSpace.getBucketDatabase().get(bucket.getBucketId()); if (dbentry.valid()) { for (uint32_t i = 0; i < nodes.size(); ++i) { if (dbentry->removeNode(nodes[i])) { LOG(debug, "Removed node %d from bucket %s. %u copies remaining", nodes[i], bucket.toString().c_str(), dbentry->getNodeCount()); } } if (dbentry->getNodeCount() != 0) { bucketSpace.getBucketDatabase().update(dbentry); } else { LOG(debug, "After update, bucket %s now has no copies. " "Removing from database.", bucket.toString().c_str()); bucketSpace.getBucketDatabase().remove(bucket.getBucketId()); } } } std::vector<uint16_t> DistributorComponent::enumerateDownNodes( const lib::ClusterState& s, const document::Bucket &bucket, const std::vector<BucketCopy>& candidates) const { std::vector<uint16_t> downNodes; for (uint32_t i = 0; i < candidates.size(); ++i) { const BucketCopy& copy(candidates[i]); const lib::NodeState& ns( s.getNodeState(lib::Node(lib::NodeType::STORAGE, copy.getNode()))); if (ns.getState() == lib::State::DOWN) { LOG(debug, "Trying to add a bucket copy to %s whose node is marked as " "down in the cluster state: %s. Ignoring it since no zombies " "are allowed!", bucket.toString().c_str(), copy.toString().c_str()); downNodes.push_back(copy.getNode()); } } return downNodes; } void DistributorComponent::updateBucketDatabase( const document::Bucket &bucket, const std::vector<BucketCopy>& changedNodes, uint32_t updateFlags) { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); assert(!(bucket.getBucketId() == document::BucketId())); BucketDatabase::Entry dbentry = bucketSpace.getBucketDatabase().get(bucket.getBucketId()); BucketOwnership ownership(checkOwnershipInPendingAndCurrentState(bucket)); if (!ownership.isOwned()) { LOG(debug, "Trying to add %s to database that we do not own according to " "cluster state '%s' - ignoring!", bucket.toString().c_str(), ownership.getNonOwnedState().toString().c_str()); LOG_BUCKET_OPERATION_NO_LOCK(bucketId, "Ignoring database insert since " "we do not own the bucket"); return; } if (!dbentry.valid()) { if (updateFlags & DatabaseUpdate::CREATE_IF_NONEXISTING) { dbentry = BucketDatabase::Entry(bucket.getBucketId(), BucketInfo()); } else { return; } } // 0 implies bucket was just added. Since we don't know if any other // distributor has run GC on it, we just have to assume this and set the // timestamp to the current time to avoid duplicate work. if (dbentry->getLastGarbageCollectionTime() == 0) { dbentry->setLastGarbageCollectionTime( getClock().getTimeInSeconds().getTime()); } // Ensure that we're not trying to bring any zombie copies into the // bucket database (i.e. copies on nodes that are actually down). std::vector<uint16_t> downNodes( enumerateDownNodes(getClusterState(), bucket, changedNodes)); // Optimize for common case where we don't have to create a new // bucket copy vector if (downNodes.empty()) { dbentry->addNodes(changedNodes, getIdealNodes(bucket)); } else { std::vector<BucketCopy> upNodes; for (uint32_t i = 0; i < changedNodes.size(); ++i) { const BucketCopy& copy(changedNodes[i]); if (std::find(downNodes.begin(), downNodes.end(), copy.getNode()) == downNodes.end()) { upNodes.push_back(copy); } } dbentry->addNodes(upNodes, getIdealNodes(bucket)); } if (updateFlags & DatabaseUpdate::RESET_TRUSTED) { dbentry->resetTrusted(); } if (dbentry->getNodeCount() == 0) { LOG(warning, "all nodes in changedNodes set (size %zu) are down, removing dbentry", changedNodes.size()); bucketSpace.getBucketDatabase().remove(bucket.getBucketId()); return; } bucketSpace.getBucketDatabase().update(dbentry); } void DistributorComponent::recheckBucketInfo(uint16_t nodeIdx, const document::Bucket &bucket) { _distributor.recheckBucketInfo(nodeIdx, bucket); } document::BucketId DistributorComponent::getBucketId(const document::DocumentId& docId) const { document::BucketId id(getBucketIdFactory().getBucketId(docId)); id.setUsedBits(_distributor.getConfig().getMinimalBucketSplit()); return id.stripUnused(); } bool DistributorComponent::storageNodeIsUp(uint32_t nodeIndex) const { const lib::NodeState& ns = getClusterState().getNodeState( lib::Node(lib::NodeType::STORAGE, nodeIndex)); return ns.getState().oneOf(_distributor.getStorageNodeUpStates()); } document::BucketId DistributorComponent::getSibling(const document::BucketId& bid) const { document::BucketId zeroBucket; document::BucketId oneBucket; if (bid.getUsedBits() == 1) { zeroBucket = document::BucketId(1, 0); oneBucket = document::BucketId(1, 1); } else { document::BucketId joinedBucket = document::BucketId( bid.getUsedBits() - 1, bid.getId()); zeroBucket = document::BucketId( bid.getUsedBits(), joinedBucket.getId()); uint64_t hiBit = 1; hiBit <<= (bid.getUsedBits() - 1); oneBucket = document::BucketId( bid.getUsedBits(), joinedBucket.getId() | hiBit); } return (zeroBucket == bid) ? oneBucket : zeroBucket; }; BucketDatabase::Entry DistributorComponent::createAppropriateBucket(const document::Bucket &bucket) { auto &bucketSpace(_bucketSpaceRepo.get(bucket.getBucketSpace())); return bucketSpace.getBucketDatabase().createAppropriateBucket( _distributor.getConfig().getMinimalBucketSplit(), bucket.getBucketId()); } bool DistributorComponent::initializing() const { return _distributor.initializing(); } } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "stdio.h" #include "FlyCapture2.h" #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <future> #include <chrono> #include <ctime> #include <thread> using namespace FlyCapture2; using namespace std; void PrintError( Error error ) { error.PrintErrorTrace(); } int get_current_time() { chrono::milliseconds ms = chrono::duration_cast<chrono::milliseconds>( chrono::system_clock::now().time_since_epoch()); return ms.count(); } int main(int argc, char* argv[]) { const Mode k_fmt7Mode = MODE_7; const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW16; const vector<int> SHUTTER_SPEEDS { 10,20,50,100,200,500 }; BusManager busMgr; unsigned int numCameras; Camera cam; Error error; PGRGuid guid; // TEST FILE WRITE ACCESS cout << "Testing file access..." << endl; FILE* tempFile = fopen("test.txt", "w+"); if (tempFile == NULL) { cout << "Failed to create file in current folder. Please check permissions." << endl; return -1; } fclose(tempFile); remove("test.txt"); // TEST CAMERA DETECTION cout << "Testing camera detection..." << endl; error = busMgr.GetNumOfCameras(&numCameras); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // GET CAMERA FROM INDEX cout << "Fetching camera from port index" << endl; error = busMgr.GetCameraFromIndex(0, &guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CONNECT cout << "Connecting to camera..." << endl; error = cam.Connect(&guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // GET CAMERA INFORMATION cout << "Fetching camera information..." << endl; CameraInfo camInfo; error = cam.GetCameraInfo(&camInfo); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CREATE FORMAT7 SETTINGS cout << "Creating fmt7 settings..." << endl; Format7ImageSettings fmt7ImageSettings; bool valid; Format7PacketInfo fmt7PacketInfo; fmt7ImageSettings.mode = k_fmt7Mode; fmt7ImageSettings.offsetX = 0; fmt7ImageSettings.offsetY = 0; fmt7ImageSettings.width = 1920; fmt7ImageSettings.height = 1200; fmt7ImageSettings.pixelFormat = k_fmt7PixFmt; // VALIDATE FORMAT7 SETTINGS cout << "Validating fmt7 settings..." << endl; error = cam.ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } if ( !valid ){ // Settings are not valid cout << "Format7 settings are not valid" << endl; return -1; } // SET FORMAT7 SETTINGS cout << "Writing fmt7 settings..." << endl; error = cam.SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SEQUENCE cout << "Starting image sequence..." << endl; unsigned int imageCount = 0; for(auto const& shutter_speed: SHUTTER_SPEEDS) { cout << "Writing image " << imageCount << " ..." << endl; imageCount++; // CREATE SHUTTER PROPERTY Property prop; prop.type = SHUTTER; prop.onOff = true; prop.autoManualMode = false; prop.absControl = true; prop.absValue = shutter_speed; // WRITE SHUTTE PROPERTY error = cam.SetProperty(&prop); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // START CAPTURE error = cam.StartCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // RETRIEVE IMAGE BUFFER Image rawImage; error = cam.RetrieveBuffer( &rawImage ); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // TESTING DELAY POST-WRITING PROPERTIES this_thread::sleep_for(chrono::milliseconds(1000)); // SET IMAGE DIMENSIONS PixelFormat pixFormat; unsigned int rows, cols, stride; rawImage.GetDimensions( &rows, &cols, &stride, &pixFormat ); // CONVERT IMAGE Image convertedImage; error = rawImage.Convert( PIXEL_FORMAT_BGRU, &convertedImage ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SAVE IMAGE ostringstream filename; int ms_time = get_current_time(); filename << "/home/pi/Pictures/" << "img_" << shutter_speed << "_" << ms_time << "_" << argv[1] << ".bmp"; error = convertedImage.Save( filename.str().c_str() ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // STOP CAPTURE error = cam.StopCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } } // DISCONNECT error = cam.Disconnect(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } cout << "Done." << endl; return 0; } <commit_msg>fixing merge with pi<commit_after>#include "stdafx.h" #include "stdio.h" #include "FlyCapture2.h" #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <future> #include <chrono> #include <ctime> #include <thread> using namespace FlyCapture2; using namespace std; void PrintError( Error error ) { error.PrintErrorTrace(); } int get_current_time() { chrono::milliseconds ms = chrono::duration_cast<chrono::milliseconds>( chrono::system_clock::now().time_since_epoch()); return ms.count(); } int main(int argc, char* argv[]) { const Mode k_fmt7Mode = MODE_7; const PixelFormat k_fmt7PixFmt = PIXEL_FORMAT_RAW16; const vector<int> SHUTTER_SPEEDS { 10,20,50,100,200,500 }; BusManager busMgr; unsigned int numCameras; Camera cam; Error error; PGRGuid guid; // TEST FILE WRITE ACCESS cout << "Testing file access..." << endl; FILE* tempFile = fopen("test.txt", "w+"); if (tempFile == NULL) { cout << "Failed to create file in current folder. Please check permissions." << endl; return -1; } fclose(tempFile); remove("test.txt"); // TEST CAMERA DETECTION cout << "Testing camera detection..." << endl; error = busMgr.GetNumOfCameras(&numCameras); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // GET CAMERA FROM INDEX cout << "Fetching camera from port index" << endl; error = busMgr.GetCameraFromIndex(0, &guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CONNECT cout << "Connecting to camera..." << endl; error = cam.Connect(&guid); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // GET CAMERA INFORMATION cout << "Fetching camera information..." << endl; CameraInfo camInfo; error = cam.GetCameraInfo(&camInfo); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // CREATE FORMAT7 SETTINGS cout << "Creating fmt7 settings..." << endl; Format7ImageSettings fmt7ImageSettings; bool valid; Format7PacketInfo fmt7PacketInfo; fmt7ImageSettings.mode = k_fmt7Mode; fmt7ImageSettings.offsetX = 0; fmt7ImageSettings.offsetY = 0; fmt7ImageSettings.width = 1920; fmt7ImageSettings.height = 1200; fmt7ImageSettings.pixelFormat = k_fmt7PixFmt; // VALIDATE FORMAT7 SETTINGS cout << "Validating fmt7 settings..." << endl; error = cam.ValidateFormat7Settings(&fmt7ImageSettings, &valid, &fmt7PacketInfo ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } if ( !valid ){ // Settings are not valid cout << "Format7 settings are not valid" << endl; return -1; } // SET FORMAT7 SETTINGS cout << "Writing fmt7 settings..." << endl; error = cam.SetFormat7Configuration(&fmt7ImageSettings, fmt7PacketInfo.recommendedBytesPerPacket ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SEQUENCE cout << "Starting image sequence..." << endl; unsigned int imageCount = 0; for(auto const& shutter_speed: SHUTTER_SPEEDS) { cout << "Writing image " << imageCount << " ..." << endl; imageCount++; // CREATE SHUTTER PROPERTY Property prop; prop.type = SHUTTER; prop.onOff = true; prop.autoManualMode = false; prop.absControl = true; prop.absValue = shutter_speed; // WRITE SHUTTE PROPERTY error = cam.SetProperty(&prop); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // START CAPTURE error = cam.StartCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // RETRIEVE IMAGE BUFFER Image rawImage; error = cam.RetrieveBuffer( &rawImage ); if (error != PGRERROR_OK) { PrintError( error ); return -1; } // TESTING DELAY POST-WRITING PROPERTIES this_thread::sleep_for(chrono::milliseconds(1000)); // SET IMAGE DIMENSIONS PixelFormat pixFormat; unsigned int rows, cols, stride; rawImage.GetDimensions( &rows, &cols, &stride, &pixFormat ); // CONVERT IMAGE Image convertedImage; error = rawImage.Convert( PIXEL_FORMAT_BGRU, &convertedImage ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // SAVE IMAGE ostringstream filename; int ms_time = get_current_time(); filename << "/home/pi/Pictures/img_gps_" << argv[1] << "_pi_" << ms_time << "_shutter_" << shutter_speed << ".bmp"; error = convertedImage.Save( filename.str().c_str() ); if (error != PGRERROR_OK){ PrintError( error ); return -1; } // STOP CAPTURE error = cam.StopCapture(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } } // DISCONNECT error = cam.Disconnect(); if (error != PGRERROR_OK){ PrintError( error ); return -1; } cout << "Done." << endl; return 0; } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------- */ /* The Toolkit for Building Voice Interaction Systems */ /* "MMDAgent" developed by MMDAgent Project Team */ /* http://www.mmdagent.jp/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2009-2011 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 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 MMDAgent project team 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. */ /* ----------------------------------------------------------------- */ /* headers */ #include <stdarg.h> #include "MMDAgent.h" /* LogText::initialize: initialize logger */ void LogText::initialize() { m_textRenderer = NULL; m_textWidth = 0; m_textHeight = 0; m_textX = 0.0; m_textY = 0.0; m_textZ = 0.0; m_textScale = 0.0; m_textList = NULL; m_displayList = NULL; m_length = NULL; m_updated = NULL; } /* LogText::clear: free logger */ void LogText::clear() { int i; if (m_textList) { for (i = 0; i < m_textHeight; i++) free(m_textList[i]); free(m_textList); } if (m_displayList) { for (i = 0; i < m_textHeight; i++) free(m_displayList[i]); free(m_displayList); } if (m_length) free(m_length); if (m_updated) free(m_updated); initialize(); } /* LogText::LogText: constructor */ LogText::LogText() { initialize(); } /* LogText::~LogText: destructor */ LogText::~LogText() { clear(); } /* LogText::setup: initialize and setup logger with args */ void LogText::setup(TextRenderer *text, const int *size, const float *position, float scale) { int i; if (text == NULL || size[0] <= 0 || size[1] <= 0 || scale <= 0.0) return; clear(); m_textRenderer = text; m_textWidth = size[0]; m_textHeight = size[1]; m_textX = position[0]; m_textY = position[1]; m_textZ = position[2]; m_textScale = scale; m_textList = (char **) malloc(sizeof(char *) * m_textHeight); for (i = 0; i < m_textHeight; i++) { m_textList[i] = (char *) malloc(sizeof(char) * m_textWidth); strcpy(m_textList[i], ""); } m_displayList = (unsigned int **) malloc(sizeof(unsigned int *) * m_textHeight); for (i = 0; i < m_textHeight; i++) m_displayList[i] = (unsigned int *) malloc(sizeof(unsigned int) * m_textWidth); m_length = (int *) malloc(sizeof(int) * m_textHeight); for (i = 0; i < m_textHeight; i++) m_length[i] = -1; m_updated = (bool *) malloc(sizeof(bool) * m_textHeight); for (i = 0; i < m_textHeight; i++) m_updated[i] = false; m_textLine = 0; } /* LogText::log: store log text */ void LogText::log(const char *format, ...) { char *p, *save; char buff[LOGTEXT_MAXBUFLEN]; va_list args; if (m_textList == NULL) return; va_start(args, format); vsprintf(buff, format, args); for (p = MMDAgent_strtok(buff, "\n", &save); p; p = MMDAgent_strtok(NULL, "\n", &save)) { strncpy(m_textList[m_textLine], p, m_textWidth - 1); m_textList[m_textLine][m_textWidth-1] = '\0'; m_updated[m_textLine] = true; if (++m_textLine >= m_textHeight) m_textLine = 0; } va_end(args); } /* LogText::render: render log text */ void LogText::render() { int i, j; float x, y, z, w, h; if (m_textList == NULL) return; x = m_textX; y = m_textY; z = m_textZ; w = 0.5f * (float) (m_textWidth) * 0.85f + 1.0f; h = 1.0f * (float) (m_textHeight) * 0.85f + 1.0f; glPushMatrix(); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); glScalef(m_textScale, m_textScale, m_textScale); glNormal3f(0.0f, 1.0f, 0.0f); glColor4f(LOGTEXT_BGCOLOR); glBegin(GL_QUADS); glVertex3f(x , y , z); glVertex3f(x + w, y , z); glVertex3f(x + w, y + h, z); glVertex3f(x , y + h, z); glEnd(); glTranslatef(x + 0.5f, y + h - 0.4f, z + 0.05f); for (i = 0; i < m_textHeight; i++) { glTranslatef(0.0f, -0.85f, 0.0f); j = m_textLine + i; if (j >= m_textHeight) j -= m_textHeight; if (MMDAgent_strlen(m_textList[j]) > 0) { glColor4f(LOGTEXT_COLOR); glPushMatrix(); if (m_updated[j]) { /* cache display list array */ m_length[j] = m_textRenderer->getDisplayListArrayOfString(m_textList[j], m_displayList[j], m_textWidth); m_updated[j] = false; } if (m_length[j] >= 0) m_textRenderer->renderDisplayListArrayOfString(m_displayList[j], m_length[j]); glPopMatrix(); } } glEnable(GL_LIGHTING); glEnable(GL_CULL_FACE); glPopMatrix(); } <commit_msg>Makes the log use FTGL if not in Windows<commit_after>/* ----------------------------------------------------------------- */ /* The Toolkit for Building Voice Interaction Systems */ /* "MMDAgent" developed by MMDAgent Project Team */ /* http://www.mmdagent.jp/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2009-2011 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 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 MMDAgent project team 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. */ /* ----------------------------------------------------------------- */ /* headers */ #include <stdarg.h> #include "MMDAgent.h" /* LogText::initialize: initialize logger */ void LogText::initialize() { m_textRenderer = NULL; m_textWidth = 0; m_textHeight = 0; m_textX = 0.0; m_textY = 0.0; m_textZ = 0.0; m_textScale = 0.0; m_textList = NULL; m_displayList = NULL; m_length = NULL; m_updated = NULL; } /* LogText::clear: free logger */ void LogText::clear() { int i; if (m_textList) { for (i = 0; i < m_textHeight; i++) free(m_textList[i]); free(m_textList); } if (m_displayList) { for (i = 0; i < m_textHeight; i++) free(m_displayList[i]); free(m_displayList); } if (m_length) free(m_length); if (m_updated) free(m_updated); initialize(); } /* LogText::LogText: constructor */ LogText::LogText() { initialize(); } /* LogText::~LogText: destructor */ LogText::~LogText() { clear(); } /* LogText::setup: initialize and setup logger with args */ void LogText::setup(TextRenderer *text, const int *size, const float *position, float scale) { int i; if (text == NULL || size[0] <= 0 || size[1] <= 0 || scale <= 0.0) return; clear(); m_textRenderer = text; m_textWidth = size[0]; m_textHeight = size[1]; m_textX = position[0]; m_textY = position[1]; m_textZ = position[2]; m_textScale = scale; m_textList = (char **) malloc(sizeof(char *) * m_textHeight); for (i = 0; i < m_textHeight; i++) { m_textList[i] = (char *) malloc(sizeof(char) * m_textWidth); strcpy(m_textList[i], ""); } m_displayList = (unsigned int **) malloc(sizeof(unsigned int *) * m_textHeight); for (i = 0; i < m_textHeight; i++) m_displayList[i] = (unsigned int *) malloc(sizeof(unsigned int) * m_textWidth); m_length = (int *) malloc(sizeof(int) * m_textHeight); for (i = 0; i < m_textHeight; i++) m_length[i] = -1; m_updated = (bool *) malloc(sizeof(bool) * m_textHeight); for (i = 0; i < m_textHeight; i++) m_updated[i] = false; m_textLine = 0; } /* LogText::log: store log text */ void LogText::log(const char *format, ...) { char *p, *save; char buff[LOGTEXT_MAXBUFLEN]; va_list args; if (m_textList == NULL) return; va_start(args, format); vsprintf(buff, format, args); for (p = MMDAgent_strtok(buff, "\n", &save); p; p = MMDAgent_strtok(NULL, "\n", &save)) { strncpy(m_textList[m_textLine], p, m_textWidth - 1); m_textList[m_textLine][m_textWidth-1] = '\0'; m_updated[m_textLine] = true; if (++m_textLine >= m_textHeight) m_textLine = 0; } va_end(args); } /* LogText::render: render log text */ void LogText::render() { int i, j; float x, y, z, w, h; if (m_textList == NULL) return; x = m_textX; y = m_textY; z = m_textZ; w = 0.5f * (float) (m_textWidth) * 0.85f + 1.0f; h = 1.0f * (float) (m_textHeight) * 0.85f + 1.0f; glPushMatrix(); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); glScalef(m_textScale, m_textScale, m_textScale); glNormal3f(0.0f, 1.0f, 0.0f); glColor4f(LOGTEXT_BGCOLOR); glBegin(GL_QUADS); glVertex3f(x , y , z); glVertex3f(x + w, y , z); glVertex3f(x + w, y + h, z); glVertex3f(x , y + h, z); glEnd(); glTranslatef(x + 0.5f, y + h - 0.4f, z + 0.05f); for (i = 0; i < m_textHeight; i++) { glTranslatef(0.0f, -0.85f, 0.0f); j = m_textLine + i; if (j >= m_textHeight) j -= m_textHeight; if (MMDAgent_strlen(m_textList[j]) > 0) { glColor4f(LOGTEXT_COLOR); glPushMatrix(); #ifdef _WIN32 if (m_updated[j]) { /* cache display list array */ m_length[j] = m_textRenderer->getDisplayListArrayOfString(m_textList[j], m_displayList[j], m_textWidth); m_updated[j] = false; } if (m_length[j] >= 0) m_textRenderer->renderDisplayListArrayOfString(m_displayList[j], m_length[j]); #else m_textRenderer->drawString(m_textList[j]); #endif /* _WIN32 */ glPopMatrix(); } } glEnable(GL_LIGHTING); glEnable(GL_CULL_FACE); glPopMatrix(); } <|endoftext|>
<commit_before>/* promising: http://elinux.org/Interfacing_with_I2C_Devices https://i2c.wiki.kernel.org/index.php/Main_Page */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "LSM303.h" #include "L3G4200D.h" #include <sys/time.h> #include <Eigen/Geometry> int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void streamRawValues(LSM303& compass, L3G4200D& gyro) { compass.enableDefault(); gyro.enableDefault(); while(1) { compass.read(); gyro.read(); printf("%7d %7d %7d, %7d %7d %7d, %7d %7d %7d\n", compass.m(0), compass.m(1), compass.m(2), compass.a(0), compass.a(1), compass.a(2), gyro.g(0), gyro.g(1), gyro.g(2) ); usleep(100*1000); } } void calibrate(LSM303& compass) { compass.enableDefault(); int_vector mag_max(0,0,0), mag_min(0,0,0); while(1) { compass.read(); mag_min = mag_min.cwiseMin(compass.m); mag_max = mag_max.cwiseMax(compass.m); printf("%7d %7d %7d %7d %7d %7d\n", mag_min(0), mag_min(1), mag_min(2), mag_max(0), mag_max(1), mag_max(2)); usleep(10*1000); // TODO: have some way of writing to ~/.lsm303_mag_cal } } void loadCalibration(int_vector& mag_min, int_vector& mag_max) { // TODO: recalibrate for my new IMU // TODO: load from ~/.lsm303_mag_cal instead of hardcoding mag_min = int_vector(-835, -931, -978); mag_max = int_vector(921, 590, 741); } static void enableSensors(LSM303& compass, L3G4200D& gyro) { compass.writeAccReg(LSM303_CTRL_REG1_A, 0x47); // normal power mode, all axes enabled, 50 Hz compass.writeAccReg(LSM303_CTRL_REG4_A, 0x20); // 8 g full scale compass.writeMagReg(LSM303_MR_REG_M, 0x00); // continuous conversion mode // 15 Hz default gyro.writeReg(L3G4200D_CTRL_REG1, 0x0F); // normal power mode, all axes enabled, 100 Hz gyro.writeReg(L3G4200D_CTRL_REG4, 0x20); // 2000 dps full scale } // Calculate offsets, assuming the MiniMU is resting // with is z axis pointing up. static void calculateOffsets(LSM303& compass, L3G4200D& gyro, vector& accel_offset, vector& gyro_offset, const int_vector& accel_sign) { // LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256 const int gravity = 256; gyro_offset = accel_offset = vector(0,0,0); const int sampleCount = 32; for(int i = 0; i < sampleCount; i++) { gyro.read(); compass.readAcc(); gyro_offset += gyro.g.cast<float>(); accel_offset += compass.a.cast<float>(); usleep(20*1000); } gyro_offset /= sampleCount; accel_offset /= sampleCount; accel_offset(2) -= gravity * accel_sign(2); } // Returns the measured angular velocity vector // in units of radians per second. static vector readGyro(L3G4200D& gyro, const int_vector& gyro_sign, const vector& gyro_offset) { // At the full-scale=2000 dps setting, the gyro datasheet says // we get 0.07 dps/digit. const float gyro_gain = 0.07 * 3.14159265 / 180; gyro.read(); return gyro_sign.cast<float>().cwiseProduct( gyro.g.cast<float>() - gyro_offset ) * gyro_gain; } static matrix updateMatrix(const vector& w, float dt) { // TODO: represent this in a cooler way, maybe: // http://eigen.tuxfamily.org/dox/classEigen_1_1VectorwiseOp.html#aeaa2c5d72558c2bfc049a098efc25633 matrix m = matrix::Identity(); m(0,1) = -dt * w(2); m(0,2) = dt * w(1); m(1,0) = dt * w(2); m(1,2) = -dt * w(0); m(2,0) = -dt * w(1); m(2,1) = dt * w(0); return m; } // TODO: change this somehow to treat all the rows equally (currently Z is special) static matrix normalize(const matrix & m) { float error = m.row(0).dot(m.row(1)); matrix norm; norm.row(0) = m.row(0) - (error/2) * m.row(1); norm.row(1) = m.row(1) - (error/2) * m.row(0); norm.row(2) = m.row(0).cross(m.row(1)); return norm; } // DCM algorithm: http://diydrones.com/forum/topics/robust-estimator-of-the void ahrs(LSM303& compass, L3G4200D& gyro) { // X axis pointing forward // Y axis pointing to the right // and Z axis pointing down // Positive pitch : nose down // Positive roll : right wing down // Positive yaw : counterclockwise const int_vector gyro_sign(1, 1, 1); const int_vector accel_sign(1, 1, 1); const int_vector mag_sign(1, 1, 1); int_vector mag_min, mag_max; loadCalibration(mag_min, mag_max); enableSensors(compass, gyro); vector accel_offset, gyro_offset; calculateOffsets(compass, gyro, accel_offset, gyro_offset, accel_sign); //printf("Offset: %7f %7f %7f %7f %7f %7f\n", // gyro_offset(0), gyro_offset(1), gyro_offset(2), // accel_offset(0), accel_offset(1), accel_offset(2)); vector angular_velocity, v_accel, v_magnetom; // The rotation matrix that can convert a vector in body coordinates // to ground coordinates. matrix rotation = matrix::Identity(); int counter = 0; int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; //printf("dt = %f\n", dt); if (dt < 0){ throw "time went backwards"; } angular_velocity = readGyro(gyro, gyro_sign, gyro_offset); //readAcc(compass); // Every 5 loop runs read compass data (10 Hz) if (++counter == 5) { counter = 0; //readMag(compass); //compassHeading(); } rotation *= updateMatrix(angular_velocity, dt); rotation = normalize(rotation); //driftCorrection(); //eulerAngles(); //printf("%14.2f %14.2f %14.2f\n", v_gyro(0), v_gyro(1), v_gyro(2)); printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", rotation(0,0), rotation(0,1), rotation(0,2), rotation(1,0), rotation(1,1), rotation(1,2), rotation(2,0), rotation(2,1), rotation(2,2)); fflush(stdout); //std::cout << rotation; // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } int main(int argc, char *argv[]) { I2CBus i2c("/dev/i2c-0"); LSM303 compass(i2c); L3G4200D gyro(i2c); uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M); if (result != 0x3C) { std::cerr << "Error getting \"Who Am I\" register." << std::endl; exit(2); } if (argc > 1) { if (0 == strcmp("cal", argv[1])) { calibrate(compass); } else if (0 == strcmp("raw", argv[1])) { streamRawValues(compass, gyro); } else { fprintf(stderr, "Unknown action '%s'.\n", argv[1]); exit(3); } } else { ahrs(compass, gyro); } return 0; } <commit_msg>Added some debugging info on stderr. Now things are working nicely except for normalization.<commit_after>/* promising: http://elinux.org/Interfacing_with_I2C_Devices https://i2c.wiki.kernel.org/index.php/Main_Page */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "LSM303.h" #include "L3G4200D.h" #include <sys/time.h> #include <Eigen/Geometry> int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void streamRawValues(LSM303& compass, L3G4200D& gyro) { compass.enableDefault(); gyro.enableDefault(); while(1) { compass.read(); gyro.read(); printf("%7d %7d %7d, %7d %7d %7d, %7d %7d %7d\n", compass.m(0), compass.m(1), compass.m(2), compass.a(0), compass.a(1), compass.a(2), gyro.g(0), gyro.g(1), gyro.g(2) ); usleep(100*1000); } } void calibrate(LSM303& compass) { compass.enableDefault(); int_vector mag_max(0,0,0), mag_min(0,0,0); while(1) { compass.read(); mag_min = mag_min.cwiseMin(compass.m); mag_max = mag_max.cwiseMax(compass.m); printf("%7d %7d %7d %7d %7d %7d\n", mag_min(0), mag_min(1), mag_min(2), mag_max(0), mag_max(1), mag_max(2)); usleep(10*1000); // TODO: have some way of writing to ~/.lsm303_mag_cal } } void loadCalibration(int_vector& mag_min, int_vector& mag_max) { // TODO: recalibrate for my new IMU // TODO: load from ~/.lsm303_mag_cal instead of hardcoding mag_min = int_vector(-835, -931, -978); mag_max = int_vector(921, 590, 741); } static void enableSensors(LSM303& compass, L3G4200D& gyro) { compass.writeAccReg(LSM303_CTRL_REG1_A, 0x47); // normal power mode, all axes enabled, 50 Hz compass.writeAccReg(LSM303_CTRL_REG4_A, 0x20); // 8 g full scale compass.writeMagReg(LSM303_MR_REG_M, 0x00); // continuous conversion mode // 15 Hz default gyro.writeReg(L3G4200D_CTRL_REG1, 0x0F); // normal power mode, all axes enabled, 100 Hz gyro.writeReg(L3G4200D_CTRL_REG4, 0x20); // 2000 dps full scale } // Calculate offsets, assuming the MiniMU is resting // with is z axis pointing up. static void calculateOffsets(LSM303& compass, L3G4200D& gyro, vector& accel_offset, vector& gyro_offset, const int_vector& accel_sign) { // LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256 const int gravity = 256; gyro_offset = accel_offset = vector(0,0,0); const int sampleCount = 32; for(int i = 0; i < sampleCount; i++) { gyro.read(); compass.readAcc(); gyro_offset += gyro.g.cast<float>(); accel_offset += compass.a.cast<float>(); usleep(20*1000); } gyro_offset /= sampleCount; accel_offset /= sampleCount; accel_offset(2) -= gravity * accel_sign(2); } // Returns the measured angular velocity vector // in units of radians per second. static vector readGyro(L3G4200D& gyro, const int_vector& gyro_sign, const vector& gyro_offset) { // At the full-scale=2000 dps setting, the gyro datasheet says // we get 0.07 dps/digit. const float gyro_gain = 0.07 * 3.14159265 / 180; gyro.read(); return gyro_sign.cast<float>().cwiseProduct( gyro.g.cast<float>() - gyro_offset ) * gyro_gain; } static matrix updateMatrix(const vector& w, float dt) { // TODO: represent this in a cooler way, maybe: // http://eigen.tuxfamily.org/dox/classEigen_1_1VectorwiseOp.html#aeaa2c5d72558c2bfc049a098efc25633 matrix m = matrix::Identity(); m(2,0) = -w(1) * dt; m(0,2) = w(1) * dt; m(0,1) = -w(2) * dt; m(1,0) = w(2) * dt; m(1,2) = -w(0) * dt; m(2,1) = w(0) * dt; return m; } // TODO: change this somehow to treat all the rows equally (currently Z is special) static matrix normalize(const matrix & m) { float error = m.row(0).dot(m.row(1)); matrix norm; norm.row(0) = m.row(0) - (error/2) * m.row(1); norm.row(1) = m.row(1) - (error/2) * m.row(0); norm.row(2) = m.row(0).cross(m.row(1)); return norm; } // DCM algorithm: http://diydrones.com/forum/topics/robust-estimator-of-the void ahrs(LSM303& compass, L3G4200D& gyro) { // X axis pointing forward // Y axis pointing to the right // and Z axis pointing down // Positive pitch : nose down // Positive roll : right wing down // Positive yaw : counterclockwise const int_vector gyro_sign(1, 1, 1); const int_vector accel_sign(1, 1, 1); const int_vector mag_sign(1, 1, 1); int_vector mag_min, mag_max; loadCalibration(mag_min, mag_max); enableSensors(compass, gyro); vector accel_offset, gyro_offset; calculateOffsets(compass, gyro, accel_offset, gyro_offset, accel_sign); //printf("Offset: %7f %7f %7f %7f %7f %7f\n", // gyro_offset(0), gyro_offset(1), gyro_offset(2), // accel_offset(0), accel_offset(1), accel_offset(2)); vector angular_velocity, v_accel, v_magnetom; // The rotation matrix that can convert a vector in body coordinates // to ground coordinates. matrix rotation = matrix::Identity(); int counter = 0; int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; //printf("dt = %f\n", dt); if (dt < 0){ throw "time went backwards"; } angular_velocity = readGyro(gyro, gyro_sign, gyro_offset); //readAcc(compass); // Every 5 loop runs read compass data (10 Hz) if (++counter == 5) { counter = 0; //readMag(compass); //compassHeading(); } rotation *= updateMatrix(angular_velocity, dt); rotation = normalize(rotation); //driftCorrection(); //eulerAngles(); //fprintf(stderr, "g: %8d %8d %8d\n", gyro.g(0), gyro.g(1), gyro.g(2)); fprintf(stderr, "w: %7.4f %7.4f %7.4f\n", angular_velocity(0), angular_velocity(1), angular_velocity(2)); printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", rotation(0,0), rotation(0,1), rotation(0,2), rotation(1,0), rotation(1,1), rotation(1,2), rotation(2,0), rotation(2,1), rotation(2,2)); fflush(stdout); //std::cout << rotation; // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } int main(int argc, char *argv[]) { I2CBus i2c("/dev/i2c-0"); LSM303 compass(i2c); L3G4200D gyro(i2c); uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M); if (result != 0x3C) { std::cerr << "Error getting \"Who Am I\" register." << std::endl; exit(2); } if (argc > 1) { if (0 == strcmp("cal", argv[1])) { calibrate(compass); } else if (0 == strcmp("raw", argv[1])) { streamRawValues(compass, gyro); } else { fprintf(stderr, "Unknown action '%s'.\n", argv[1]); exit(3); } } else { ahrs(compass, gyro); } return 0; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Zeroth. // // Copyright (c) 2014 Colin Hill // /////////////////////////////////////////////////////////////////////////////// #include "ServerLoop.h" #include <Hect/Debug/TransformDebugRenderLayer.h> #include <Hect/Debug/BoundingBoxDebugRenderLayer.h> #include <Hect/Graphics/Components/DirectionalLight.h> #include <Hect/Graphics/Components/Geometry.h> #include <Hect/Physics/Components/RigidBody.h> #include <Hect/Spacial/Components/Transform.h> ServerLoop::ServerLoop(AssetCache& assetCache, InputSystem& inputSystem, Window& window, Renderer& renderer) : Loop(TimeSpan::fromSeconds((Real)1 / (Real)60)), _assetCache(&assetCache), _input(&inputSystem), _window(&window), _taskPool(4), _scene(assetCache), _renderSystem(_scene, renderer, assetCache), _debugRenderSystem(_scene, renderer), _transformSystem(_scene), _boundingBoxSystem(_scene), _physicsSystem(_scene, _taskPool), _playerCameraSystem(_scene, inputSystem), _transformDebugRenderLayer(assetCache), _boundingBoxDebugRenderLayer(assetCache) { _debugRenderSystem.addRenderLayer(Key_F5, _transformDebugRenderLayer); _debugRenderSystem.addRenderLayer(Key_F6, _boundingBoxDebugRenderLayer); Entity::Iter sun = _scene.createEntity(); auto directionalLight = sun->addComponent(DirectionalLight()); directionalLight->setColor(Vector3(1.0, 1.0, 1.0)); directionalLight->setDirection(Vector3(1.0, 0.0, 0.0)); sun->activate(); _player = _scene.createEntity("Test/Player.entity"); _player->activate(); _test = _scene.createEntity("Test/MaterialTest.entity"); _test->clone()->activate(); Dispatcher<KeyboardEvent>& keyboardDispatcher = _input->keyboard().dispatcher(); keyboardDispatcher.addListener(*this); keyboardDispatcher.addListener(_debugRenderSystem); Mouse& mouse = _input->mouse(); mouse.setMode(MouseMode_Relative); } ServerLoop::~ServerLoop() { Dispatcher<KeyboardEvent>& keyboardDispatcher = _input->keyboard().dispatcher(); keyboardDispatcher.removeListener(_debugRenderSystem); keyboardDispatcher.removeListener(*this); } void ServerLoop::fixedUpdate(Real timeStep) { _input->updateAxes(timeStep); _physicsSystem.endAsynchronousUpdate(); _playerCameraSystem.update(timeStep); _renderSystem.updateActiveCamera(); _transformSystem.update(); _boundingBoxSystem.update(); _physicsSystem.beginAsynchronousUpdate(timeStep, 4); } void ServerLoop::frameUpdate(Real delta) { delta; _renderSystem.renderAll(*_window); _debugRenderSystem.renderAll(*_window); _window->swapBuffers(); } void ServerLoop::receiveEvent(const KeyboardEvent& event) { if (event.type != KeyboardEventType_KeyDown) { return; } if (event.key == Key_Esc) { setActive(false); } if (event.key == Key_Tab) { Mouse& mouse = _input->mouse(); if (mouse.mode() == MouseMode_Cursor) { mouse.setMode(MouseMode_Relative); } else { mouse.setMode(MouseMode_Cursor); } } if (event.key == Key_F) { Entity::Iter cloneEntity = _test->clone(); cloneEntity->replaceComponent(*_player->component<Transform>()); auto rigidBody = cloneEntity->component<RigidBody>(); if (rigidBody) { rigidBody->setLinearVelocity(_player->component<Camera>()->front() * 15.0f); } cloneEntity->activate(); } }<commit_msg>Supporting changes<commit_after>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Zeroth. // // Copyright (c) 2014 Colin Hill // /////////////////////////////////////////////////////////////////////////////// #include "ServerLoop.h" #include <Hect/Debug/TransformDebugRenderLayer.h> #include <Hect/Debug/BoundingBoxDebugRenderLayer.h> #include <Hect/Graphics/Components/DirectionalLight.h> #include <Hect/Graphics/Components/Geometry.h> #include <Hect/Physics/Components/RigidBody.h> #include <Hect/Spacial/Components/Transform.h> ServerLoop::ServerLoop(AssetCache& assetCache, InputSystem& inputSystem, Window& window, Renderer& renderer) : Loop(TimeSpan::fromSeconds((Real)1 / (Real)60)), _assetCache(&assetCache), _input(&inputSystem), _window(&window), _taskPool(4), _scene(assetCache), _renderSystem(_scene, renderer, assetCache), _debugRenderSystem(_scene, renderer), _transformSystem(_scene), _boundingBoxSystem(_scene), _physicsSystem(_scene, _taskPool), _playerCameraSystem(_scene, inputSystem), _transformDebugRenderLayer(assetCache), _boundingBoxDebugRenderLayer(assetCache) { _debugRenderSystem.addRenderLayer(Key_F5, _transformDebugRenderLayer); _debugRenderSystem.addRenderLayer(Key_F6, _boundingBoxDebugRenderLayer); Entity::Iter sun = _scene.createEntity(); auto directionalLight = sun->addComponent(DirectionalLight()); directionalLight->setColor(Vector3(1.0, 1.0, 1.0)); directionalLight->setDirection(Vector3(1.0, -1.0, -1.0)); sun->activate(); _player = _scene.createEntity("Test/Player.entity"); _player->activate(); _test = _scene.createEntity("Test/MaterialTest.entity"); _test->clone()->activate(); Dispatcher<KeyboardEvent>& keyboardDispatcher = _input->keyboard().dispatcher(); keyboardDispatcher.addListener(*this); keyboardDispatcher.addListener(_debugRenderSystem); Mouse& mouse = _input->mouse(); mouse.setMode(MouseMode_Relative); } ServerLoop::~ServerLoop() { Dispatcher<KeyboardEvent>& keyboardDispatcher = _input->keyboard().dispatcher(); keyboardDispatcher.removeListener(_debugRenderSystem); keyboardDispatcher.removeListener(*this); } void ServerLoop::fixedUpdate(Real timeStep) { _input->updateAxes(timeStep); _physicsSystem.endAsynchronousUpdate(); _playerCameraSystem.update(timeStep); _renderSystem.updateActiveCamera(); _transformSystem.update(); _boundingBoxSystem.update(); _physicsSystem.beginAsynchronousUpdate(timeStep, 4); } void ServerLoop::frameUpdate(Real delta) { delta; _renderSystem.renderAll(*_window); _debugRenderSystem.renderAll(*_window); _window->swapBuffers(); } void ServerLoop::receiveEvent(const KeyboardEvent& event) { if (event.type != KeyboardEventType_KeyDown) { return; } if (event.key == Key_Esc) { setActive(false); } if (event.key == Key_Tab) { Mouse& mouse = _input->mouse(); if (mouse.mode() == MouseMode_Cursor) { mouse.setMode(MouseMode_Relative); } else { mouse.setMode(MouseMode_Cursor); } } if (event.key == Key_F) { Entity::Iter cloneEntity = _test->clone(); cloneEntity->replaceComponent(*_player->component<Transform>()); auto rigidBody = cloneEntity->component<RigidBody>(); if (rigidBody) { rigidBody->setLinearVelocity(_player->component<Camera>()->front() * 15.0f); } cloneEntity->activate(); } }<|endoftext|>
<commit_before>#include "vector.h" #include "MinIMU9.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <system_error> // TODO: print warning if accelerometer magnitude is not close to 1 when starting up int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void print(matrix m) { printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f", m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } void streamRawValues(IMU& imu) { imu.enable(); while(1) { imu.read(); printf("%7d %7d %7d %7d %7d %7d %7d %7d %7d\n", imu.raw_m[0], imu.raw_m[1], imu.raw_m[2], imu.raw_a[0], imu.raw_a[1], imu.raw_a[2], imu.raw_g[0], imu.raw_g[1], imu.raw_g[2] ); usleep(20*1000); } } matrix rotationFromCompass(const vector& acceleration, const vector& magnetic_field) { vector up = acceleration; // usually true vector magnetic_east = magnetic_field.cross(up); vector east = magnetic_east; // a rough approximation vector north = up.cross(east); matrix rotationFromCompass; rotationFromCompass.row(0) = east; rotationFromCompass.row(1) = north; rotationFromCompass.row(2) = up; rotationFromCompass.row(0).normalize(); rotationFromCompass.row(1).normalize(); rotationFromCompass.row(2).normalize(); return rotationFromCompass; } float heading(matrix rotation) { // The board's x axis in earth coordinates. vector x = rotation.col(0); x.normalize(); x(2) = 0; //float heading_weight = x.norm(); // 0 = east, pi/2 = north return atan2(x(1), x(0)); } typedef void fuse_function(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field); void fuse_compass_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { rotation = rotationFromCompass(acceleration, magnetic_field); } void fuse_gyro_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { // First order approximation of the quaternion representing this rotation. quaternion w = quaternion(1, angular_velocity(0)*dt/2, angular_velocity(1)*dt/2, angular_velocity(2)*dt/2); rotation *= w; rotation.normalize(); } #define Kp_ROLLPITCH 1 #define Ki_ROLLPITCH 0.00002 #define Kp_YAW 1 #define Ki_YAW 0.00002 #define PI 3.14159265 void fuse_default(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { rotation = quaternion::Identity(); // TODO: finish this algorithm //matrix rotationCompass = rotationFromCompass(acceleration, magnetic_field); // We trust the accelerometer more if it is telling us 1G. //float accel_weight = 1 - 2*abs(1 - acceleration.norm()); //if (accel_weight < 0){ accel_weight = 0; } // Add a "torque" that makes our up vector (rotation.row(2)) // get closer to the acceleration vector. //vector errorRollPitch = acceleration.cross(rotation.row(2)) * accel_weight; // Add a "torque" that makes our east vector (rotation.row(0)) // get closer to east vector calculated from the compass. //vector errorYaw = rotationCompass.row(0).cross(rotation.row(0)); //vector drift_correction = errorYaw * Kp_YAW + errorRollPitch * Kp_ROLLPITCH; //rotation *= updateMatrix(angular_velocity + drift_correction, dt); //rotation = normalize(rotation); } void ahrs(IMU& imu, fuse_function * fuse_func) { imu.loadCalibration(); imu.enable(); imu.measureOffsets(); // The quaternion that can convert a vector in body coordinates // to ground coordinates when it its changed to a matrix. quaternion rotation = quaternion::Identity(); int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; if (dt < 0){ throw std::runtime_error("time went backwards"); } vector angular_velocity = imu.readGyro(); vector acceleration = imu.readAcc(); vector magnetic_field = imu.readMag(); fuse_func(rotation, dt, angular_velocity, acceleration, magnetic_field); matrix r = rotation.matrix(); printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", r(0,0), r(0,1), r(0,2), r(1,0), r(1,1), r(1,2), r(2,0), r(2,1), r(2,2), acceleration(0), acceleration(1), acceleration(2), magnetic_field(0), magnetic_field(1), magnetic_field(2)); fflush(stdout); // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } int main(int argc, char *argv[]) { try { MinIMU9 imu("/dev/i2c-0"); imu.checkConnection(); if (argc > 1) { const char * action = argv[1]; if (0 == strcmp("raw", action)) { streamRawValues(imu); } else if (0 == strcmp("gyro-only", action)) { ahrs(imu, &fuse_gyro_only); } else if (0 == strcmp("compass-only", action)) { ahrs(imu, &fuse_compass_only); } else { fprintf(stderr, "Unknown action '%s'.\n", action); return 3; } } else { ahrs(imu, &fuse_default); } return 0; } catch(const std::system_error & error) { std::string what = error.what(); const std::error_code & code = error.code(); std::cerr << "Error: " << what << " " << code.message() << " (" << code << ")\n"; } catch(const std::exception & error) { std::cerr << "Error: " << error.what() << '\n'; } return 1; } <commit_msg>Made the quaternion algorithm actually work. Now the algorithm is much less arbitrary than it was before.<commit_after>#include "vector.h" #include "MinIMU9.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <system_error> // TODO: print warning if accelerometer magnitude is not close to 1 when starting up int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void print(matrix m) { printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f", m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } void streamRawValues(IMU& imu) { imu.enable(); while(1) { imu.read(); printf("%7d %7d %7d %7d %7d %7d %7d %7d %7d\n", imu.raw_m[0], imu.raw_m[1], imu.raw_m[2], imu.raw_a[0], imu.raw_a[1], imu.raw_a[2], imu.raw_g[0], imu.raw_g[1], imu.raw_g[2] ); usleep(20*1000); } } matrix rotationFromCompass(const vector& acceleration, const vector& magnetic_field) { vector up = acceleration; // usually true vector magnetic_east = magnetic_field.cross(up); vector east = magnetic_east; // a rough approximation vector north = up.cross(east); matrix rotationFromCompass; rotationFromCompass.row(0) = east; rotationFromCompass.row(1) = north; rotationFromCompass.row(2) = up; rotationFromCompass.row(0).normalize(); rotationFromCompass.row(1).normalize(); rotationFromCompass.row(2).normalize(); return rotationFromCompass; } float heading(matrix rotation) { // The board's x axis in earth coordinates. vector x = rotation.col(0); x.normalize(); x(2) = 0; //float heading_weight = x.norm(); // 0 = east, pi/2 = north return atan2(x(1), x(0)); } typedef void fuse_function(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field); void fuse_compass_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { // Implicit conversion of rotation matrix to quaternion. rotation = rotationFromCompass(acceleration, magnetic_field); } // w is angular velocity in radiands per second. // dt is the time. void rotate(quaternion& rotation, const vector& w, float dt) { // First order approximation of the quaternion representing this rotation. quaternion q = quaternion(1, w(0)*dt/2, w(1)*dt/2, w(2)*dt/2); rotation *= q; rotation.normalize(); } void fuse_gyro_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { rotate(rotation, angular_velocity, dt); } void fuse_default(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { vector correction = vector(0, 0, 0); if (abs(acceleration.norm() - 1) <= 0.3) { // The magnetidude of acceleration is close to 1 g, so // it might be pointing up and we can do drift correction. const float correction_strength = 1; matrix rotationCompass = rotationFromCompass(acceleration, magnetic_field); matrix rotationMatrix = rotation.toRotationMatrix(); correction = ( rotationCompass.row(0).cross(rotationMatrix.row(0)) + rotationCompass.row(1).cross(rotationMatrix.row(1)) + rotationCompass.row(2).cross(rotationMatrix.row(2)) ) * correction_strength; } rotate(rotation, angular_velocity + correction, dt); } void ahrs(IMU& imu, fuse_function * fuse_func) { imu.loadCalibration(); imu.enable(); imu.measureOffsets(); // The quaternion that can convert a vector in body coordinates // to ground coordinates when it its changed to a matrix. quaternion rotation = quaternion::Identity(); int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; if (dt < 0){ throw std::runtime_error("time went backwards"); } vector angular_velocity = imu.readGyro(); vector acceleration = imu.readAcc(); vector magnetic_field = imu.readMag(); fuse_func(rotation, dt, angular_velocity, acceleration, magnetic_field); matrix r = rotation.toRotationMatrix(); printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", r(0,0), r(0,1), r(0,2), r(1,0), r(1,1), r(1,2), r(2,0), r(2,1), r(2,2), acceleration(0), acceleration(1), acceleration(2), magnetic_field(0), magnetic_field(1), magnetic_field(2)); fflush(stdout); // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } int main(int argc, char *argv[]) { try { MinIMU9 imu("/dev/i2c-0"); imu.checkConnection(); if (argc > 1) { const char * action = argv[1]; if (0 == strcmp("raw", action)) { streamRawValues(imu); } else if (0 == strcmp("gyro-only", action)) { ahrs(imu, &fuse_gyro_only); } else if (0 == strcmp("compass-only", action)) { ahrs(imu, &fuse_compass_only); } else { fprintf(stderr, "Unknown action '%s'.\n", action); return 3; } } else { ahrs(imu, &fuse_default); } return 0; } catch(const std::system_error & error) { std::string what = error.what(); const std::error_code & code = error.code(); std::cerr << "Error: " << what << " " << code.message() << " (" << code << ")\n"; } catch(const std::exception & error) { std::cerr << "Error: " << error.what() << '\n'; } return 1; } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /* Tool to create accuracy statistics from running an audio recognition model on a continuous stream of samples. This is designed to be an environment for running experiments on new models and settings to understand the effects they will have in a real application. You need to supply it with a long audio file containing sounds you want to recognize and a text file listing the labels of each sound along with the time they occur. With this information, and a frozen model, the tool will process the audio stream, apply the model, and keep track of how many mistakes and successes the model achieved. The matched percentage is the number of sounds that were correctly classified, as a percentage of the total number of sounds listed in the ground truth file. A correct classification is when the right label is chosen within a short time of the expected ground truth, where the time tolerance is controlled by the 'time_tolerance_ms' command line flag. The wrong percentage is how many sounds triggered a detection (the classifier figured out it wasn't silence or background noise), but the detected class was wrong. This is also a percentage of the total number of ground truth sounds. The false positive percentage is how many sounds were detected when there was only silence or background noise. This is also expressed as a percentage of the total number of ground truth sounds, though since it can be large it may go above 100%. The easiest way to get an audio file and labels to test with is by using the 'generate_streaming_test_wav' script. This will synthesize a test file with randomly placed sounds and background noise, and output a text file with the ground truth. If you want to test natural data, you need to use a .wav with the same sample rate as your model (often 16,000 samples per second), and note down where the sounds occur in time. Save this information out as a comma-separated text file, where the first column is the label and the second is the time in seconds from the start of the file that it occurs. Here's an example of how to run the tool: bazel run tensorflow/examples/speech_commands:test_streaming_accuracy -- \ --wav=/tmp/streaming_test_bg.wav \ --graph=/tmp/conv_frozen.pb \ --labels=/tmp/speech_commands_train/conv_labels.txt \ --ground_truth=/tmp/streaming_test_labels.txt --verbose \ --clip_duration_ms=1000 --detection_threshold=0.70 --average_window_ms=500 \ --suppression_ms=500 --time_tolerance_ms=1500 */ #include <fstream> #include <iomanip> #include <unordered_set> #include <vector> #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/wav/wav_io.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/examples/speech_commands/accuracy_utils.h" #include "tensorflow/examples/speech_commands/recognize_commands.h" // These are all common classes it's handy to reference with no namespace. using tensorflow::Flag; using tensorflow::Status; using tensorflow::Tensor; using tensorflow::int32; using tensorflow::int64; using tensorflow::string; using tensorflow::uint16; using tensorflow::uint32; namespace { // Reads a model graph definition from disk, and creates a session object you // can use to run it. Status LoadGraph(const string& graph_file_name, std::unique_ptr<tensorflow::Session>* session) { tensorflow::GraphDef graph_def; Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def); if (!load_graph_status.ok()) { return tensorflow::errors::NotFound("Failed to load compute graph at '", graph_file_name, "'"); } session->reset(tensorflow::NewSession(tensorflow::SessionOptions())); Status session_create_status = (*session)->Create(graph_def); if (!session_create_status.ok()) { return session_create_status; } return Status::OK(); } // Takes a file name, and loads a list of labels from it, one per line, and // returns a vector of the strings. Status ReadLabelsFile(const string& file_name, std::vector<string>* result) { std::ifstream file(file_name); if (!file) { return tensorflow::errors::NotFound("Labels file '", file_name, "' not found."); } result->clear(); string line; while (std::getline(file, line)) { result->push_back(line); } return Status::OK(); } } // namespace int main(int argc, char* argv[]) { string wav = ""; string graph = ""; string labels = ""; string ground_truth = ""; string input_data_name = "decoded_sample_data:0"; string input_rate_name = "decoded_sample_data:1"; string output_name = "labels_softmax"; int32 clip_duration_ms = 1000; int32 clip_stride_ms = 30; int32 average_window_ms = 500; int32 time_tolerance_ms = 750; int32 suppression_ms = 1500; float detection_threshold = 0.7f; bool verbose = false; std::vector<Flag> flag_list = { Flag("wav", &wav, "audio file to be identified"), Flag("graph", &graph, "model to be executed"), Flag("labels", &labels, "path to file containing labels"), Flag("ground_truth", &ground_truth, "path to file containing correct times and labels of words in the " "audio as <word>,<timestamp in ms> lines"), Flag("input_data_name", &input_data_name, "name of input data node in model"), Flag("input_rate_name", &input_rate_name, "name of input sample rate node in model"), Flag("output_name", &output_name, "name of output node in model"), Flag("clip_duration_ms", &clip_duration_ms, "length of recognition window"), Flag("average_window_ms", &average_window_ms, "length of window to smooth results over"), Flag("time_tolerance_ms", &time_tolerance_ms, "maximum gap allowed between a recognition and ground truth"), Flag("suppression_ms", &suppression_ms, "how long to ignore others for after a recognition"), Flag("clip_stride_ms", &clip_stride_ms, "how often to run recognition"), Flag("detection_threshold", &detection_threshold, "what score is required to trigger detection of a word"), Flag("verbose", &verbose, "whether to log extra debugging information"), }; string usage = tensorflow::Flags::Usage(argv[0], flag_list); const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list); if (!parse_result) { LOG(ERROR) << usage; return -1; } // We need to call this to set up global state for TensorFlow. tensorflow::port::InitMain(argv[0], &argc, &argv); if (argc > 1) { LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage; return -1; } // First we load and initialize the model. std::unique_ptr<tensorflow::Session> session; Status load_graph_status = LoadGraph(graph, &session); if (!load_graph_status.ok()) { LOG(ERROR) << load_graph_status; return -1; } std::vector<string> labels_list; Status read_labels_status = ReadLabelsFile(labels, &labels_list); if (!read_labels_status.ok()) { LOG(ERROR) << read_labels_status; return -1; } std::vector<std::pair<string, tensorflow::int64>> ground_truth_list; Status read_ground_truth_status = tensorflow::ReadGroundTruthFile(ground_truth, &ground_truth_list); if (!read_ground_truth_status.ok()) { LOG(ERROR) << read_ground_truth_status; return -1; } string wav_string; Status read_wav_status = tensorflow::ReadFileToString( tensorflow::Env::Default(), wav, &wav_string); if (!read_wav_status.ok()) { LOG(ERROR) << read_wav_status; return -1; } std::vector<float> audio_data; uint32 sample_count; uint16 channel_count; uint32 sample_rate; Status decode_wav_status = tensorflow::wav::DecodeLin16WaveAsFloatVector( wav_string, &audio_data, &sample_count, &channel_count, &sample_rate); if (!decode_wav_status.ok()) { LOG(ERROR) << decode_wav_status; return -1; } if (channel_count != 1) { LOG(ERROR) << "Only mono .wav files can be used, but input has " << channel_count << " channels."; return -1; } const int64 clip_duration_samples = (clip_duration_ms * sample_rate) / 1000; const int64 sample_stride_samples = (clip_stride_ms * sample_rate) / 1000; Tensor audio_data_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({clip_duration_samples, 1})); Tensor sample_rate_tensor(tensorflow::DT_INT32, tensorflow::TensorShape({})); sample_rate_tensor.scalar<int32>()() = sample_rate; tensorflow::RecognizeCommands recognize_commands( labels_list, average_window_ms, detection_threshold, suppression_ms); std::vector<std::pair<string, int64>> all_found_words; tensorflow::StreamingAccuracyStats previous_stats; const int64 audio_data_end = (sample_count - clip_duration_ms); for (int64 audio_data_offset = 0; audio_data_offset < audio_data_end; audio_data_offset += sample_stride_samples) { const float* input_start = &(audio_data[audio_data_offset]); const float* input_end = input_start + clip_duration_samples; std::copy(input_start, input_end, audio_data_tensor.flat<float>().data()); // Actually run the audio through the model. std::vector<Tensor> outputs; Status run_status = session->Run({{input_data_name, audio_data_tensor}, {input_rate_name, sample_rate_tensor}}, {output_name}, {}, &outputs); if (!run_status.ok()) { LOG(ERROR) << "Running model failed: " << run_status; return -1; } const int64 current_time_ms = (audio_data_offset * 1000) / sample_rate; string found_command; float score; bool is_new_command; Status recognize_status = recognize_commands.ProcessLatestResults( outputs[0], current_time_ms, &found_command, &score, &is_new_command); if (!recognize_status.ok()) { LOG(ERROR) << "Recognition processing failed: " << recognize_status; return -1; } if (is_new_command && (found_command != "_silence_")) { all_found_words.push_back({found_command, current_time_ms}); if (verbose) { tensorflow::StreamingAccuracyStats stats; tensorflow::CalculateAccuracyStats(ground_truth_list, all_found_words, current_time_ms, time_tolerance_ms, &stats); int32 false_positive_delta = stats.how_many_false_positives - previous_stats.how_many_false_positives; int32 correct_delta = stats.how_many_correct_words - previous_stats.how_many_correct_words; int32 wrong_delta = stats.how_many_wrong_words - previous_stats.how_many_wrong_words; string recognition_state; if (false_positive_delta == 1) { recognition_state = " (False Positive)"; } else if (correct_delta == 1) { recognition_state = " (Correct)"; } else if (wrong_delta == 1) { recognition_state = " (Wrong)"; } else { LOG(ERROR) << "Unexpected state in statistics"; } LOG(INFO) << current_time_ms << "ms: " << found_command << ": " << score << recognition_state; previous_stats = stats; tensorflow::PrintAccuracyStats(stats); } } } tensorflow::StreamingAccuracyStats stats; tensorflow::CalculateAccuracyStats(ground_truth_list, all_found_words, -1, time_tolerance_ms, &stats); tensorflow::PrintAccuracyStats(stats); return 0; } <commit_msg>Renames variable for consistency with flag.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ /* Tool to create accuracy statistics from running an audio recognition model on a continuous stream of samples. This is designed to be an environment for running experiments on new models and settings to understand the effects they will have in a real application. You need to supply it with a long audio file containing sounds you want to recognize and a text file listing the labels of each sound along with the time they occur. With this information, and a frozen model, the tool will process the audio stream, apply the model, and keep track of how many mistakes and successes the model achieved. The matched percentage is the number of sounds that were correctly classified, as a percentage of the total number of sounds listed in the ground truth file. A correct classification is when the right label is chosen within a short time of the expected ground truth, where the time tolerance is controlled by the 'time_tolerance_ms' command line flag. The wrong percentage is how many sounds triggered a detection (the classifier figured out it wasn't silence or background noise), but the detected class was wrong. This is also a percentage of the total number of ground truth sounds. The false positive percentage is how many sounds were detected when there was only silence or background noise. This is also expressed as a percentage of the total number of ground truth sounds, though since it can be large it may go above 100%. The easiest way to get an audio file and labels to test with is by using the 'generate_streaming_test_wav' script. This will synthesize a test file with randomly placed sounds and background noise, and output a text file with the ground truth. If you want to test natural data, you need to use a .wav with the same sample rate as your model (often 16,000 samples per second), and note down where the sounds occur in time. Save this information out as a comma-separated text file, where the first column is the label and the second is the time in seconds from the start of the file that it occurs. Here's an example of how to run the tool: bazel run tensorflow/examples/speech_commands:test_streaming_accuracy -- \ --wav=/tmp/streaming_test_bg.wav \ --graph=/tmp/conv_frozen.pb \ --labels=/tmp/speech_commands_train/conv_labels.txt \ --ground_truth=/tmp/streaming_test_labels.txt --verbose \ --clip_duration_ms=1000 --detection_threshold=0.70 --average_window_ms=500 \ --suppression_ms=500 --time_tolerance_ms=1500 */ #include <fstream> #include <iomanip> #include <unordered_set> #include <vector> #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/wav/wav_io.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/examples/speech_commands/accuracy_utils.h" #include "tensorflow/examples/speech_commands/recognize_commands.h" // These are all common classes it's handy to reference with no namespace. using tensorflow::Flag; using tensorflow::Status; using tensorflow::Tensor; using tensorflow::int32; using tensorflow::int64; using tensorflow::string; using tensorflow::uint16; using tensorflow::uint32; namespace { // Reads a model graph definition from disk, and creates a session object you // can use to run it. Status LoadGraph(const string& graph_file_name, std::unique_ptr<tensorflow::Session>* session) { tensorflow::GraphDef graph_def; Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def); if (!load_graph_status.ok()) { return tensorflow::errors::NotFound("Failed to load compute graph at '", graph_file_name, "'"); } session->reset(tensorflow::NewSession(tensorflow::SessionOptions())); Status session_create_status = (*session)->Create(graph_def); if (!session_create_status.ok()) { return session_create_status; } return Status::OK(); } // Takes a file name, and loads a list of labels from it, one per line, and // returns a vector of the strings. Status ReadLabelsFile(const string& file_name, std::vector<string>* result) { std::ifstream file(file_name); if (!file) { return tensorflow::errors::NotFound("Labels file '", file_name, "' not found."); } result->clear(); string line; while (std::getline(file, line)) { result->push_back(line); } return Status::OK(); } } // namespace int main(int argc, char* argv[]) { string wav = ""; string graph = ""; string labels = ""; string ground_truth = ""; string input_data_name = "decoded_sample_data:0"; string input_rate_name = "decoded_sample_data:1"; string output_name = "labels_softmax"; int32 clip_duration_ms = 1000; int32 clip_stride_ms = 30; int32 average_window_ms = 500; int32 time_tolerance_ms = 750; int32 suppression_ms = 1500; float detection_threshold = 0.7f; bool verbose = false; std::vector<Flag> flag_list = { Flag("wav", &wav, "audio file to be identified"), Flag("graph", &graph, "model to be executed"), Flag("labels", &labels, "path to file containing labels"), Flag("ground_truth", &ground_truth, "path to file containing correct times and labels of words in the " "audio as <word>,<timestamp in ms> lines"), Flag("input_data_name", &input_data_name, "name of input data node in model"), Flag("input_rate_name", &input_rate_name, "name of input sample rate node in model"), Flag("output_name", &output_name, "name of output node in model"), Flag("clip_duration_ms", &clip_duration_ms, "length of recognition window"), Flag("average_window_ms", &average_window_ms, "length of window to smooth results over"), Flag("time_tolerance_ms", &time_tolerance_ms, "maximum gap allowed between a recognition and ground truth"), Flag("suppression_ms", &suppression_ms, "how long to ignore others for after a recognition"), Flag("clip_stride_ms", &clip_stride_ms, "how often to run recognition"), Flag("detection_threshold", &detection_threshold, "what score is required to trigger detection of a word"), Flag("verbose", &verbose, "whether to log extra debugging information"), }; string usage = tensorflow::Flags::Usage(argv[0], flag_list); const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list); if (!parse_result) { LOG(ERROR) << usage; return -1; } // We need to call this to set up global state for TensorFlow. tensorflow::port::InitMain(argv[0], &argc, &argv); if (argc > 1) { LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage; return -1; } // First we load and initialize the model. std::unique_ptr<tensorflow::Session> session; Status load_graph_status = LoadGraph(graph, &session); if (!load_graph_status.ok()) { LOG(ERROR) << load_graph_status; return -1; } std::vector<string> labels_list; Status read_labels_status = ReadLabelsFile(labels, &labels_list); if (!read_labels_status.ok()) { LOG(ERROR) << read_labels_status; return -1; } std::vector<std::pair<string, tensorflow::int64>> ground_truth_list; Status read_ground_truth_status = tensorflow::ReadGroundTruthFile(ground_truth, &ground_truth_list); if (!read_ground_truth_status.ok()) { LOG(ERROR) << read_ground_truth_status; return -1; } string wav_string; Status read_wav_status = tensorflow::ReadFileToString( tensorflow::Env::Default(), wav, &wav_string); if (!read_wav_status.ok()) { LOG(ERROR) << read_wav_status; return -1; } std::vector<float> audio_data; uint32 sample_count; uint16 channel_count; uint32 sample_rate; Status decode_wav_status = tensorflow::wav::DecodeLin16WaveAsFloatVector( wav_string, &audio_data, &sample_count, &channel_count, &sample_rate); if (!decode_wav_status.ok()) { LOG(ERROR) << decode_wav_status; return -1; } if (channel_count != 1) { LOG(ERROR) << "Only mono .wav files can be used, but input has " << channel_count << " channels."; return -1; } const int64 clip_duration_samples = (clip_duration_ms * sample_rate) / 1000; const int64 clip_stride_samples = (clip_stride_ms * sample_rate) / 1000; Tensor audio_data_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({clip_duration_samples, 1})); Tensor sample_rate_tensor(tensorflow::DT_INT32, tensorflow::TensorShape({})); sample_rate_tensor.scalar<int32>()() = sample_rate; tensorflow::RecognizeCommands recognize_commands( labels_list, average_window_ms, detection_threshold, suppression_ms); std::vector<std::pair<string, int64>> all_found_words; tensorflow::StreamingAccuracyStats previous_stats; const int64 audio_data_end = (sample_count - clip_duration_ms); for (int64 audio_data_offset = 0; audio_data_offset < audio_data_end; audio_data_offset += clip_stride_samples) { const float* input_start = &(audio_data[audio_data_offset]); const float* input_end = input_start + clip_duration_samples; std::copy(input_start, input_end, audio_data_tensor.flat<float>().data()); // Actually run the audio through the model. std::vector<Tensor> outputs; Status run_status = session->Run({{input_data_name, audio_data_tensor}, {input_rate_name, sample_rate_tensor}}, {output_name}, {}, &outputs); if (!run_status.ok()) { LOG(ERROR) << "Running model failed: " << run_status; return -1; } const int64 current_time_ms = (audio_data_offset * 1000) / sample_rate; string found_command; float score; bool is_new_command; Status recognize_status = recognize_commands.ProcessLatestResults( outputs[0], current_time_ms, &found_command, &score, &is_new_command); if (!recognize_status.ok()) { LOG(ERROR) << "Recognition processing failed: " << recognize_status; return -1; } if (is_new_command && (found_command != "_silence_")) { all_found_words.push_back({found_command, current_time_ms}); if (verbose) { tensorflow::StreamingAccuracyStats stats; tensorflow::CalculateAccuracyStats(ground_truth_list, all_found_words, current_time_ms, time_tolerance_ms, &stats); int32 false_positive_delta = stats.how_many_false_positives - previous_stats.how_many_false_positives; int32 correct_delta = stats.how_many_correct_words - previous_stats.how_many_correct_words; int32 wrong_delta = stats.how_many_wrong_words - previous_stats.how_many_wrong_words; string recognition_state; if (false_positive_delta == 1) { recognition_state = " (False Positive)"; } else if (correct_delta == 1) { recognition_state = " (Correct)"; } else if (wrong_delta == 1) { recognition_state = " (Wrong)"; } else { LOG(ERROR) << "Unexpected state in statistics"; } LOG(INFO) << current_time_ms << "ms: " << found_command << ": " << score << recognition_state; previous_stats = stats; tensorflow::PrintAccuracyStats(stats); } } } tensorflow::StreamingAccuracyStats stats; tensorflow::CalculateAccuracyStats(ground_truth_list, all_found_words, -1, time_tolerance_ms, &stats); tensorflow::PrintAccuracyStats(stats); return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<class _Tp> // basic_string(const _Tp& __t, size_type __pos, size_type __n, // const allocator_type& __a = allocator_type()); // // Mostly we're testing string_view here #include <string> #include <string_view> #include <stdexcept> #include <algorithm> #include <cassert> #include "test_macros.h" #include "test_allocator.h" #include "min_allocator.h" template <class S, class SV> void test(SV sv, unsigned pos, unsigned n) { typedef typename S::traits_type T; typedef typename S::allocator_type A; if (pos <= sv.size()) { S s2(sv, pos, n); LIBCPP_ASSERT(s2.__invariants()); assert(pos <= sv.size()); unsigned rlen = std::min<unsigned>(sv.size() - pos, n); assert(s2.size() == rlen); assert(T::compare(s2.data(), sv.data() + pos, rlen) == 0); assert(s2.get_allocator() == A()); assert(s2.capacity() >= s2.size()); } #ifndef TEST_HAS_NO_EXCEPTIONS else { try { S s2(sv, pos, n); assert(false); } catch (std::out_of_range&) { assert(pos > sv.size()); } } #endif } template <class S, class SV> void test(SV sv, unsigned pos, unsigned n, const typename S::allocator_type& a) { typedef typename S::traits_type T; typedef typename S::allocator_type A; if (pos <= sv.size()) { S s2(sv, pos, n, a); LIBCPP_ASSERT(s2.__invariants()); assert(pos <= sv.size()); unsigned rlen = std::min<unsigned>(sv.size() - pos, n); assert(s2.size() == rlen); assert(T::compare(s2.data(), sv.data() + pos, rlen) == 0); assert(s2.get_allocator() == a); assert(s2.capacity() >= s2.size()); } #ifndef TEST_HAS_NO_EXCEPTIONS else { try { S s2(sv, pos, n, a); assert(false); } catch (std::out_of_range&) { assert(pos > sv.size()); } } #endif } int main() { { typedef test_allocator<char> A; typedef std::basic_string_view<char, std::char_traits<char> > SV; typedef std::basic_string <char, std::char_traits<char>, A> S; test<S,SV>(SV(), 0, 0); test<S,SV>(SV(), 0, 1); test<S,SV>(SV(), 1, 0); test<S,SV>(SV(), 1, 1); test<S,SV>(SV(), 1, 2); test<S,SV>(SV("1"), 0, 0); test<S,SV>(SV("1"), 0, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100); test<S,SV>(SV(), 0, 0, A(4)); test<S,SV>(SV(), 0, 1, A(4)); test<S,SV>(SV(), 1, 0, A(4)); test<S,SV>(SV(), 1, 1, A(4)); test<S,SV>(SV(), 1, 2, A(4)); test<S,SV>(SV("1"), 0, 0, A(6)); test<S,SV>(SV("1"), 0, 1, A(6)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0, A(8)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1, A(8)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10, A(8)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100, A(8)); } #if TEST_STD_VER >= 11 { typedef min_allocator<char> A; typedef std::basic_string_view<char, std::char_traits<char> > SV; typedef std::basic_string <char, std::char_traits<char>, A> S; test<S,SV>(SV(), 0, 0); test<S,SV>(SV(), 0, 1); test<S,SV>(SV(), 1, 0); test<S,SV>(SV(), 1, 1); test<S,SV>(SV(), 1, 2); test<S,SV>(SV("1"), 0, 0); test<S,SV>(SV("1"), 0, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100); test<S,SV>(SV(), 0, 0, A()); test<S,SV>(SV(), 0, 1, A()); test<S,SV>(SV(), 1, 0, A()); test<S,SV>(SV(), 1, 1, A()); test<S,SV>(SV(), 1, 2, A()); test<S,SV>(SV("1"), 0, 0, A()); test<S,SV>(SV("1"), 0, 1, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100, A()); } #endif { typedef std::string S; typedef std::string_view SV; S s = "ABCD"; SV sv = "EFGH"; char arr[] = "IJKL"; S s1("CDEF", 4); // calls ctor(const char *, len) assert(s1 == "CDEF"); S s2("QRST", 0, 3); // calls ctor(string("QRST", pos, len) assert(s2 == "QRS"); S s3(sv, 0, std::string::npos); // calls ctor(T, pos, npos) assert(s3 == sv); S s4(sv, 0, 3); // calls ctor(T, pos, len) assert(s4 == "EFG"); S s5(arr, 0, 2); // calls ctor(const char *, len) assert(s5 == "IJ"); S s6(arr, 0); // calls ctor(const char *, len) assert(s6 == ""); S s7(s.data(), 2); // calls ctor(const char *, len) assert(s7 == "AB"); } } <commit_msg>Resolve unused local typedef warning in test.<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<class _Tp> // basic_string(const _Tp& __t, size_type __pos, size_type __n, // const allocator_type& __a = allocator_type()); // // Mostly we're testing string_view here #include <string> #include <string_view> #include <stdexcept> #include <algorithm> #include <cassert> #include "test_macros.h" #include "test_allocator.h" #include "min_allocator.h" template <class S, class SV> void test(SV sv, unsigned pos, unsigned n) { typedef typename S::traits_type T; typedef typename S::allocator_type A; if (pos <= sv.size()) { S s2(sv, pos, n); LIBCPP_ASSERT(s2.__invariants()); assert(pos <= sv.size()); unsigned rlen = std::min<unsigned>(sv.size() - pos, n); assert(s2.size() == rlen); assert(T::compare(s2.data(), sv.data() + pos, rlen) == 0); assert(s2.get_allocator() == A()); assert(s2.capacity() >= s2.size()); } #ifndef TEST_HAS_NO_EXCEPTIONS else { try { S s2(sv, pos, n); assert(false); } catch (std::out_of_range&) { assert(pos > sv.size()); } } #endif } template <class S, class SV> void test(SV sv, unsigned pos, unsigned n, const typename S::allocator_type& a) { typedef typename S::traits_type T; if (pos <= sv.size()) { S s2(sv, pos, n, a); LIBCPP_ASSERT(s2.__invariants()); assert(pos <= sv.size()); unsigned rlen = std::min<unsigned>(sv.size() - pos, n); assert(s2.size() == rlen); assert(T::compare(s2.data(), sv.data() + pos, rlen) == 0); assert(s2.get_allocator() == a); assert(s2.capacity() >= s2.size()); } #ifndef TEST_HAS_NO_EXCEPTIONS else { try { S s2(sv, pos, n, a); assert(false); } catch (std::out_of_range&) { assert(pos > sv.size()); } } #endif } int main() { { typedef test_allocator<char> A; typedef std::basic_string_view<char, std::char_traits<char> > SV; typedef std::basic_string <char, std::char_traits<char>, A> S; test<S,SV>(SV(), 0, 0); test<S,SV>(SV(), 0, 1); test<S,SV>(SV(), 1, 0); test<S,SV>(SV(), 1, 1); test<S,SV>(SV(), 1, 2); test<S,SV>(SV("1"), 0, 0); test<S,SV>(SV("1"), 0, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100); test<S,SV>(SV(), 0, 0, A(4)); test<S,SV>(SV(), 0, 1, A(4)); test<S,SV>(SV(), 1, 0, A(4)); test<S,SV>(SV(), 1, 1, A(4)); test<S,SV>(SV(), 1, 2, A(4)); test<S,SV>(SV("1"), 0, 0, A(6)); test<S,SV>(SV("1"), 0, 1, A(6)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0, A(8)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1, A(8)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10, A(8)); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100, A(8)); } #if TEST_STD_VER >= 11 { typedef min_allocator<char> A; typedef std::basic_string_view<char, std::char_traits<char> > SV; typedef std::basic_string <char, std::char_traits<char>, A> S; test<S,SV>(SV(), 0, 0); test<S,SV>(SV(), 0, 1); test<S,SV>(SV(), 1, 0); test<S,SV>(SV(), 1, 1); test<S,SV>(SV(), 1, 2); test<S,SV>(SV("1"), 0, 0); test<S,SV>(SV("1"), 0, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100); test<S,SV>(SV(), 0, 0, A()); test<S,SV>(SV(), 0, 1, A()); test<S,SV>(SV(), 1, 0, A()); test<S,SV>(SV(), 1, 1, A()); test<S,SV>(SV(), 1, 2, A()); test<S,SV>(SV("1"), 0, 0, A()); test<S,SV>(SV("1"), 0, 1, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 0, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 1, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 10, A()); test<S,SV>(SV("1234567890123456789012345678901234567890123456789012345678901234567890"), 50, 100, A()); } #endif { typedef std::string S; typedef std::string_view SV; S s = "ABCD"; SV sv = "EFGH"; char arr[] = "IJKL"; S s1("CDEF", 4); // calls ctor(const char *, len) assert(s1 == "CDEF"); S s2("QRST", 0, 3); // calls ctor(string("QRST", pos, len) assert(s2 == "QRS"); S s3(sv, 0, std::string::npos); // calls ctor(T, pos, npos) assert(s3 == sv); S s4(sv, 0, 3); // calls ctor(T, pos, len) assert(s4 == "EFG"); S s5(arr, 0, 2); // calls ctor(const char *, len) assert(s5 == "IJ"); S s6(arr, 0); // calls ctor(const char *, len) assert(s6 == ""); S s7(s.data(), 2); // calls ctor(const char *, len) assert(s7 == "AB"); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <QtDeclarative/qmlcontext.h> #include <QtDeclarative/qmlview.h> #include <qmlgraphicsitem.h> class tst_QmlGraphicsItem : public QObject { Q_OBJECT public: tst_QmlGraphicsItem(); private slots: void keys(); void keyNavigation(); private: template<typename T> T *findItem(QmlGraphicsItem *parent, const QString &objectName); }; class KeysTestObject : public QObject { Q_OBJECT public: KeysTestObject() : mKey(0), mModifiers(0), mForwardedKey(0) {} void reset() { mKey = 0; mText = QString(); mModifiers = 0; mForwardedKey = 0; } public slots: void keyPress(int key, QString text, int modifiers) { mKey = key; mText = text; mModifiers = modifiers; } void keyRelease(int key, QString text, int modifiers) { mKey = key; mText = text; mModifiers = modifiers; } void forwardedKey(int key) { mForwardedKey = key; } public: int mKey; QString mText; int mModifiers; int mForwardedKey; private: }; tst_QmlGraphicsItem::tst_QmlGraphicsItem() { } void tst_QmlGraphicsItem::keys() { QmlView *canvas = new QmlView(0); canvas->setFixedSize(240,320); canvas->setUrl(QUrl("file://" SRCDIR "/data/keys.qml")); KeysTestObject *testObject = new KeysTestObject; canvas->rootContext()->setContextProperty("keysTestObject", testObject); canvas->execute(); canvas->show(); qApp->processEvents(); QEvent wa(QEvent::WindowActivate); QApplication::sendEvent(canvas, &wa); QFocusEvent fe(QEvent::FocusIn); QApplication::sendEvent(canvas, &fe); QKeyEvent key(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier, "A", false, 1); QApplication::sendEvent(canvas, &key); QCOMPARE(testObject->mKey, int(Qt::Key_A)); QCOMPARE(testObject->mForwardedKey, int(Qt::Key_A)); QCOMPARE(testObject->mText, QLatin1String("A")); QVERIFY(testObject->mModifiers == Qt::NoModifier); QVERIFY(!key.isAccepted()); testObject->reset(); key = QKeyEvent(QEvent::KeyRelease, Qt::Key_A, Qt::ShiftModifier, "A", false, 1); QApplication::sendEvent(canvas, &key); QCOMPARE(testObject->mKey, int(Qt::Key_A)); QCOMPARE(testObject->mForwardedKey, int(Qt::Key_A)); QCOMPARE(testObject->mText, QLatin1String("A")); QVERIFY(testObject->mModifiers == Qt::ShiftModifier); QVERIFY(key.isAccepted()); testObject->reset(); key = QKeyEvent(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QCOMPARE(testObject->mKey, int(Qt::Key_Return)); QCOMPARE(testObject->mForwardedKey, int(Qt::Key_Return)); QCOMPARE(testObject->mText, QLatin1String("Return")); QVERIFY(testObject->mModifiers == Qt::NoModifier); QVERIFY(key.isAccepted()); delete canvas; delete testObject; } void tst_QmlGraphicsItem::keyNavigation() { QmlView *canvas = new QmlView(0); canvas->setFixedSize(240,320); canvas->setUrl(QUrl("file://" SRCDIR "/data/keynavigation.qml")); canvas->execute(); canvas->show(); qApp->processEvents(); QEvent wa(QEvent::WindowActivate); QApplication::sendEvent(canvas, &wa); QFocusEvent fe(QEvent::FocusIn); QApplication::sendEvent(canvas, &fe); QmlGraphicsItem *item = findItem<QmlGraphicsItem>(canvas->root(), "item1"); QVERIFY(item); QVERIFY(item->hasFocus()); // right QKeyEvent key(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item2"); QVERIFY(item); QVERIFY(item->hasFocus()); // down key = QKeyEvent(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item4"); QVERIFY(item); QVERIFY(item->hasFocus()); // left key = QKeyEvent(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item3"); QVERIFY(item); QVERIFY(item->hasFocus()); // up key = QKeyEvent(QEvent::KeyPress, Qt::Key_Up, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item1"); QVERIFY(item); QVERIFY(item->hasFocus()); } template<typename T> T *tst_QmlGraphicsItem::findItem(QmlGraphicsItem *parent, const QString &objectName) { const QMetaObject &mo = T::staticMetaObject; //qDebug() << parent->QGraphicsObject::children().count() << "children"; for (int i = 0; i < parent->QGraphicsObject::children().count(); ++i) { QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem*>(parent->QGraphicsObject::children().at(i)); if(!item) continue; //qDebug() << "try" << item; if (mo.cast(item) && (objectName.isEmpty() || item->objectName() == objectName)) return static_cast<T*>(item); item = findItem<T>(item, objectName); if (item) return static_cast<T*>(item); } return 0; } QTEST_MAIN(tst_QmlGraphicsItem) #include "tst_qmlgraphicsitem.moc" <commit_msg>Robustify test<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <QtDeclarative/qmlcontext.h> #include <QtDeclarative/qmlview.h> #include <qmlgraphicsitem.h> class tst_QmlGraphicsItem : public QObject { Q_OBJECT public: tst_QmlGraphicsItem(); private slots: void keys(); void keyNavigation(); private: template<typename T> T *findItem(QmlGraphicsItem *parent, const QString &objectName); }; class KeysTestObject : public QObject { Q_OBJECT public: KeysTestObject() : mKey(0), mModifiers(0), mForwardedKey(0) {} void reset() { mKey = 0; mText = QString(); mModifiers = 0; mForwardedKey = 0; } public slots: void keyPress(int key, QString text, int modifiers) { mKey = key; mText = text; mModifiers = modifiers; } void keyRelease(int key, QString text, int modifiers) { mKey = key; mText = text; mModifiers = modifiers; } void forwardedKey(int key) { mForwardedKey = key; } public: int mKey; QString mText; int mModifiers; int mForwardedKey; private: }; tst_QmlGraphicsItem::tst_QmlGraphicsItem() { } void tst_QmlGraphicsItem::keys() { QmlView *canvas = new QmlView(0); canvas->setFixedSize(240,320); canvas->setUrl(QUrl("file://" SRCDIR "/data/keys.qml")); KeysTestObject *testObject = new KeysTestObject; canvas->rootContext()->setContextProperty("keysTestObject", testObject); canvas->execute(); canvas->show(); qApp->processEvents(); QEvent wa(QEvent::WindowActivate); QApplication::sendEvent(canvas, &wa); QFocusEvent fe(QEvent::FocusIn); QApplication::sendEvent(canvas, &fe); QKeyEvent key(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier, "A", false, 1); QApplication::sendEvent(canvas, &key); QCOMPARE(testObject->mKey, int(Qt::Key_A)); QCOMPARE(testObject->mForwardedKey, int(Qt::Key_A)); QCOMPARE(testObject->mText, QLatin1String("A")); QVERIFY(testObject->mModifiers == Qt::NoModifier); QVERIFY(!key.isAccepted()); testObject->reset(); key = QKeyEvent(QEvent::KeyRelease, Qt::Key_A, Qt::ShiftModifier, "A", false, 1); QApplication::sendEvent(canvas, &key); QCOMPARE(testObject->mKey, int(Qt::Key_A)); QCOMPARE(testObject->mForwardedKey, int(Qt::Key_A)); QCOMPARE(testObject->mText, QLatin1String("A")); QVERIFY(testObject->mModifiers == Qt::ShiftModifier); QVERIFY(key.isAccepted()); testObject->reset(); key = QKeyEvent(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QCOMPARE(testObject->mKey, int(Qt::Key_Return)); QCOMPARE(testObject->mForwardedKey, int(Qt::Key_Return)); QCOMPARE(testObject->mText, QLatin1String("Return")); QVERIFY(testObject->mModifiers == Qt::NoModifier); QVERIFY(key.isAccepted()); delete canvas; delete testObject; } void tst_QmlGraphicsItem::keyNavigation() { QmlView *canvas = new QmlView(0); canvas->setFixedSize(240,320); canvas->setUrl(QUrl("file://" SRCDIR "/data/keynavigation.qml")); canvas->execute(); canvas->show(); qApp->processEvents(); QEvent wa(QEvent::WindowActivate); QApplication::sendEvent(canvas, &wa); QFocusEvent fe(QEvent::FocusIn); QApplication::sendEvent(canvas, &fe); QmlGraphicsItem *item = findItem<QmlGraphicsItem>(canvas->root(), "item1"); QVERIFY(item); QVERIFY(item->hasFocus()); // right QKeyEvent key(QEvent::KeyPress, Qt::Key_Right, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item2"); QVERIFY(item); QVERIFY(item->hasFocus()); // down key = QKeyEvent(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item4"); QVERIFY(item); QVERIFY(item->hasFocus()); // left key = QKeyEvent(QEvent::KeyPress, Qt::Key_Left, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item3"); QVERIFY(item); QVERIFY(item->hasFocus()); // up key = QKeyEvent(QEvent::KeyPress, Qt::Key_Up, Qt::NoModifier, "", false, 1); QApplication::sendEvent(canvas, &key); QVERIFY(key.isAccepted()); item = findItem<QmlGraphicsItem>(canvas->root(), "item1"); QVERIFY(item); QVERIFY(item->hasFocus()); } template<typename T> T *tst_QmlGraphicsItem::findItem(QmlGraphicsItem *parent, const QString &objectName) { if (!parent) return 0; const QMetaObject &mo = T::staticMetaObject; //qDebug() << parent->QGraphicsObject::children().count() << "children"; for (int i = 0; i < parent->QGraphicsObject::children().count(); ++i) { QmlGraphicsItem *item = qobject_cast<QmlGraphicsItem*>(parent->QGraphicsObject::children().at(i)); if(!item) continue; //qDebug() << "try" << item; if (mo.cast(item) && (objectName.isEmpty() || item->objectName() == objectName)) return static_cast<T*>(item); item = findItem<T>(item, objectName); if (item) return static_cast<T*>(item); } return 0; } QTEST_MAIN(tst_QmlGraphicsItem) #include "tst_qmlgraphicsitem.moc" <|endoftext|>
<commit_before>#ifndef RPG_HPP #define RPG_HPP #include "Scene.hpp" #include "AnimatedSprite.hpp" #include "Collision.hpp" #include "Utils.hpp" #include <string> #include <vector> #include <ctime> #include <cstdlib> #include <cmath> class RPG: public Scene { public: RPG(std::string _name, SceneManager* mgr, sf::RenderWindow* w) :Scene(_name, mgr, w) {} void loadMap() { for (int i=0; i<mapa.getSize().y; i++) { for (int j=0; j<mapa.getSize().x; j++) { if (mapa.getPixel(i, j)==sf::Color(0, 0, 0)) { tempWall.setPosition(i*tilesize,j*tilesize); spWall.push_back(tempWall); } else if(mapa.getPixel(i,j)==sf::Color(128,32,0)) { tempDoor.setPosition(i*tilesize,j*tilesize); spDoor.push_back(tempDoor); } else { tempGrass.setPosition(i*tilesize,j*tilesize); spGrass.push_back(tempGrass); } if (mapa.getPixel(i, j)==sf::Color(0, 0, 255)) { spTadeusz.setPosition(i*tilesize,j*tilesize); } if (mapa.getPixel(i, j)==sf::Color(255, 0, 0)) { tempEnemy.setPosition(i*tilesize,j*tilesize); spEnemy.push_back(tempEnemy); } if(mapa.getPixel(i, j)==sf::Color(0, 0, 255)) { spWaterfall.setPosition(i*tilesize, j*tilesize); } } } } float distance(sf::Sprite spA, sf::Sprite spB) { return sqrt((spA.getPosition().x-spB.getPosition().x)*(spA.getPosition().x-spB.getPosition().x)+(spA.getPosition().y-spB.getPosition().y)*(spA.getPosition().y-spB.getPosition().y)); } virtual void onSceneLoadToMemory() { if (!font.loadFromFile("files/Carnevalee_Freakshow.ttf")) { std::cout << "cannot load font\n"; } texTadeusz.loadFromFile("files/textures/rpg/playerStand.png"); spTadeusz.setTexture(texTadeusz); spTadeusz.setScale(1, 1); spTadeusz.setOrigin(spTadeusz.getTextureRect().width*0.5,spTadeusz.getTextureRect().height*0.5); texWall.loadFromFile("files/textures/rpg/Wall.png"); tempWall.setTexture(texWall); tempWall.setScale(1, 1); texEnemy.loadFromFile("files/textures/rpg/enemyStand.png"); tempEnemy.setTexture(texEnemy); tempEnemy.setOrigin(tempEnemy.getTextureRect().width*0.5, tempEnemy.getTextureRect().height*0.5); texGrass.loadFromFile("files/textures/rpg/grass.png"); tempGrass.setTexture(texGrass); texDoor.loadFromFile("files/textures/rpg/door.png"); texDoorOpen.loadFromFile("files/textures/rpg/doorOpen.png"); texWaterfall.loadFromFile("files/textures/rpg/Waterfall.png"); spWaterfall.setTexture(texWaterfall); spWaterfall.setScale(4,4); window->setMouseCursorVisible(0); texCrosshair.loadFromFile("files/textures/rpg/crosshair.png"); spCrosshair.setTexture(texCrosshair); spCrosshair.setOrigin(spCrosshair.getTextureRect().height*0.5, spCrosshair.getTextureRect().width*0.5); //attackcircle Attack.setFillColor(sf::Color(0, 0, 0, 0)); Attack.setOutlineThickness(2); Attack.setOutlineColor(sf::Color(250, 150, 100)); Attack.setRadius(50); Attack.setOrigin(Attack.getRadius(), Attack.getRadius()); mapa.loadFromFile("files/maps/rpg/mapa1.png"); loadMap(); } virtual void onSceneActivate() { } void deliverEvent(sf::Event& event) { } virtual void draw(double deltaTime) { spWaterfall.setTextureRect(sf::IntRect( 0, spWaterfall.getTextureRect().height-tilesize-w, spWaterfall.getTextureRect().width, tilesize )); w++; if((texWaterfall.getSize().y-tilesize<w)) w=0; //MOVEMENT if ((sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left))) { offset += sf::Vector2f(-tilesize*0.1, 0); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up))) { offset += sf::Vector2f(0, -tilesize*0.1); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))) { offset += sf::Vector2f(0, tilesize*0.1); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right))) { offset += sf::Vector2f(tilesize*0.1, 0); } spTadeusz.move(offset); //COLLISION for(int i = 0; i<spEnemy.size(); i++) if(Collision::BoundingBoxTest(spTadeusz,spEnemy[i])) spTadeusz.move(-offset); for(int i = 0; i<spWall.size(); i++) if(Collision::BoundingBoxTest(spTadeusz,spWall[i])) spTadeusz.move(-offset);; offset=sf::Vector2f(0, 0); spCrosshair.setPosition(sf::Vector2f(sf::Mouse::getPosition(*window))); //OBRACANIE spTadeusz.setRotation(90+180/M_PI*atan2(sf::Mouse::getPosition(*window).y-spTadeusz.getPosition().y, sf::Mouse::getPosition(*window).x-spTadeusz.getPosition().x)); //SKELETON MOVEMENT for(int i = 0; i < spEnemy.size(); i++) spEnemy[i].move(sf::Vector2f(Utils::randInt(-50,50)*tilesize*0.001,Utils::randInt(-50,50)*tilesize*0.001)); //DOORS for(int i=0; i<spDoor.size(); i++) if(Collision::BoundingBoxTest(spTadeusz,spDoor[i])) spDoor[i].setTexture(texDoorOpen); else spDoor[i].setTexture(texDoor); //DRAW STARTS window->clear(sf::Color()); for(int i = 0; i < spGrass.size(); i++) window->draw(spGrass[i]); for(int i = 0; i < spWall.size(); i++) window->draw(spWall[i]); for(int i = 0; i < spDoor.size(); i++) window->draw(spDoor[i]); for(int i = 0; i < spEnemy.size(); i++) window->draw(spEnemy[i]); window->draw(spWaterfall); window->draw(spCrosshair); window->draw(spTadeusz); //ATTACK if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { Attack.setPosition(spTadeusz.getPosition()); window->draw(Attack); for(int i = spEnemy.size()-1; i>=0; i--) if(distance(spEnemy[i],spTadeusz)<=50) spEnemy.erase(spEnemy.begin()+i); } } protected: sf::Font font; sf::Texture texTadeusz; sf::Sprite spTadeusz; sf::Image mapa; sf::Texture texWall; std::vector <sf::Sprite> spWall; sf::Sprite tempWall; int tilesize = 30; sf::Vector2f offset; sf::Texture texEnemy; std::vector <sf::Sprite> spEnemy; sf::Sprite tempEnemy; sf::Texture texGrass; std::vector <sf::Sprite> spGrass; sf::Sprite tempGrass; int w = 0; sf::Texture texWaterfall; sf::Sprite spWaterfall; sf::Texture texDoor; sf::Texture texDoorOpen; std::vector <sf::Sprite> spDoor; sf::Sprite tempDoor; sf::Texture texCrosshair; sf::Sprite spCrosshair; sf::CircleShape Attack; }; #endif //RPG <commit_msg>mala zmiania<commit_after>#ifndef RPG_HPP #define RPG_HPP #include "Scene.hpp" #include "AnimatedSprite.hpp" #include "Collision.hpp" #include "Utils.hpp" #include <string> #include <vector> #include <ctime> #include <cstdlib> #include <cmath> class RPG: public Scene { public: RPG(std::string _name, SceneManager* mgr, sf::RenderWindow* w) :Scene(_name, mgr, w) {} void loadMap() { for (int i=0; i<mapa.getSize().y; i++) { for (int j=0; j<mapa.getSize().x; j++) { if (mapa.getPixel(i, j)==sf::Color(0, 0, 0)) { tempWall.setPosition(i*tilesize,j*tilesize); spWall.push_back(tempWall); } else if(mapa.getPixel(i,j)==sf::Color(128,32,0)) { tempDoor.setPosition(i*tilesize,j*tilesize); spDoor.push_back(tempDoor); } else { tempGrass.setPosition(i*tilesize,j*tilesize); spGrass.push_back(tempGrass); } if (mapa.getPixel(i, j)==sf::Color(0, 0, 255)) { spTadeusz.setPosition(i*tilesize,j*tilesize); } if (mapa.getPixel(i, j)==sf::Color(255, 0, 0)) { tempEnemy.setPosition(i*tilesize,j*tilesize); spEnemy.push_back(tempEnemy); } if(mapa.getPixel(i, j)==sf::Color(0, 0, 255)) { spWaterfall.setPosition(i*tilesize, j*tilesize); } } } } float distance(sf::Sprite spA, sf::Sprite spB) { return sqrt((spA.getPosition().x-spB.getPosition().x)*(spA.getPosition().x-spB.getPosition().x)+(spA.getPosition().y-spB.getPosition().y)*(spA.getPosition().y-spB.getPosition().y)); } virtual void onSceneLoadToMemory() { if (!font.loadFromFile("files/Carnevalee_Freakshow.ttf")) { std::cout << "cannot load font\n"; } texTadeusz.loadFromFile("files/textures/rpg/playerStand.png"); spTadeusz.setTexture(texTadeusz); spTadeusz.setScale(1, 1); spTadeusz.setOrigin(spTadeusz.getTextureRect().width*0.5,spTadeusz.getTextureRect().height*0.5); texWall.loadFromFile("files/textures/rpg/Wall.png"); tempWall.setTexture(texWall); tempWall.setScale(1, 1); texEnemy.loadFromFile("files/textures/rpg/enemyStand.png"); tempEnemy.setTexture(texEnemy); tempEnemy.setOrigin(tempEnemy.getTextureRect().width*0.5, tempEnemy.getTextureRect().height*0.5); texGrass.loadFromFile("files/textures/rpg/grass.png"); tempGrass.setTexture(texGrass); texDoor.loadFromFile("files/textures/rpg/door.png"); texDoorOpen.loadFromFile("files/textures/rpg/doorOpen.png"); texWaterfall.loadFromFile("files/textures/rpg/Waterfall.png"); texWaterfall.setRepeated(true); spWaterfall.setTexture(texWaterfall); // spWaterfall.setScale(4,4); window->setMouseCursorVisible(0); texCrosshair.loadFromFile("files/textures/rpg/crosshair.png"); spCrosshair.setTexture(texCrosshair); spCrosshair.setOrigin(spCrosshair.getTextureRect().height*0.5, spCrosshair.getTextureRect().width*0.5); //attackcircle Attack.setFillColor(sf::Color(0, 0, 0, 0)); Attack.setOutlineThickness(2); Attack.setOutlineColor(sf::Color(250, 150, 100)); Attack.setRadius(50); Attack.setOrigin(Attack.getRadius(), Attack.getRadius()); mapa.loadFromFile("files/maps/rpg/mapa1.png"); loadMap(); } virtual void onSceneActivate() { } void deliverEvent(sf::Event& event) { } virtual void draw(double deltaTime) { // spWaterfall.setTextureRect(sf::IntRect(0, texWaterfall.getSize().y-2*tilesize-w, texWaterfall.getSize().x, tilesize*2 )); //w++; //if((texWaterfall.getSize().y-2*tilesize<w)) // w=0; spWaterfall.setTextureRect(sf::IntRect(0, -w, texWaterfall.getSize().x, tilesize*2 )); w++; spWaterfall.setColor(sf::Color(255,255,255,Utils::randInt(100,200))); //MOVEMENT if ((sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left))) { offset += sf::Vector2f(-tilesize*0.1, 0); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up))) { offset += sf::Vector2f(0, -tilesize*0.1); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))) { offset += sf::Vector2f(0, tilesize*0.1); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right))) { offset += sf::Vector2f(tilesize*0.1, 0); } spTadeusz.move(offset); //COLLISION for(int i = 0; i<spEnemy.size(); i++) if(Collision::BoundingBoxTest(spTadeusz,spEnemy[i])) spTadeusz.move(-offset); for(int i = 0; i<spWall.size(); i++) if(Collision::BoundingBoxTest(spTadeusz,spWall[i])) spTadeusz.move(-offset);; offset=sf::Vector2f(0, 0); spCrosshair.setPosition(sf::Vector2f(sf::Mouse::getPosition(*window))); //OBRACANIE spTadeusz.setRotation(90+180/M_PI*atan2(sf::Mouse::getPosition(*window).y-spTadeusz.getPosition().y, sf::Mouse::getPosition(*window).x-spTadeusz.getPosition().x)); //SKELETON MOVEMENT for(int i = 0; i < spEnemy.size(); i++) spEnemy[i].move(sf::Vector2f(Utils::randInt(-50,50)*tilesize*0.001,Utils::randInt(-50,50)*tilesize*0.001)); //DOORS for(int i=0; i<spDoor.size(); i++) if(Collision::BoundingBoxTest(spTadeusz,spDoor[i])) spDoor[i].setTexture(texDoorOpen); else spDoor[i].setTexture(texDoor); //DRAW STARTS window->clear(sf::Color()); for(int i = 0; i < spGrass.size(); i++) window->draw(spGrass[i]); for(int i = 0; i < spWall.size(); i++) window->draw(spWall[i]); for(int i = 0; i < spDoor.size(); i++) window->draw(spDoor[i]); for(int i = 0; i < spEnemy.size(); i++) window->draw(spEnemy[i]); window->draw(spWaterfall); window->draw(spCrosshair); window->draw(spTadeusz); //ATTACK if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { Attack.setPosition(spTadeusz.getPosition()); window->draw(Attack); for(int i = spEnemy.size()-1; i>=0; i--) if(distance(spEnemy[i],spTadeusz)<=50) spEnemy.erase(spEnemy.begin()+i); } } protected: sf::Font font; sf::Texture texTadeusz; sf::Sprite spTadeusz; sf::Image mapa; sf::Texture texWall; std::vector <sf::Sprite> spWall; sf::Sprite tempWall; int tilesize = 30; sf::Vector2f offset; sf::Texture texEnemy; std::vector <sf::Sprite> spEnemy; sf::Sprite tempEnemy; sf::Texture texGrass; std::vector <sf::Sprite> spGrass; sf::Sprite tempGrass; int w = 0; sf::Texture texWaterfall; sf::Sprite spWaterfall; sf::Texture texDoor; sf::Texture texDoorOpen; std::vector <sf::Sprite> spDoor; sf::Sprite tempDoor; sf::Texture texCrosshair; sf::Sprite spCrosshair; sf::CircleShape Attack; }; #endif //RPG <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// #include <ResourceManager/ResourceManager.hpp> #include <ResourceManager/BaseResource.hpp> #include <ResourceManager/LuaParser.hpp> #include <string> #include <vector> namespace rm { //////////////////////////////////////////////////////////// /// Initialise static members //////////////////////////////////////////////////////////// ResourceLookup ResourceManager::resources = {}; ResourceLookup ResourceManager::errorResources = {}; ResourceQueue ResourceManager::loadingQueue = {}; ResourceQueue ResourceManager::unloadQueue = {}; ResourceQueue ResourceManager::reloadQueue = {}; bool ResourceManager::useNullForErrorRes = true; LoadCompleteCallback ResourceManager::loadCompleteCallback = nullptr; enum class LoadMode { Queue, Block, }; //////////////////////////////////////////////////////////// /// Function definitions //////////////////////////////////////////////////////////// void ResourceManager::unloadResource(const std::string& name, LoadMode mode) { // Checking if resource exists in resources if (resources.find(name) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(name)->second; // If the resource has to be removed immediately if(mode == LoadMode::Block) { // Log what resources were unloaded Logger::logMessage("Unloading Resource: ", resources.find(name)); // Change the status of the BaseResource pointer->setIsLoaded(false); // Unload the BaseResource pointer->unload(); } else { // Send to unloadQueue list unloadQueue.push(pointer); } return; } return; } void ResourceManager::reloadResource(const std::string& name) { ResourcePtr res = nullptr; // Check if resource exists in resource map if (resources.find(name) != resources.end()) { // Set resource pointer res = resources[name]; } else { Logger::logMessage("Reload resource warning: Resource not already loaded"); // Create new resource anyway //loadingQueue.push(res); // Not quire sure how to handle this/if we're allowing them to load anyway } // Send to reloadQueue reloadQueue.push(res); // Must appropriately set isLoaded in resource // Should it even change the state of isLoaded, since it will be loaded until it hits the queue? } void ResourceManager::initPack(const std::string& path) { //How do you check if a string is a valid file path? Does this even need to be checked? /* if(path is not a valid filepath) { return error? } */ //Get a list of data from the resource pack lua table ResourceDataList list = LuaParser::parsePack(path); //iterate through the list and create a new resource if one does not already exist. for(ResourceDataList::iterator iter = list.begin(); iter != list.end(); iter++) { if(resources.find(path)==resources.end) { ResourcePtr res = ResourceFactory::createResource(iter->path, iter->type); res->setAlias(iter->alias); resources.insert({iter->alias, res}); //return success? } else { //return error (already exists)? } } } void ResourceManager::loadPack(const std::string& path, LoadMode mode) { // Create a list from the parsePack ResourceDataList list = LuaParser::parsePack(path); // Iterate through the list for (ResourceDataList::iterator var = list.begin; var != list.end; ++var) { // Checking if resource exists in resources if (resources.find(var->alias) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Checking if the resource is not loaded if (pointer->isLoaded() == false) { // If the resource has to be loaded immediately if (mode == LoadMode::Block) { // Log what resources were unloaded Logger::logMessage("Loading Resource: ", resources.find(var->alias)); // Change the status of the BaseResource pointer->setIsLoaded(true); // Unload the BaseResource pointer->load(); } else { // Send to unloadQueue list loadingQueue.push(pointer); } } } } return; } void ResourceManager::unloadPack(const std::string& path, LoadMode mode) { // Create a list from the parsePack ResourceDataList list = LuaParser::parsePack(path); // Iterate through the list for (ResourceDataList::iterator var = list.begin; var != list.end; ++var) { // Checking if resource exists in resources if (resources.find(var->alias) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Checking if the resource is loaded if (pointer->isLoaded() == true) { // If the resource has to be unloaded immediately if (mode == LoadMode::Block) { // Log what resources were unloaded Logger::logMessage("Loading Resource: ", resources.find(var->alias)); // Change the status of the BaseResource pointer->setIsLoaded(false); // Unload the BaseResource pointer->unload(); } else { // Send to unloadQueue list unloadQueue.push(pointer); } } } } return; } void ResourceManager::reloadPack(const std::string& path) { // Create a list from the parsePack ResourceDataList list = LuaParser::parsePack(path); // Iterate through the list for (ResourceDataList::iterator var = list.begin; var != list.end; ++var) { // Assign the alias to a throw away string std::string name = var->alias; // Checking if resource exists in resource map if (resources.find(name) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr res = resources.find(name)->second; // Send to reloadQueue reloadQueue.push(res); } else { Logger::logMessage("Reload resource warning: Resource not already loaded"); // Create new resource anyway //loadingQueue.push(res); // Not quire sure how to handle this/if we're allowing them to load anyway } } } void ResourceManager::switchPack(const std::string& fromPath, const std::string& toPath) { // Create a list from the parsePack for the current pack ResourceDataList from = LuaParser::parsePack(fromPath); // Create a list from the parsePack for the future Pack ResourceDataList tolist = LuaParser::parsePack(toPath); // Create a string vector to hold the common resources std::vector<std::string> common; // Load the future pack for (ResourceDataList::iterator var = tolist.begin; var != tolist.end; ++var) { // Checking if resource exists in resources if (resources.find(var->alias) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Checking if the resource is not loaded if (pointer->isLoaded() == false) { // Change the status of the BaseResource pointer->setIsLoaded(true); // Send to unloadQueue list loadingQueue.push(pointer); } else { // Add the name to the vector common.push_back(var->alias); } } } // Iterate through the old Pack and remove the Resources that are not common to the pack and the vector for (ResourceDataList::iterator var = from.begin; var != from.end; ++var) { // Checking if resource is common to the string vector if (resources.find(var->alias) != resources.end()) { if (std::find(common.begin(), common.end(), resources.find(var->alias) != common.end)) { // The two entries are common - do nothing } else { // The two entries do not match - unload the old entry // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Send to unloadQueue list loadingQueue.push(pointer); } } } } void ResourceManager::init(bool _useNullForErrorRes) { useNullForErrorRes = _useNullForErrorRes; if(!useNullForErrorRes) { // initPack("ResMan_DefaultError_Resources\ErrorResource_LuaFile.txt"); } } void ResourceManager::update() { loadFromQueue(); unloadFromQueue(); reloadFromQueue(); } void ResourceManager::cleanupUnused() { // run for each resource in list for(auto& r : resources) { // if the resource pointer is unique if(r.second.unique()) { // Log what resources were unloaded Logger::logMessage("Unloading Unused Resource: ", r.first); // Change resource status to false r.second->setIsLoaded(false); // unload resource r.second->unload(); } } } bool ResourceManager::isLoading() { return getNumToLoad() > 0; } size_t ResourceManager::getNumToLoad()//ResourceManager::getNumToLoad() { return loadingQueue.size(); } ResourceList ResourceManager::listAll() { // create a temp list to add pointers ResourceList temp; // iterate through and add each pointer to the temp list for (ResourceLookup::iterator it = resources.begin; it != resources.end; ++it) { temp.push_back(it->second); } return temp; } size_t ResourceManager::getNumResources() { return resources.size(); } void ResourceManager::setLoadCompleteCallback(LoadCompleteCallback callback) { loadCompleteCallback = callback; } void ResourceManager::loadFromQueue() { while (loadingQueue.size() > 0) { // Check First res in the queue auto frontRes = loadingQueue.front(); // Check to see if the resource is already loaded. if (frontRes->isLoaded()) { // If its loaded delete from queue // Allow for another resource to be loaded if there are still l more in the queue. loadingQueue.pop(); } else { // Load the first resource and check if any errors if (frontRes->load()) { // Set resource to is loaded frontRes->setIsLoaded(true); // Remove from loading queue loadingQueue.pop(); } else { // Log Error Logger::logMessage("Load Resource Failed: ", frontRes->getAlias); } // Send load complete call back once the last item is loaded. if (loadingQueue.size() == 0) { loadCompleteCallback(); } // break from loop so only one resource is loaded at a time. break; } } } void ResourceManager::unloadFromQueue() { // Only run when queue is > 0 while (unloadQueue.size() > 0) { // Check First res in the queue auto frontRes = unloadQueue.front(); // Check to see if the resource is already unloaded. if (!frontRes->isLoaded()) { // If its unloaded delete from queue // Allow for another resource to be unloaded if there are still l more in the queue. unloadQueue.pop(); } else { // Load the first resource and check if any errors if (frontRes->unload()) { // Set resource to is unloaded frontRes->setIsLoaded(false); // Remove from unloading queue unloadQueue.pop(); } else { // Log Error Logger::logMessage("Unload Resource Failed: ", frontRes->getAlias); } // break from loop so only one resource is unloaded at a time. break; } } } void ResourceManager::reloadFromQueue() { if (reloadQueue.size() > 0) { // Check First res in the queue auto frontRes = reloadQueue.front(); // Load the first resource and check if any errors if (frontRes->reload()) { // Remove from reloading Queue reloadQueue.pop(); } else { // Log Error Logger::logMessage("Reload Resource Failed: ", frontRes->getAlias); } } } } // namespace rm <commit_msg>Fixed emum error in ResMan.cpp<commit_after>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// #include <ResourceManager/ResourceManager.hpp> #include <ResourceManager/BaseResource.hpp> #include <ResourceManager/LuaParser.hpp> #include <string> #include <vector> namespace rm { //////////////////////////////////////////////////////////// /// Initialise static members //////////////////////////////////////////////////////////// ResourceLookup ResourceManager::resources = {}; ResourceLookup ResourceManager::errorResources = {}; ResourceQueue ResourceManager::loadingQueue = {}; ResourceQueue ResourceManager::unloadQueue = {}; ResourceQueue ResourceManager::reloadQueue = {}; bool ResourceManager::useNullForErrorRes = true; LoadCompleteCallback ResourceManager::loadCompleteCallback = nullptr; //////////////////////////////////////////////////////////// /// Function definitions //////////////////////////////////////////////////////////// void ResourceManager::unloadResource(const std::string& name, LoadMode mode) { // Checking if resource exists in resources if (resources.find(name) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(name)->second; // If the resource has to be removed immediately if(mode == LoadMode::Block) { // Log what resources were unloaded Logger::logMessage("Unloading Resource: ", resources.find(name)); // Change the status of the BaseResource pointer->setIsLoaded(false); // Unload the BaseResource pointer->unload(); } else { // Send to unloadQueue list unloadQueue.push(pointer); } return; } return; } void ResourceManager::reloadResource(const std::string& name) { ResourcePtr res = nullptr; // Check if resource exists in resource map if (resources.find(name) != resources.end()) { // Set resource pointer res = resources[name]; } else { Logger::logMessage("Reload resource warning: Resource not already loaded"); // Create new resource anyway //loadingQueue.push(res); // Not quire sure how to handle this/if we're allowing them to load anyway } // Send to reloadQueue reloadQueue.push(res); // Must appropriately set isLoaded in resource // Should it even change the state of isLoaded, since it will be loaded until it hits the queue? } void ResourceManager::initPack(const std::string& path) { //How do you check if a string is a valid file path? Does this even need to be checked? /* if(path is not a valid filepath) { return error? } */ //Get a list of data from the resource pack lua table ResourceDataList list = LuaParser::parsePack(path); //iterate through the list and create a new resource if one does not already exist. for(ResourceDataList::iterator iter = list.begin(); iter != list.end(); iter++) { if(resources.find(path)==resources.end) { ResourcePtr res = ResourceFactory::createResource(iter->path, iter->type); res->setAlias(iter->alias); resources.insert({iter->alias, res}); //return success? } else { //return error (already exists)? } } } void ResourceManager::loadPack(const std::string& path, LoadMode mode) { // Create a list from the parsePack ResourceDataList list = LuaParser::parsePack(path); // Iterate through the list for (ResourceDataList::iterator var = list.begin; var != list.end; ++var) { // Checking if resource exists in resources if (resources.find(var->alias) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Checking if the resource is not loaded if (pointer->isLoaded() == false) { // If the resource has to be loaded immediately if (mode == LoadMode::Block) { // Log what resources were unloaded Logger::logMessage("Loading Resource: ", resources.find(var->alias)); // Change the status of the BaseResource pointer->setIsLoaded(true); // Unload the BaseResource pointer->load(); } else { // Send to unloadQueue list loadingQueue.push(pointer); } } } } return; } void ResourceManager::unloadPack(const std::string& path, LoadMode mode) { // Create a list from the parsePack ResourceDataList list = LuaParser::parsePack(path); // Iterate through the list for (ResourceDataList::iterator var = list.begin; var != list.end; ++var) { // Checking if resource exists in resources if (resources.find(var->alias) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Checking if the resource is loaded if (pointer->isLoaded() == true) { // If the resource has to be unloaded immediately if (mode == LoadMode::Block) { // Log what resources were unloaded Logger::logMessage("Loading Resource: ", resources.find(var->alias)); // Change the status of the BaseResource pointer->setIsLoaded(false); // Unload the BaseResource pointer->unload(); } else { // Send to unloadQueue list unloadQueue.push(pointer); } } } } return; } void ResourceManager::reloadPack(const std::string& path) { // Create a list from the parsePack ResourceDataList list = LuaParser::parsePack(path); // Iterate through the list for (ResourceDataList::iterator var = list.begin; var != list.end; ++var) { // Assign the alias to a throw away string std::string name = var->alias; // Checking if resource exists in resource map if (resources.find(name) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr res = resources.find(name)->second; // Send to reloadQueue reloadQueue.push(res); } else { Logger::logMessage("Reload resource warning: Resource not already loaded"); // Create new resource anyway //loadingQueue.push(res); // Not quire sure how to handle this/if we're allowing them to load anyway } } } void ResourceManager::switchPack(const std::string& fromPath, const std::string& toPath) { // Create a list from the parsePack for the current pack ResourceDataList from = LuaParser::parsePack(fromPath); // Create a list from the parsePack for the future Pack ResourceDataList tolist = LuaParser::parsePack(toPath); // Create a string vector to hold the common resources std::vector<std::string> common; // Load the future pack for (ResourceDataList::iterator var = tolist.begin; var != tolist.end; ++var) { // Checking if resource exists in resources if (resources.find(var->alias) != resources.end()) { // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Checking if the resource is not loaded if (pointer->isLoaded() == false) { // Change the status of the BaseResource pointer->setIsLoaded(true); // Send to unloadQueue list loadingQueue.push(pointer); } else { // Add the name to the vector common.push_back(var->alias); } } } // Iterate through the old Pack and remove the Resources that are not common to the pack and the vector for (ResourceDataList::iterator var = from.begin; var != from.end; ++var) { // Checking if resource is common to the string vector if (resources.find(var->alias) != resources.end()) { if (std::find(common.begin(), common.end(), resources.find(var->alias) != common.end)) { // The two entries are common - do nothing } else { // The two entries do not match - unload the old entry // Assigns a new pointer to the key for the resource ResourcePtr pointer = resources.find(var->alias)->second; // Send to unloadQueue list loadingQueue.push(pointer); } } } } void ResourceManager::init(bool _useNullForErrorRes) { useNullForErrorRes = _useNullForErrorRes; if(!useNullForErrorRes) { // initPack("ResMan_DefaultError_Resources\ErrorResource_LuaFile.txt"); } } void ResourceManager::update() { loadFromQueue(); unloadFromQueue(); reloadFromQueue(); } void ResourceManager::cleanupUnused() { // run for each resource in list for(auto& r : resources) { // if the resource pointer is unique if(r.second.unique()) { // Log what resources were unloaded Logger::logMessage("Unloading Unused Resource: ", r.first); // Change resource status to false r.second->setIsLoaded(false); // unload resource r.second->unload(); } } } bool ResourceManager::isLoading() { return getNumToLoad() > 0; } size_t ResourceManager::getNumToLoad()//ResourceManager::getNumToLoad() { return loadingQueue.size(); } ResourceList ResourceManager::listAll() { // create a temp list to add pointers ResourceList temp; // iterate through and add each pointer to the temp list for (ResourceLookup::iterator it = resources.begin; it != resources.end; ++it) { temp.push_back(it->second); } return temp; } size_t ResourceManager::getNumResources() { return resources.size(); } void ResourceManager::setLoadCompleteCallback(LoadCompleteCallback callback) { loadCompleteCallback = callback; } void ResourceManager::loadFromQueue() { while (loadingQueue.size() > 0) { // Check First res in the queue auto frontRes = loadingQueue.front(); // Check to see if the resource is already loaded. if (frontRes->isLoaded()) { // If its loaded delete from queue // Allow for another resource to be loaded if there are still l more in the queue. loadingQueue.pop(); } else { // Load the first resource and check if any errors if (frontRes->load()) { // Set resource to is loaded frontRes->setIsLoaded(true); // Remove from loading queue loadingQueue.pop(); } else { // Log Error Logger::logMessage("Load Resource Failed: ", frontRes->getAlias); } // Send load complete call back once the last item is loaded. if (loadingQueue.size() == 0) { loadCompleteCallback(); } // break from loop so only one resource is loaded at a time. break; } } } void ResourceManager::unloadFromQueue() { // Only run when queue is > 0 while (unloadQueue.size() > 0) { // Check First res in the queue auto frontRes = unloadQueue.front(); // Check to see if the resource is already unloaded. if (!frontRes->isLoaded()) { // If its unloaded delete from queue // Allow for another resource to be unloaded if there are still l more in the queue. unloadQueue.pop(); } else { // Load the first resource and check if any errors if (frontRes->unload()) { // Set resource to is unloaded frontRes->setIsLoaded(false); // Remove from unloading queue unloadQueue.pop(); } else { // Log Error Logger::logMessage("Unload Resource Failed: ", frontRes->getAlias); } // break from loop so only one resource is unloaded at a time. break; } } } void ResourceManager::reloadFromQueue() { if (reloadQueue.size() > 0) { // Check First res in the queue auto frontRes = reloadQueue.front(); // Load the first resource and check if any errors if (frontRes->reload()) { // Remove from reloading Queue reloadQueue.pop(); } else { // Log Error Logger::logMessage("Reload Resource Failed: ", frontRes->getAlias); } } } } // namespace rm <|endoftext|>
<commit_before>#pragma once #include <string> #include <fstream> #include <string> #include <sstream> #include <vector> //#include <regex> #include <Grappa.hpp> #include <Cache.hpp> #include <ParallelLoop.hpp> #include "Tuple.hpp" #include "grappa/graph.hpp" DECLARE_string(relations); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } /// Read tuples of format /// src dst /// /// create as array of Tuple void readEdges( std::string fn, GlobalAddress<Tuple> tuples, uint64_t numTuples ) { std::ifstream testfile(fn); CHECK( testfile.is_open() ); // shared by the local tasks reading the file int fin = 0; // synchronous IO with asynchronous write Grappa::forall_here<1>(0, numTuples, [tuples,numTuples,&fin,&testfile](int64_t s, int64_t n) { std::string line; for (int ignore=s; ignore<s+n; ignore++) { CHECK( testfile.good() ); std::getline( testfile, line ); int myindex = fin++; Incoherent<Tuple>::WO lr(tuples+myindex, 1); std::vector<std::string> tokens = split( line, '\t' ); VLOG(5) << tokens[0] << "->" << tokens[1]; (*lr).columns[0] = std::stoi(tokens[0]); (*lr).columns[1] = std::stoi(tokens[1]); } }); CHECK( fin == numTuples ); testfile.close(); } /// Read tuples of format /// src dst /// /// create as tuple_graph tuple_graph readEdges( std::string fn, int64_t numTuples ) { std::ifstream testfile(fn, std::ifstream::in); CHECK( testfile.is_open() ); // shared by the local tasks reading the file int64_t fin = 0; auto edges = Grappa::global_alloc<packed_edge>(numTuples); // token delimiter // std::regex rgx("\\s+"); // synchronous IO with asynchronous write Grappa::forall_here<&Grappa::impl::local_gce, 1>(0, numTuples, [edges,numTuples,&fin,&testfile](int64_t s, int64_t n) { std::string line; for (int ignore=s; ignore<s+n; ignore++) { CHECK( testfile.good() ); std::getline( testfile, line ); // parse and create the edge // c++11 but NOT SUPPORTED/broken in gcc4.7.2 // std::regex_token_iterator<std::string::iterator> iter(line.begin(), line.end(), // rgx, -1); // -1 = matches as splitters // auto src = std::stoi(*iter); iter++; // auto dst = std::stoi(*iter); std::stringstream ss(line); std::string buf; ss >> buf; auto src = std::stoi(buf); ss >> buf; auto dst = std::stoi(buf); VLOG(5) << src << "->" << dst; packed_edge pe; write_edge(&pe, src, dst); // write edge to location int myindex = fin++; Grappa::delegate::write<async>(edges+myindex, pe); } }); CHECK( fin == numTuples ); testfile.close(); tuple_graph tg { edges, numTuples }; return tg; } template <typename T> GlobalAddress<T> readTuples( std::string fn, int64_t numTuples ) { std::string path = FLAGS_relations+"/"+fn; std::ifstream testfile(path, std::ifstream::in); CHECK( testfile.is_open() ) << path << " failed to open"; // shared by the local tasks reading the file int64_t fin = 0; auto tuples = Grappa::global_alloc<T>(numTuples); // token delimiter // std::regex rgx("\\s+"); // synchronous IO with asynchronous write Grappa::forall_here<&Grappa::impl::local_gce, 1>(0, numTuples, [tuples,numTuples,&fin,&testfile](int64_t s, int64_t n) { std::string line; for (int ignore=s; ignore<s+n; ignore++) { CHECK( testfile.good() ); std::getline( testfile, line ); std::vector<int64_t> readFields; // TODO: compiler should use catalog to statically insert num fields std::stringstream ss(line); while (true) { std::string buf; ss >> buf; if (buf.compare("") == 0) break; auto f = std::stoi(buf); readFields.push_back(f); } T val( readFields ); VLOG(5) << val; // write edge to location int myindex = fin++; Grappa::delegate::write<async>(tuples+myindex, val); } }); CHECK( fin == numTuples ); testfile.close(); return tuples; } <commit_msg>parallel file io<commit_after>#pragma once #include <string> #include <fstream> #include <string> #include <sstream> #include <vector> //#include <regex> #include <Grappa.hpp> #include <Cache.hpp> #include <ParallelLoop.hpp> #include "Tuple.hpp" #include "grappa/graph.hpp" DECLARE_string(relations); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } /// Read tuples of format /// src dst /// /// create as array of Tuple void readEdges( std::string fn, GlobalAddress<Tuple> tuples, uint64_t numTuples ) { std::ifstream testfile(fn); CHECK( testfile.is_open() ); // shared by the local tasks reading the file int fin = 0; // synchronous IO with asynchronous write Grappa::forall_here<1>(0, numTuples, [tuples,numTuples,&fin,&testfile](int64_t s, int64_t n) { std::string line; for (int ignore=s; ignore<s+n; ignore++) { CHECK( testfile.good() ); std::getline( testfile, line ); int myindex = fin++; Incoherent<Tuple>::WO lr(tuples+myindex, 1); std::vector<std::string> tokens = split( line, '\t' ); VLOG(5) << tokens[0] << "->" << tokens[1]; (*lr).columns[0] = std::stoi(tokens[0]); (*lr).columns[1] = std::stoi(tokens[1]); } }); CHECK( fin == numTuples ); testfile.close(); } /// Read tuples of format /// src dst /// /// create as tuple_graph tuple_graph readEdges( std::string fn, int64_t numTuples ) { std::ifstream testfile(fn, std::ifstream::in); CHECK( testfile.is_open() ); // shared by the local tasks reading the file int64_t fin = 0; auto edges = Grappa::global_alloc<packed_edge>(numTuples); // token delimiter // std::regex rgx("\\s+"); // synchronous IO with asynchronous write Grappa::forall_here<&Grappa::impl::local_gce, 1>(0, numTuples, [edges,numTuples,&fin,&testfile](int64_t s, int64_t n) { std::string line; for (int ignore=s; ignore<s+n; ignore++) { CHECK( testfile.good() ); std::getline( testfile, line ); // parse and create the edge // c++11 but NOT SUPPORTED/broken in gcc4.7.2 // std::regex_token_iterator<std::string::iterator> iter(line.begin(), line.end(), // rgx, -1); // -1 = matches as splitters // auto src = std::stoi(*iter); iter++; // auto dst = std::stoi(*iter); std::stringstream ss(line); std::string buf; ss >> buf; auto src = std::stoi(buf); ss >> buf; auto dst = std::stoi(buf); VLOG(5) << src << "->" << dst; packed_edge pe; write_edge(&pe, src, dst); // write edge to location int myindex = fin++; Grappa::delegate::write<async>(edges+myindex, pe); } }); CHECK( fin == numTuples ); testfile.close(); tuple_graph tg { edges, numTuples }; return tg; } template <typename T> Relation<T> readTuplesUnordered( std::string fn ) { /* std::string metadata_path = FLAGS_relations+"/"+fn+"."+metadata; //TODO replace such metadatafiles with a real catalog std::ifstream metadata_file(metadata_path, std::ifstream::in); CHECK( metadata_file.is_open() ) << metadata_path << " failed to open"; int64_t numcols; metadata_file >> numcols; */ // binary; TODO: factor out to allow other formats like fixed-line length ascii std::string data_path = FLAGS_relations+"/"+fn; size_t file_size = fs::file_size( path ); size_t ntuples = file_size / row_size_bytes; CHECK( ntuples * row_size_bytes == file_size ) << "File is ill-formatted; perhaps not all rows have " << numcols << " columns?"; auto tuples = Grappa::global_alloc<T>(numTuples); size_t offset_counter; auto offset_counter_addr = make_global( &offset_counter, Grappa::mycore() ); on_all_cores( [=] { // find my array split auto local_start = tuples.localize(); auto local_end = (tuples+numTuples).localize(); size_t local_count = local_end - local_start; // reserve a file split int64_t offset = Grappa::delegate::fetch_and_add( offset_counter_addr, local_count ) std::ifstream data_file(data_path, std::ifstream::in | std::ios_base::binary); CHECK( data_file.is_open() ) << data_path << " failed to open"; infile.seekg( offset * sizeof(T) ); infile.read( (char*) local_start, local_count * sizeof(T) ) data_file.close(); }); Relation<T> r = { tuples, ntuples }; return r; } template <typename T> GlobalAddress<T> readTuples( std::string fn, int64_t numTuples ) { std::string path = FLAGS_relations+"/"+fn; std::ifstream testfile(path, std::ifstream::in); CHECK( testfile.is_open() ) << path << " failed to open"; // shared by the local tasks reading the file int64_t fin = 0; auto tuples = Grappa::global_alloc<T>(numTuples); // token delimiter // std::regex rgx("\\s+"); // synchronous IO with asynchronous write Grappa::forall_here<&Grappa::impl::local_gce, 1>(0, numTuples, [tuples,numTuples,&fin,&testfile](int64_t s, int64_t n) { std::string line; for (int ignore=s; ignore<s+n; ignore++) { CHECK( testfile.good() ); std::getline( testfile, line ); std::vector<int64_t> readFields; // TODO: compiler should use catalog to statically insert num fields std::stringstream ss(line); while (true) { std::string buf; ss >> buf; if (buf.compare("") == 0) break; auto f = std::stoi(buf); readFields.push_back(f); } T val( readFields ); VLOG(5) << val; // write edge to location int myindex = fin++; Grappa::delegate::write<async>(tuples+myindex, val); } }); CHECK( fin == numTuples ); testfile.close(); return tuples; } <|endoftext|>
<commit_before>extern "C" { #include "../../raspi/i2c/btz_i2c.h" } #include <stdio.h> #include <unistd.h> int main() { printf("Testing raspberry i2c driver\n"); printf("Initializing i2c bus\n"); int result = INIT_I2C(); printf("Init result:%i\n",result); printf("try read register 0 from slave...\n"); char value[2]; result = READ_REGISTER(0x12,0x0,value,2); printf("Read result:%i\n",result); for(int i=0;i<2;i++) { printf("Value @%i:%i\n",i,value[i]); } printf("Read Done.\n"); printf("Try write register\n"); char testData[4]; testData[0] = 0x0; testData[1] = 0x0; testData[2] = 0x0; testData[3] = 0x0; usleep(10 *1000); result = WRITE_REGISTER(0x12,0x0,testData,4); printf("Write resulted:%i",result); printf("try read register 0 from slave...\n"); result = READ_REGISTER(0x12,0x0,value,2); printf("Read result:%i\n",result); for(int i=0;i<2;i++) { printf("Value @%i:%i\n",i,value[i]); } printf("Read Done.\n"); return 1; } <commit_msg>added conversation to int<commit_after>extern "C" { #include "../../raspi/i2c/btz_i2c.h" } #include <stdio.h> #include <unistd.h> int main() { printf("Testing raspberry i2c driver\n"); printf("Initializing i2c bus\n"); int result = INIT_I2C(); printf("Init result:%i\n",result); printf("try read register 0 from slave...\n"); char value[2]; result = READ_REGISTER(0x12,0x0,value,2); printf("Read result:%i\n",result); int intVal = (value[0] | value[1] << 8); for(int i=0;i<2;i++) { printf("Value @%i:%i\n",i,intVal); } printf("Read Done.\n"); printf("Try write register\n"); char testData[4]; testData[0] = 0x0; testData[1] = 0x0; testData[2] = 0x0; testData[3] = 0x0; usleep(10 *1000); result = WRITE_REGISTER(0x12,0x0,testData,4); printf("Write resulted:%i",result); printf("try read register 0 from slave...\n"); result = READ_REGISTER(0x12,0x0,value,2); printf("Read result:%i\n",result); intVal = (value[0] | value[1] << 8); for(int i=0;i<2;i++) { printf("Value @%i:%i\n",i,intVal); } printf("Read Done.\n"); return 1; } <|endoftext|>
<commit_before>/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ #include "platform_display_text.hpp" #include <GG/adobe/dictionary.hpp> #include <GG/adobe/string.hpp> #include <GG/adobe/future/widgets/headers/display.hpp> #include <GG/adobe/future/widgets/headers/widget_utils.hpp> #include <GG/adobe/future/widgets/headers/platform_metrics.hpp> #include <GG/TextControl.h> #include <GG/GUI.h> #include <GG/StyleFactory.h> #include <string> #include <cassert> #include <sstream> namespace { std::string field_text(const std::string& label, const adobe::any_regular_t& value, GG::Clr label_color) { std::stringstream result; if (!label.empty()) result << GG::RgbaTag(label_color) << label << "</rgba> "; if (value != adobe::any_regular_t()) { adobe::type_info_t type(value.type_info()); if (type == adobe::type_info<double>() || type == adobe::type_info<bool>() || type == adobe::type_info<adobe::name_t>()) { result << value; } else if (type == adobe::type_info<adobe::array_t>()) { result << '['; const adobe::array_t& array = value.cast<adobe::array_t>(); for (adobe::array_t::const_iterator it = array.begin(), end_it = array.end(); it != end_it; ++it) { result << field_text("", *it, label_color); if (boost::next(it) != end_it) result << ','; } result << ']'; } else if (type == adobe::type_info<adobe::dictionary_t>()) { result << '{'; const adobe::dictionary_t& dictionary = value.cast<adobe::dictionary_t>(); for (adobe::dictionary_t::const_iterator it = dictionary.begin(), end_it = dictionary.end(); it != end_it; ++it) { result << it->first << ": " << field_text("", it->second, label_color); if (boost::next(it) != end_it) result << ','; } result << '}'; } else { result << value.cast<adobe::string_t>(); } } return result.str(); } } namespace adobe { display_text_t::display_text_t(const std::string& name, const std::string& alt_text, int characters, GG::Clr color, GG::Clr label_color) : name_m(name), alt_text_m(alt_text), characters_m(characters), color_m(color), label_color_m(label_color) {} void display_text_t::place(const place_data_t& place_data) { implementation::set_control_bounds(window_m, place_data); } void display_text_t::display(const model_type& value) { assert(window_m); value_m = value; window_m->SetText(field_text(name_m, value_m, label_color_m)); } void display_text_t::measure(extents_t& result) { assert(window_m); boost::shared_ptr<GG::Font> font = implementation::DefaultFont(); extents_t space_extents(metrics::measure_text(std::string(" "), font)); extents_t label_extents(metrics::measure_text(name_m, font)); extents_t characters_extents(metrics::measure_text(std::string(characters_m, '0'), font)); // set up default settings (baseline, etc.) result = space_extents; // set the width to the label width (if any) result.width() = label_extents.width(); // add a guide for the label result.horizontal().guide_set_m.push_back(label_extents.width()); // if there's a label, add space for a space if (label_extents.width() != 0) result.width() += space_extents.width(); // append the character extents (if any) result.width() += characters_extents.width(); // if there are character extents, add space for a space if (characters_extents.width() != 0) result.width() += space_extents.width(); assert(result.horizontal().length_m); } void display_text_t::measure_vertical(extents_t& calculated_horizontal, const place_data_t& placed_horizontal) { assert(window_m); extents_t::slice_t& vert = calculated_horizontal.vertical(); vert.length_m = Value(implementation::DefaultFont()->Lineskip()); vert.guide_set_m.push_back(Value(implementation::DefaultFont()->Ascent())); } void display_text_t::set_label_color(GG::Clr color) { label_color_m = color; display(value_m); } template <> platform_display_type insert<display_text_t>(display_t& display, platform_display_type& parent, display_text_t& element) { element.window_m = implementation::Factory().NewTextControl(GG::X0, GG::Y0, GG::X1, GG::Y1, element.name_m, implementation::DefaultFont(), element.color_m, GG::FORMAT_LEFT | GG::FORMAT_TOP, GG::INTERACTIVE); if (!element.alt_text_m.empty()) implementation::set_control_alt_text(element.window_m, element.alt_text_m); element.color_proxy_m.initialize( boost::bind(&GG::TextControl::SetColor, element.window_m, _1) ); element.label_color_proxy_m.initialize( boost::bind(&display_text_t::set_label_color, &element, _1) ); return display.insert(parent, get_display(element)); } } <commit_msg>Added support for GG::Clr to platform_display_text.<commit_after>/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ #include "platform_display_text.hpp" #include <GG/adobe/dictionary.hpp> #include <GG/adobe/string.hpp> #include <GG/adobe/future/widgets/headers/display.hpp> #include <GG/adobe/future/widgets/headers/widget_utils.hpp> #include <GG/adobe/future/widgets/headers/platform_metrics.hpp> #include <GG/TextControl.h> #include <GG/GUI.h> #include <GG/StyleFactory.h> #include <string> #include <cassert> #include <sstream> namespace { std::string field_text(const std::string& label, const adobe::any_regular_t& value, GG::Clr label_color) { std::stringstream result; if (!label.empty()) result << GG::RgbaTag(label_color) << label << "</rgba> "; if (value != adobe::any_regular_t()) { adobe::type_info_t type(value.type_info()); if (type == adobe::type_info<double>() || type == adobe::type_info<bool>() || type == adobe::type_info<adobe::name_t>()) { result << value; } else if (type == adobe::type_info<adobe::array_t>()) { result << '['; const adobe::array_t& array = value.cast<adobe::array_t>(); for (adobe::array_t::const_iterator it = array.begin(), end_it = array.end(); it != end_it; ++it) { result << field_text("", *it, label_color); if (boost::next(it) != end_it) result << ','; } result << ']'; } else if (type == adobe::type_info<adobe::dictionary_t>()) { result << '{'; const adobe::dictionary_t& dictionary = value.cast<adobe::dictionary_t>(); for (adobe::dictionary_t::const_iterator it = dictionary.begin(), end_it = dictionary.end(); it != end_it; ++it) { result << it->first << ": " << field_text("", it->second, label_color); if (boost::next(it) != end_it) result << ','; } result << '}'; } else if (type == adobe::type_info<GG::Clr>()) { result << "color("; const GG::Clr& color = value.cast<GG::Clr>(); bool previous_element = false; if (color.r) { result << "r: " << static_cast<int>(color.r); previous_element = true; } if (color.g) { if (previous_element) result << ", "; result << "g: " << static_cast<int>(color.g); previous_element = true; } if (color.b) { if (previous_element) result << ", "; result << "b: " << static_cast<int>(color.b); previous_element = true; } if (color.a != 255) { if (previous_element) result << ", "; result << "a: " << static_cast<int>(color.a); } result << ')'; } else { result << value.cast<adobe::string_t>(); } } return result.str(); } } namespace adobe { display_text_t::display_text_t(const std::string& name, const std::string& alt_text, int characters, GG::Clr color, GG::Clr label_color) : name_m(name), alt_text_m(alt_text), characters_m(characters), color_m(color), label_color_m(label_color) {} void display_text_t::place(const place_data_t& place_data) { implementation::set_control_bounds(window_m, place_data); } void display_text_t::display(const model_type& value) { assert(window_m); value_m = value; window_m->SetText(field_text(name_m, value_m, label_color_m)); } void display_text_t::measure(extents_t& result) { assert(window_m); boost::shared_ptr<GG::Font> font = implementation::DefaultFont(); extents_t space_extents(metrics::measure_text(std::string(" "), font)); extents_t label_extents(metrics::measure_text(name_m, font)); extents_t characters_extents(metrics::measure_text(std::string(characters_m, '0'), font)); // set up default settings (baseline, etc.) result = space_extents; // set the width to the label width (if any) result.width() = label_extents.width(); // add a guide for the label result.horizontal().guide_set_m.push_back(label_extents.width()); // if there's a label, add space for a space if (label_extents.width() != 0) result.width() += space_extents.width(); // append the character extents (if any) result.width() += characters_extents.width(); // if there are character extents, add space for a space if (characters_extents.width() != 0) result.width() += space_extents.width(); assert(result.horizontal().length_m); } void display_text_t::measure_vertical(extents_t& calculated_horizontal, const place_data_t& placed_horizontal) { assert(window_m); extents_t::slice_t& vert = calculated_horizontal.vertical(); vert.length_m = Value(implementation::DefaultFont()->Lineskip()); vert.guide_set_m.push_back(Value(implementation::DefaultFont()->Ascent())); } void display_text_t::set_label_color(GG::Clr color) { label_color_m = color; display(value_m); } template <> platform_display_type insert<display_text_t>(display_t& display, platform_display_type& parent, display_text_t& element) { element.window_m = implementation::Factory().NewTextControl(GG::X0, GG::Y0, GG::X1, GG::Y1, element.name_m, implementation::DefaultFont(), element.color_m, GG::FORMAT_LEFT | GG::FORMAT_TOP, GG::INTERACTIVE); if (!element.alt_text_m.empty()) implementation::set_control_alt_text(element.window_m, element.alt_text_m); element.color_proxy_m.initialize( boost::bind(&GG::TextControl::SetColor, element.window_m, _1) ); element.label_color_proxy_m.initialize( boost::bind(&display_text_t::set_label_color, &element, _1) ); return display.insert(parent, get_display(element)); } } <|endoftext|>
<commit_before>#include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <string> #include <sstream> #include <cassert> #include <cmath> // TODO: Replace this as soon as possible with a more modern option // parser interface. #include <getopt.h> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "geometry/RipsExpanderTopDown.hh" #include "persistenceDiagrams/Norms.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "topology/io/Pajek.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; std::string formatOutput( const std::string& prefix, unsigned k, unsigned K ) { std::ostringstream stream; stream << prefix; stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k; stream << ".txt"; return stream.str(); } std::string formatLabel( const std::string label ) { // No whitespace---nothing to do if( label.find( '\t' ) == std::string::npos && label.find( ' ' ) == std::string::npos ) return label; else return "\""+label+"\""; } void usage() { std::cerr << "Usage: clique-persistence-diagram [--invert-weights] [--reverse] FILE K\n" << "\n" << "Calculates the clique persistence diagram for FILE, which is\n" << "supposed to be a weighted graph. The K parameter denotes the\n" << "maximum dimension of a simplex for extracting a clique graph\n" << "and tracking persistence of clique communities.\n\n" << "" << "******************\n" << "Optional arguments\n" << "******************\n" << "\n" << " --centrality : If specified, calculates centralities for\n" << " all vertices. Note that this uses copious\n" << " amounts of time because *all* communities\n" << " need to be extracted and inspected.\n" << "\n" << " --invert-weights: If specified, inverts input weights. This\n" << " is useful if the original weights measure\n" << " the strength of a relationship, and not a\n" << " dissimilarity.\n" << "\n" << " --reverse : Reverses the enumeration order of cliques\n" << " by looking for higher-dimensional cliques\n" << " before enumerating lower-dimensional ones\n" << " instead of the other way around.\n" << "\n\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "centrality" , no_argument , nullptr, 'c' }, { "ignore-empty" , no_argument , nullptr, 'e' }, { "invert-weights", no_argument , nullptr, 'i' }, { "normalize" , no_argument , nullptr, 'n' }, { "reverse" , no_argument , nullptr, 'r' }, { "min-k" , required_argument, nullptr, 'k' }, { nullptr , 0 , nullptr, 0 } }; bool calculateCentrality = false; bool ignoreEmpty = false; bool invertWeights = false; bool normalize = false; bool reverse = false; unsigned minK = 0; int option = 0; while( ( option = getopt_long( argc, argv, "k:ceinr", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'k': minK = unsigned( std::stoul( optarg ) ); break; case 'c': calculateCentrality = true; break; case 'e': ignoreEmpty = true; break; case 'i': invertWeights = true; break; case 'n': normalize = true; break; case 'r': reverse = true; break; default: break; } } if( (argc - optind ) < 2 ) { usage(); return -1; } std::string filename = argv[optind++]; unsigned maxK = static_cast<unsigned>( std::stoul( argv[optind++] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- std::cerr << "* Reading '" << filename << "'..."; // Optional map of node labels. If the graph contains node labels and // I am able to read them, this map will be filled. std::map<VertexType, std::string> labels; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); auto labelMap = reader.getNodeAttribute( "label" ); // Note that this assumes that the labels are convertible to // numbers. // // TODO: Solve this generically? for( auto&& pair : labelMap ) if( !pair.second.empty() ) labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second; if( labels.empty() ) labels.clear(); } else if( aleph::utilities::extension( filename ) == ".net" ) { aleph::topology::io::PajekReader reader; reader( filename, K ); auto labelMap = reader.getLabelMap(); // Note that this assumes that the labels are convertible to // numbers. // // TODO: Solve this generically? for( auto&& pair : labelMap ) if( !pair.second.empty() ) labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second; if( labels.empty() ) labels.clear(); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; DataType maxWeight = std::numeric_limits<DataType>::lowest(); DataType minWeight = std::numeric_limits<DataType>::max(); for( auto&& simplex : K ) { maxWeight = std::max( maxWeight, simplex.data() ); minWeight = std::min( minWeight, simplex.data() ); } if( normalize && maxWeight != minWeight ) { std::cerr << "* Normalizing weights to [0,1]..."; auto range = maxWeight - minWeight; for (auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( ( s.data() - minWeight ) / range ); K.replace( it, s ); } maxWeight = DataType(1); minWeight = DataType(0); std::cerr << "finished\n"; } if( invertWeights ) { std::cerr << "* Inverting filtration weights..."; for( auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( maxWeight - s.data() ); K.replace( it, s ); } std::cerr << "finished\n"; } // Expansion --------------------------------------------------------- std::cerr << "* Expanding simplicial complex to k=" << maxK << "..."; if( reverse ) { aleph::geometry::RipsExpanderTopDown<SimplicialComplex> ripsExpander; auto L = ripsExpander( K, maxK, minK ); K = ripsExpander.assignMaximumWeight( L, K ); } else { aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); } std::cerr << "finished\n" << "* Expanded simplicial complex has " << K.size() << " simplices\n"; K.sort( aleph::filtrations::Data<Simplex>() ); // Stores the accumulated persistence of vertices. Persistence // accumulates if a vertex participates in a clique community. std::map<VertexType, double> accumulatedPersistenceMap; // Stores the number of clique communities a vertex is a part of. // I am using this only for debugging the algorithm. std::map<VertexType, unsigned> numberOfCliqueCommunities; std::vector<double> totalPersistenceValues; totalPersistenceValues.reserve( maxK ); // By traversing the clique graphs in descending order I can be sure // that a graph will be available. Otherwise, in case of a minimum k // parameter and a reverted expansion, only empty clique graphs will // be traversed. for( unsigned k = maxK; k >= 1; k-- ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; if( !ignoreEmpty && C.empty()) { std::cerr << "* Stopping here because no further cliques for processing exist\n"; break; } auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram<Simplex, aleph::traits::PersistencePairingCalculation<aleph::PersistencePairing<VertexType> > >( C ); auto&& pd = std::get<0>( tuple ); auto&& pp = std::get<1>( tuple ); auto&& cs = std::get<2>( tuple ); if( calculateCentrality ) { std::cerr << "* Calculating centrality measure (this may take a very long time!)..."; auto itPoint = pd.begin(); for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair ) { // Skip zero-dimensional persistence pairs. This looks somewhat // wrong but is correct---recall that we are operating on _two_ // iterators at once! // // The persistence pair iterator is 'dumb' and has no knowledge // about the persistence values. Hence, we need the iterator of // the persistence diagram as well. // // Note that the diagram must not be modified for this to work! if( itPoint->x() == itPoint->y() ) { ++itPoint; continue; } SimplicialComplex filteredComplex; { std::vector<Simplex> simplices; if( itPair->second < C.size() ) { simplices.reserve( itPair->second ); std::copy( C.begin() + itPair->first, C.begin() + itPair->second, std::back_inserter( simplices ) ); filteredComplex = SimplicialComplex( simplices.begin(), simplices.end() ); } else filteredComplex = C; } auto uf = calculateConnectedComponents( filteredComplex ); auto desiredRoot = *C.at( itPair->first ).begin(); auto root = uf.find( desiredRoot ); // Normally, this should be a self-assignment, // but in some cases the order of traversal is // slightly different, resulting in unexpected // roots. std::set<VertexType> cliqueVertices; std::vector<VertexType> vertices; uf.get( root, std::back_inserter( vertices ) ); for( auto&& vertex : vertices ) { // Notice that the vertex identifier represents the index // within the filtration of the _original_ complex, hence // I can just access the corresponding simplex that way. auto s = K.at( vertex ); cliqueVertices.insert( s.begin(), s.end() ); } for( auto&& cliqueVertex : cliqueVertices ) { auto persistence = std::isfinite( itPoint->persistence() ) ? std::pow( itPoint->persistence(), 2 ) : std::pow( 2*maxWeight - itPoint->x(), 2 ); accumulatedPersistenceMap[cliqueVertex] += persistence; numberOfCliqueCommunities[cliqueVertex] += 1; } ++itPoint; } std::cerr << "finished\n"; } pd.removeDiagonal(); if( !C.empty() ) { using namespace aleph::utilities; auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK ); std::cerr << "* Storing output in '" << outputFilename << "'...\n"; std::transform( pd.begin(), pd.end(), pd.begin(), [&maxWeight] ( const PersistenceDiagram::Point& p ) { if( !std::isfinite( p.y() ) ) return PersistenceDiagram::Point( p.x(), 2 * maxWeight ); else return PersistenceDiagram::Point( p ); } ); std::ofstream out( outputFilename ); out << "# Original filename: " << filename << "\n"; out << "# k : " << k << "\n"; { auto itPoint = pd.begin(); for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair, ++itPoint ) out << itPoint->x() << "\t" << itPoint->y() << "\t" << cs.at( *C.at( itPair->first ).begin() ) << "\n"; } } } { using namespace aleph::utilities; auto outputFilename = "/tmp/" + stem( basename( filename ) ) + ".txt"; std::cerr << "* Storing accumulated persistence values in '" << outputFilename << "'...\n"; std::ofstream out( outputFilename ); for( auto&& pair : accumulatedPersistenceMap ) out << pair.first << "\t" << pair.second << "\t" << numberOfCliqueCommunities.at(pair.first) << ( labels.empty() ? "" : "\t" + formatLabel( labels.at( pair.first ) ) ) << "\n"; } } <commit_msg>Added progress indicator<commit_after>#include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <string> #include <sstream> #include <cassert> #include <cmath> // TODO: Replace this as soon as possible with a more modern option // parser interface. #include <getopt.h> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "geometry/RipsExpanderTopDown.hh" #include "persistenceDiagrams/Norms.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "topology/io/Pajek.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; std::string formatOutput( const std::string& prefix, unsigned k, unsigned K ) { std::ostringstream stream; stream << prefix; stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k; stream << ".txt"; return stream.str(); } std::string formatLabel( const std::string label ) { // No whitespace---nothing to do if( label.find( '\t' ) == std::string::npos && label.find( ' ' ) == std::string::npos ) return label; else return "\""+label+"\""; } void usage() { std::cerr << "Usage: clique-persistence-diagram [--invert-weights] [--reverse] FILE K\n" << "\n" << "Calculates the clique persistence diagram for FILE, which is\n" << "supposed to be a weighted graph. The K parameter denotes the\n" << "maximum dimension of a simplex for extracting a clique graph\n" << "and tracking persistence of clique communities.\n\n" << "" << "******************\n" << "Optional arguments\n" << "******************\n" << "\n" << " --centrality : If specified, calculates centralities for\n" << " all vertices. Note that this uses copious\n" << " amounts of time because *all* communities\n" << " need to be extracted and inspected.\n" << "\n" << " --invert-weights: If specified, inverts input weights. This\n" << " is useful if the original weights measure\n" << " the strength of a relationship, and not a\n" << " dissimilarity.\n" << "\n" << " --reverse : Reverses the enumeration order of cliques\n" << " by looking for higher-dimensional cliques\n" << " before enumerating lower-dimensional ones\n" << " instead of the other way around.\n" << "\n\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "centrality" , no_argument , nullptr, 'c' }, { "ignore-empty" , no_argument , nullptr, 'e' }, { "invert-weights", no_argument , nullptr, 'i' }, { "normalize" , no_argument , nullptr, 'n' }, { "reverse" , no_argument , nullptr, 'r' }, { "min-k" , required_argument, nullptr, 'k' }, { nullptr , 0 , nullptr, 0 } }; bool calculateCentrality = false; bool ignoreEmpty = false; bool invertWeights = false; bool normalize = false; bool reverse = false; unsigned minK = 0; int option = 0; while( ( option = getopt_long( argc, argv, "k:ceinr", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'k': minK = unsigned( std::stoul( optarg ) ); break; case 'c': calculateCentrality = true; break; case 'e': ignoreEmpty = true; break; case 'i': invertWeights = true; break; case 'n': normalize = true; break; case 'r': reverse = true; break; default: break; } } if( (argc - optind ) < 2 ) { usage(); return -1; } std::string filename = argv[optind++]; unsigned maxK = static_cast<unsigned>( std::stoul( argv[optind++] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- std::cerr << "* Reading '" << filename << "'..."; // Optional map of node labels. If the graph contains node labels and // I am able to read them, this map will be filled. std::map<VertexType, std::string> labels; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); auto labelMap = reader.getNodeAttribute( "label" ); // Note that this assumes that the labels are convertible to // numbers. // // TODO: Solve this generically? for( auto&& pair : labelMap ) if( !pair.second.empty() ) labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second; if( labels.empty() ) labels.clear(); } else if( aleph::utilities::extension( filename ) == ".net" ) { aleph::topology::io::PajekReader reader; reader( filename, K ); auto labelMap = reader.getLabelMap(); // Note that this assumes that the labels are convertible to // numbers. // // TODO: Solve this generically? for( auto&& pair : labelMap ) if( !pair.second.empty() ) labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second; if( labels.empty() ) labels.clear(); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; DataType maxWeight = std::numeric_limits<DataType>::lowest(); DataType minWeight = std::numeric_limits<DataType>::max(); for( auto&& simplex : K ) { maxWeight = std::max( maxWeight, simplex.data() ); minWeight = std::min( minWeight, simplex.data() ); } if( normalize && maxWeight != minWeight ) { std::cerr << "* Normalizing weights to [0,1]..."; auto range = maxWeight - minWeight; for (auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( ( s.data() - minWeight ) / range ); K.replace( it, s ); } maxWeight = DataType(1); minWeight = DataType(0); std::cerr << "finished\n"; } if( invertWeights ) { std::cerr << "* Inverting filtration weights..."; for( auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( maxWeight - s.data() ); K.replace( it, s ); } std::cerr << "finished\n"; } // Expansion --------------------------------------------------------- std::cerr << "* Expanding simplicial complex to k=" << maxK << "..."; if( reverse ) { aleph::geometry::RipsExpanderTopDown<SimplicialComplex> ripsExpander; auto L = ripsExpander( K, maxK, minK ); K = ripsExpander.assignMaximumWeight( L, K ); } else { aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); } std::cerr << "finished\n" << "* Expanded simplicial complex has " << K.size() << " simplices\n"; K.sort( aleph::filtrations::Data<Simplex>() ); // Stores the accumulated persistence of vertices. Persistence // accumulates if a vertex participates in a clique community. std::map<VertexType, double> accumulatedPersistenceMap; // Stores the number of clique communities a vertex is a part of. // I am using this only for debugging the algorithm. std::map<VertexType, unsigned> numberOfCliqueCommunities; std::vector<double> totalPersistenceValues; totalPersistenceValues.reserve( maxK ); // By traversing the clique graphs in descending order I can be sure // that a graph will be available. Otherwise, in case of a minimum k // parameter and a reverted expansion, only empty clique graphs will // be traversed. for( unsigned k = maxK; k >= 1; k-- ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; if( !ignoreEmpty && C.empty()) { std::cerr << "* Stopping here because no further cliques for processing exist\n"; break; } auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram<Simplex, aleph::traits::PersistencePairingCalculation<aleph::PersistencePairing<VertexType> > >( C ); auto&& pd = std::get<0>( tuple ); auto&& pp = std::get<1>( tuple ); auto&& cs = std::get<2>( tuple ); if( calculateCentrality ) { std::cerr << "* Calculating centrality measure (this may take a very long time!)..."; auto progress = 0.f; auto itPoint = pd.begin(); for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair ) { // Skip zero-dimensional persistence pairs. This looks somewhat // wrong but is correct---recall that we are operating on _two_ // iterators at once! // // The persistence pair iterator is 'dumb' and has no knowledge // about the persistence values. Hence, we need the iterator of // the persistence diagram as well. // // Note that the diagram must not be modified for this to work! if( itPoint->x() == itPoint->y() ) { ++itPoint; continue; } SimplicialComplex filteredComplex; { std::vector<Simplex> simplices; if( itPair->second < C.size() ) { simplices.reserve( itPair->second ); std::copy( C.begin() + itPair->first, C.begin() + itPair->second, std::back_inserter( simplices ) ); filteredComplex = SimplicialComplex( simplices.begin(), simplices.end() ); } else filteredComplex = C; } auto uf = calculateConnectedComponents( filteredComplex ); auto desiredRoot = *C.at( itPair->first ).begin(); auto root = uf.find( desiredRoot ); // Normally, this should be a self-assignment, // but in some cases the order of traversal is // slightly different, resulting in unexpected // roots. std::set<VertexType> cliqueVertices; std::vector<VertexType> vertices; uf.get( root, std::back_inserter( vertices ) ); for( auto&& vertex : vertices ) { // Notice that the vertex identifier represents the index // within the filtration of the _original_ complex, hence // I can just access the corresponding simplex that way. auto s = K.at( vertex ); cliqueVertices.insert( s.begin(), s.end() ); } for( auto&& cliqueVertex : cliqueVertices ) { auto persistence = std::isfinite( itPoint->persistence() ) ? std::pow( itPoint->persistence(), 2 ) : std::pow( 2*maxWeight - itPoint->x(), 2 ); accumulatedPersistenceMap[cliqueVertex] += persistence; numberOfCliqueCommunities[cliqueVertex] += 1; } progress = float( std::distance( pd.begin(), itPoint ) ) / float( pd.size() ) * 100.f; if( itPoint == pd.begin() ) std::cerr << " 0%"; else std::cerr << "\b\b\b\b \b" << std::fixed << std::setw(3) << std::setprecision(0) << progress << "%"; ++itPoint; } std::cerr << "finished\n"; } pd.removeDiagonal(); if( !C.empty() ) { using namespace aleph::utilities; auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK ); std::cerr << "* Storing output in '" << outputFilename << "'...\n"; std::transform( pd.begin(), pd.end(), pd.begin(), [&maxWeight] ( const PersistenceDiagram::Point& p ) { if( !std::isfinite( p.y() ) ) return PersistenceDiagram::Point( p.x(), 2 * maxWeight ); else return PersistenceDiagram::Point( p ); } ); std::ofstream out( outputFilename ); out << "# Original filename: " << filename << "\n"; out << "# k : " << k << "\n"; { auto itPoint = pd.begin(); for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair, ++itPoint ) out << itPoint->x() << "\t" << itPoint->y() << "\t" << cs.at( *C.at( itPair->first ).begin() ) << "\n"; } } } { using namespace aleph::utilities; auto outputFilename = "/tmp/" + stem( basename( filename ) ) + ".txt"; std::cerr << "* Storing accumulated persistence values in '" << outputFilename << "'...\n"; std::ofstream out( outputFilename ); for( auto&& pair : accumulatedPersistenceMap ) out << pair.first << "\t" << pair.second << "\t" << numberOfCliqueCommunities.at(pair.first) << ( labels.empty() ? "" : "\t" + formatLabel( labels.at( pair.first ) ) ) << "\n"; } } <|endoftext|>
<commit_before>//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like binutils "objdump", that is, it // dumps out a plethora of information about an object file depending on the // flags. // //===----------------------------------------------------------------------===// #include "llvm-objdump.h" #include "MCFunction.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/STLExtras.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryObject.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" #include <algorithm> #include <cstring> using namespace llvm; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); static cl::opt<bool> Disassemble("disassemble", cl::desc("Display assembler mnemonics for the machine instructions")); static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"), cl::aliasopt(Disassemble)); static cl::opt<bool> Relocations("r", cl::desc("Display the relocation entries in the file")); static cl::opt<bool> MachO("macho", cl::desc("Use MachO specific object file parser")); static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO)); cl::opt<std::string> llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " "see -version for available targets")); cl::opt<std::string> llvm::ArchName("arch", cl::desc("Target arch to disassemble for, " "see -version for available targets")); static cl::opt<bool> SectionHeaders("section-headers", cl::desc("Display summaries of the headers " "for each section.")); static cl::alias SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), cl::aliasopt(SectionHeaders)); static cl::alias SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), cl::aliasopt(SectionHeaders)); static StringRef ToolName; static bool error(error_code ec) { if (!ec) return false; outs() << ToolName << ": error reading file: " << ec.message() << ".\n"; outs().flush(); return true; } static const Target *GetTarget(const ObjectFile *Obj = NULL) { // Figure out the target triple. llvm::Triple TT("unknown-unknown-unknown"); if (TripleName.empty()) { if (Obj) TT.setArch(Triple::ArchType(Obj->getArch())); } else TT.setTriple(Triple::normalize(TripleName)); if (!ArchName.empty()) TT.setArchName(ArchName); TripleName = TT.str(); // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); if (TheTarget) return TheTarget; errs() << ToolName << ": error: unable to get target for '" << TripleName << "', see --version and --triple.\n"; return 0; } void llvm::DumpBytes(StringRef bytes) { static const char hex_rep[] = "0123456789abcdef"; // FIXME: The real way to do this is to figure out the longest instruction // and align to that size before printing. I'll fix this when I get // around to outputting relocations. // 15 is the longest x86 instruction // 3 is for the hex rep of a byte + a space. // 1 is for the null terminator. enum { OutputSize = (15 * 3) + 1 }; char output[OutputSize]; assert(bytes.size() <= 15 && "DumpBytes only supports instructions of up to 15 bytes"); memset(output, ' ', sizeof(output)); unsigned index = 0; for (StringRef::iterator i = bytes.begin(), e = bytes.end(); i != e; ++i) { output[index] = hex_rep[(*i & 0xF0) >> 4]; output[index + 1] = hex_rep[*i & 0xF]; index += 3; } output[sizeof(output) - 1] = 0; outs() << output; } static void DisassembleObject(const ObjectFile *Obj) { const Target *TheTarget = GetTarget(Obj); if (!TheTarget) { // GetTarget prints out stuff. return; } outs() << '\n'; outs() << Obj->getFileName() << ":\tfile format " << Obj->getFileFormatName() << "\n\n"; error_code ec; for (section_iterator i = Obj->begin_sections(), e = Obj->end_sections(); i != e; i.increment(ec)) { if (error(ec)) break; bool text; if (error(i->isText(text))) break; if (!text) continue; // Make a list of all the symbols in this section. std::vector<std::pair<uint64_t, StringRef> > Symbols; for (symbol_iterator si = Obj->begin_symbols(), se = Obj->end_symbols(); si != se; si.increment(ec)) { bool contains; if (!error(i->containsSymbol(*si, contains)) && contains) { uint64_t Address; if (error(si->getOffset(Address))) break; StringRef Name; if (error(si->getName(Name))) break; Symbols.push_back(std::make_pair(Address, Name)); } } // Sort the symbols by address, just in case they didn't come in that way. array_pod_sort(Symbols.begin(), Symbols.end()); StringRef name; if (error(i->getName(name))) break; outs() << "Disassembly of section " << name << ':'; // If the section has no symbols just insert a dummy one and disassemble // the whole section. if (Symbols.empty()) Symbols.push_back(std::make_pair(0, name)); // Set up disassembler. OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName)); if (!AsmInfo) { errs() << "error: no assembly info for target " << TripleName << "\n"; return; } OwningPtr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, "", "")); if (!STI) { errs() << "error: no subtarget info for target " << TripleName << "\n"; return; } OwningPtr<const MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI)); if (!DisAsm) { errs() << "error: no disassembler for target " << TripleName << "\n"; return; } int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( AsmPrinterVariant, *AsmInfo, *STI)); if (!IP) { errs() << "error: no instruction printer for target " << TripleName << '\n'; return; } StringRef Bytes; if (error(i->getContents(Bytes))) break; StringRefMemoryObject memoryObject(Bytes); uint64_t Size; uint64_t Index; uint64_t SectSize; if (error(i->getSize(SectSize))) break; // Disassemble symbol by symbol. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { uint64_t Start = Symbols[si].first; uint64_t End; // The end is either the size of the section or the beginning of the next // symbol. if (si == se - 1) End = SectSize; // Make sure this symbol takes up space. else if (Symbols[si + 1].first != Start) End = Symbols[si + 1].first - 1; else // This symbol has the same address as the next symbol. Skip it. continue; outs() << '\n' << Symbols[si].second << ":\n"; #ifndef NDEBUG raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); #else raw_ostream &DebugOut = nulls(); #endif for (Index = Start; Index < End; Index += Size) { MCInst Inst; if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut, nulls())) { uint64_t addr; if (error(i->getAddress(addr))) break; outs() << format("%8x:\t", addr + Index); DumpBytes(StringRef(Bytes.data() + Index, Size)); IP->printInst(&Inst, outs(), ""); outs() << "\n"; } else { errs() << ToolName << ": warning: invalid instruction encoding\n"; if (Size == 0) Size = 1; // skip illegible bytes } } } } } static void PrintRelocations(const ObjectFile *o) { error_code ec; for (section_iterator si = o->begin_sections(), se = o->end_sections(); si != se; si.increment(ec)){ if (error(ec)) return; if (si->begin_relocations() == si->end_relocations()) continue; StringRef secname; if (error(si->getName(secname))) continue; outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; for (relocation_iterator ri = si->begin_relocations(), re = si->end_relocations(); ri != re; ri.increment(ec)) { if (error(ec)) return; uint64_t address; SmallString<32> relocname; SmallString<32> valuestr; if (error(ri->getTypeName(relocname))) continue; if (error(ri->getAddress(address))) continue; if (error(ri->getValueString(valuestr))) continue; outs() << address << " " << relocname << " " << valuestr << "\n"; } outs() << "\n"; } } static void PrintSectionHeaders(const ObjectFile *o) { outs() << "Sections:\n" "Idx Name Size Address Type\n"; error_code ec; unsigned i = 0; for (section_iterator si = o->begin_sections(), se = o->end_sections(); si != se; si.increment(ec)) { if (error(ec)) return; StringRef Name; if (error(si->getName(Name))) return; uint64_t Address; if (error(si->getAddress(Address))) return; uint64_t Size; if (error(si->getSize(Size))) return; bool Text, Data, BSS; if (error(si->isText(Text))) return; if (error(si->isData(Data))) return; if (error(si->isBSS(BSS))) return; std::string Type = (std::string(Text ? "TEXT " : "") + (Data ? "DATA " : "") + (BSS ? "BSS" : "")); outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size, Address, Type.c_str()); ++i; } } static void DumpObject(const ObjectFile *o) { if (Disassemble) DisassembleObject(o); if (Relocations) PrintRelocations(o); if (SectionHeaders) PrintSectionHeaders(o); } /// @brief Dump each object file in \a a; static void DumpArchive(const Archive *a) { for (Archive::child_iterator i = a->begin_children(), e = a->end_children(); i != e; ++i) { OwningPtr<Binary> child; if (error_code ec = i->getAsBinary(child)) { errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message() << ".\n"; continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) DumpObject(o); else errs() << ToolName << ": '" << a->getFileName() << "': " << "Unrecognized file type.\n"; } } /// @brief Open file and figure out how to dump it. static void DumpInput(StringRef file) { // If file isn't stdin, check that it exists. if (file != "-" && !sys::fs::exists(file)) { errs() << ToolName << ": '" << file << "': " << "No such file\n"; return; } if (MachO && Disassemble) { DisassembleInputMachO(file); return; } // Attempt to open the binary. OwningPtr<Binary> binary; if (error_code ec = createBinary(file, binary)) { errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n"; return; } if (Archive *a = dyn_cast<Archive>(binary.get())) { DumpArchive(a); } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) { DumpObject(o); } else { errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; } } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize targets and assembly printers/parsers. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllDisassemblers(); cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); TripleName = Triple::normalize(TripleName); ToolName = argv[0]; // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); if (!Disassemble && !Relocations && !SectionHeaders) { cl::PrintHelpMessage(); return 2; } std::for_each(InputFilenames.begin(), InputFilenames.end(), DumpInput); return 0; } <commit_msg>llvm-objdump: Fix whitespace.<commit_after>//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like binutils "objdump", that is, it // dumps out a plethora of information about an object file depending on the // flags. // //===----------------------------------------------------------------------===// #include "llvm-objdump.h" #include "MCFunction.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/STLExtras.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/MemoryObject.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" #include <algorithm> #include <cstring> using namespace llvm; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); static cl::opt<bool> Disassemble("disassemble", cl::desc("Display assembler mnemonics for the machine instructions")); static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"), cl::aliasopt(Disassemble)); static cl::opt<bool> Relocations("r", cl::desc("Display the relocation entries in the file")); static cl::opt<bool> MachO("macho", cl::desc("Use MachO specific object file parser")); static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO)); cl::opt<std::string> llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " "see -version for available targets")); cl::opt<std::string> llvm::ArchName("arch", cl::desc("Target arch to disassemble for, " "see -version for available targets")); static cl::opt<bool> SectionHeaders("section-headers", cl::desc("Display summaries of the headers " "for each section.")); static cl::alias SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), cl::aliasopt(SectionHeaders)); static cl::alias SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), cl::aliasopt(SectionHeaders)); static StringRef ToolName; static bool error(error_code ec) { if (!ec) return false; outs() << ToolName << ": error reading file: " << ec.message() << ".\n"; outs().flush(); return true; } static const Target *GetTarget(const ObjectFile *Obj = NULL) { // Figure out the target triple. llvm::Triple TT("unknown-unknown-unknown"); if (TripleName.empty()) { if (Obj) TT.setArch(Triple::ArchType(Obj->getArch())); } else TT.setTriple(Triple::normalize(TripleName)); if (!ArchName.empty()) TT.setArchName(ArchName); TripleName = TT.str(); // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); if (TheTarget) return TheTarget; errs() << ToolName << ": error: unable to get target for '" << TripleName << "', see --version and --triple.\n"; return 0; } void llvm::DumpBytes(StringRef bytes) { static const char hex_rep[] = "0123456789abcdef"; // FIXME: The real way to do this is to figure out the longest instruction // and align to that size before printing. I'll fix this when I get // around to outputting relocations. // 15 is the longest x86 instruction // 3 is for the hex rep of a byte + a space. // 1 is for the null terminator. enum { OutputSize = (15 * 3) + 1 }; char output[OutputSize]; assert(bytes.size() <= 15 && "DumpBytes only supports instructions of up to 15 bytes"); memset(output, ' ', sizeof(output)); unsigned index = 0; for (StringRef::iterator i = bytes.begin(), e = bytes.end(); i != e; ++i) { output[index] = hex_rep[(*i & 0xF0) >> 4]; output[index + 1] = hex_rep[*i & 0xF]; index += 3; } output[sizeof(output) - 1] = 0; outs() << output; } static void DisassembleObject(const ObjectFile *Obj) { const Target *TheTarget = GetTarget(Obj); if (!TheTarget) { // GetTarget prints out stuff. return; } outs() << '\n'; outs() << Obj->getFileName() << ":\tfile format " << Obj->getFileFormatName() << "\n\n"; error_code ec; for (section_iterator i = Obj->begin_sections(), e = Obj->end_sections(); i != e; i.increment(ec)) { if (error(ec)) break; bool text; if (error(i->isText(text))) break; if (!text) continue; // Make a list of all the symbols in this section. std::vector<std::pair<uint64_t, StringRef> > Symbols; for (symbol_iterator si = Obj->begin_symbols(), se = Obj->end_symbols(); si != se; si.increment(ec)) { bool contains; if (!error(i->containsSymbol(*si, contains)) && contains) { uint64_t Address; if (error(si->getOffset(Address))) break; StringRef Name; if (error(si->getName(Name))) break; Symbols.push_back(std::make_pair(Address, Name)); } } // Sort the symbols by address, just in case they didn't come in that way. array_pod_sort(Symbols.begin(), Symbols.end()); StringRef name; if (error(i->getName(name))) break; outs() << "Disassembly of section " << name << ':'; // If the section has no symbols just insert a dummy one and disassemble // the whole section. if (Symbols.empty()) Symbols.push_back(std::make_pair(0, name)); // Set up disassembler. OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName)); if (!AsmInfo) { errs() << "error: no assembly info for target " << TripleName << "\n"; return; } OwningPtr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, "", "")); if (!STI) { errs() << "error: no subtarget info for target " << TripleName << "\n"; return; } OwningPtr<const MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI)); if (!DisAsm) { errs() << "error: no disassembler for target " << TripleName << "\n"; return; } int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( AsmPrinterVariant, *AsmInfo, *STI)); if (!IP) { errs() << "error: no instruction printer for target " << TripleName << '\n'; return; } StringRef Bytes; if (error(i->getContents(Bytes))) break; StringRefMemoryObject memoryObject(Bytes); uint64_t Size; uint64_t Index; uint64_t SectSize; if (error(i->getSize(SectSize))) break; // Disassemble symbol by symbol. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { uint64_t Start = Symbols[si].first; uint64_t End; // The end is either the size of the section or the beginning of the next // symbol. if (si == se - 1) End = SectSize; // Make sure this symbol takes up space. else if (Symbols[si + 1].first != Start) End = Symbols[si + 1].first - 1; else // This symbol has the same address as the next symbol. Skip it. continue; outs() << '\n' << Symbols[si].second << ":\n"; #ifndef NDEBUG raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); #else raw_ostream &DebugOut = nulls(); #endif for (Index = Start; Index < End; Index += Size) { MCInst Inst; if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut, nulls())) { uint64_t addr; if (error(i->getAddress(addr))) break; outs() << format("%8x:\t", addr + Index); DumpBytes(StringRef(Bytes.data() + Index, Size)); IP->printInst(&Inst, outs(), ""); outs() << "\n"; } else { errs() << ToolName << ": warning: invalid instruction encoding\n"; if (Size == 0) Size = 1; // skip illegible bytes } } } } } static void PrintRelocations(const ObjectFile *o) { error_code ec; for (section_iterator si = o->begin_sections(), se = o->end_sections(); si != se; si.increment(ec)){ if (error(ec)) return; if (si->begin_relocations() == si->end_relocations()) continue; StringRef secname; if (error(si->getName(secname))) continue; outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; for (relocation_iterator ri = si->begin_relocations(), re = si->end_relocations(); ri != re; ri.increment(ec)) { if (error(ec)) return; uint64_t address; SmallString<32> relocname; SmallString<32> valuestr; if (error(ri->getTypeName(relocname))) continue; if (error(ri->getAddress(address))) continue; if (error(ri->getValueString(valuestr))) continue; outs() << address << " " << relocname << " " << valuestr << "\n"; } outs() << "\n"; } } static void PrintSectionHeaders(const ObjectFile *o) { outs() << "Sections:\n" "Idx Name Size Address Type\n"; error_code ec; unsigned i = 0; for (section_iterator si = o->begin_sections(), se = o->end_sections(); si != se; si.increment(ec)) { if (error(ec)) return; StringRef Name; if (error(si->getName(Name))) return; uint64_t Address; if (error(si->getAddress(Address))) return; uint64_t Size; if (error(si->getSize(Size))) return; bool Text, Data, BSS; if (error(si->isText(Text))) return; if (error(si->isData(Data))) return; if (error(si->isBSS(BSS))) return; std::string Type = (std::string(Text ? "TEXT " : "") + (Data ? "DATA " : "") + (BSS ? "BSS" : "")); outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size, Address, Type.c_str()); ++i; } } static void DumpObject(const ObjectFile *o) { if (Disassemble) DisassembleObject(o); if (Relocations) PrintRelocations(o); if (SectionHeaders) PrintSectionHeaders(o); } /// @brief Dump each object file in \a a; static void DumpArchive(const Archive *a) { for (Archive::child_iterator i = a->begin_children(), e = a->end_children(); i != e; ++i) { OwningPtr<Binary> child; if (error_code ec = i->getAsBinary(child)) { errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message() << ".\n"; continue; } if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) DumpObject(o); else errs() << ToolName << ": '" << a->getFileName() << "': " << "Unrecognized file type.\n"; } } /// @brief Open file and figure out how to dump it. static void DumpInput(StringRef file) { // If file isn't stdin, check that it exists. if (file != "-" && !sys::fs::exists(file)) { errs() << ToolName << ": '" << file << "': " << "No such file\n"; return; } if (MachO && Disassemble) { DisassembleInputMachO(file); return; } // Attempt to open the binary. OwningPtr<Binary> binary; if (error_code ec = createBinary(file, binary)) { errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n"; return; } if (Archive *a = dyn_cast<Archive>(binary.get())) { DumpArchive(a); } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) { DumpObject(o); } else { errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; } } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize targets and assembly printers/parsers. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllDisassemblers(); cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); TripleName = Triple::normalize(TripleName); ToolName = argv[0]; // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); if (!Disassemble && !Relocations && !SectionHeaders) { cl::PrintHelpMessage(); return 2; } std::for_each(InputFilenames.begin(), InputFilenames.end(), DumpInput); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2015, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QLocalServer> #include <QLocalSocket> #include <QFile> #include <TWebApplication> #include <tsystembus.h> #include "systembusdaemon.h" static SystemBusDaemon *systemBusDaemon = nullptr; static int maxServers = 0; SystemBusDaemon::SystemBusDaemon() : QObject(), localServer(new QLocalServer), socketSet() { connect(localServer, SIGNAL(newConnection()), this, SLOT(acceptConnection())); } SystemBusDaemon::~SystemBusDaemon() { delete localServer; } bool SystemBusDaemon::open() { #ifdef Q_OS_UNIX // UNIX QFile file(QLatin1String("/tmp/") + TSystemBus::connectionName()); if (file.exists()) { file.remove(); tSystemWarn("File removed for UNIX domain socket : %s", qPrintable(file.fileName())); } #endif return localServer->listen(TSystemBus::connectionName()); } void SystemBusDaemon::close() { tSystemDebug("close system bus daemon : %s", qPrintable(localServer->fullServerName())); localServer->close(); } void SystemBusDaemon::acceptConnection() { QLocalSocket *socket; while ( (socket = localServer->nextPendingConnection()) ) { tSystemDebug("acceptConnection"); connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); connect(socket, SIGNAL(disconnected()), this, SLOT(handleDisconnect())); socketSet.insert(socket); } } void SystemBusDaemon::readSocket() { const int HEADER_LEN = 5; tSystemDebug("SystemBusDaemon::readSocket"); QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender()); if (!socket) { return; } QByteArray buf; for (;;) { buf += socket->readAll(); if (maxServers <= 1) { // do nothing break; } QDataStream ds(buf); ds.setByteOrder(QDataStream::BigEndian); quint8 opcode; int length; ds >> opcode >> length; if (buf.length() < HEADER_LEN || buf.length() < length + HEADER_LEN) { if (!socket->waitForReadyRead(1000)) { tSystemError("Manager frame too short [%s:%d]", __FILE__, __LINE__); break; } continue; } length += HEADER_LEN; // Writes to other tfservers for (auto *tfserver : socketSet) { if (tfserver != socket) { int wrotelen = 0; for (;;) { int len = tfserver->write(buf.data() + wrotelen, length - wrotelen); if (len <= 0) { tSystemError("PIPE write error len:%d [%s:%d]", len, __FILE__, __LINE__); break; } wrotelen += len; if (wrotelen == length) { break; } if (!tfserver->waitForBytesWritten(1000)) { tSystemError("PIPE wait error [%s:%d]", __FILE__, __LINE__); break; } } } } buf.remove(0, length); if (buf.isEmpty()) break; if (!socket->waitForReadyRead(1000)) { tSystemError("Invalid frame [%s:%d]", __FILE__, __LINE__); break; } } } /* Data format 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +---------------+-----------------------------------------------+ | opcode (8) | Payload length (32) | |---------------+-----------------------------------------------+ | | Payload data ... | */ void SystemBusDaemon::handleDisconnect() { QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender()); if (socket) { socketSet.remove(socket); tSystemDebug("disconnected local socket : %p", socket); } } SystemBusDaemon *SystemBusDaemon::instance() { return systemBusDaemon; } void SystemBusDaemon::instantiate() { if (!systemBusDaemon) { systemBusDaemon = new SystemBusDaemon; systemBusDaemon->open(); maxServers = Tf::app()->maxNumberOfAppServers(); } } void SystemBusDaemon::releaseResource(qint64 pid) { #ifdef Q_OS_UNIX // UNIX QFile file(QLatin1String("/tmp/") + TSystemBus::connectionName(pid)); if (file.exists()) { file.remove(); tSystemWarn("File removed for UNIX domain socket : %s", qPrintable(file.fileName())); } #else Q_UNUSED(pid); #endif } <commit_msg>add debug messages.<commit_after>/* Copyright (c) 2015, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QLocalServer> #include <QLocalSocket> #include <QFile> #include <TWebApplication> #include <tsystembus.h> #include "systembusdaemon.h" static SystemBusDaemon *systemBusDaemon = nullptr; static int maxServers = 0; SystemBusDaemon::SystemBusDaemon() : QObject(), localServer(new QLocalServer), socketSet() { connect(localServer, SIGNAL(newConnection()), this, SLOT(acceptConnection())); } SystemBusDaemon::~SystemBusDaemon() { delete localServer; } bool SystemBusDaemon::open() { #ifdef Q_OS_UNIX // UNIX QFile file(QLatin1String("/tmp/") + TSystemBus::connectionName()); if (file.exists()) { file.remove(); tSystemWarn("File removed for UNIX domain socket : %s", qPrintable(file.fileName())); } #endif bool ret = localServer->listen(TSystemBus::connectionName()); if (ret) { tSystemDebug("system bus open : %s", qPrintable(localServer->fullServerName())); } else { tSystemError("system bus open error [%s:%d]", __FILE__, __LINE__); } return ret; } void SystemBusDaemon::close() { tSystemDebug("close system bus daemon : %s", qPrintable(localServer->fullServerName())); localServer->close(); } void SystemBusDaemon::acceptConnection() { QLocalSocket *socket; while ( (socket = localServer->nextPendingConnection()) ) { tSystemDebug("acceptConnection"); connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); connect(socket, SIGNAL(disconnected()), this, SLOT(handleDisconnect())); socketSet.insert(socket); } } void SystemBusDaemon::readSocket() { const int HEADER_LEN = 5; tSystemDebug("SystemBusDaemon::readSocket"); QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender()); if (!socket) { return; } QByteArray buf; for (;;) { buf += socket->readAll(); if (maxServers <= 1) { // do nothing break; } QDataStream ds(buf); ds.setByteOrder(QDataStream::BigEndian); quint8 opcode; int length; ds >> opcode >> length; if (buf.length() < HEADER_LEN || buf.length() < length + HEADER_LEN) { if (!socket->waitForReadyRead(1000)) { tSystemError("Manager frame too short [%s:%d]", __FILE__, __LINE__); break; } continue; } length += HEADER_LEN; // Writes to other tfservers for (auto *tfserver : socketSet) { if (tfserver != socket) { int wrotelen = 0; for (;;) { int len = tfserver->write(buf.data() + wrotelen, length - wrotelen); if (len <= 0) { tSystemError("PIPE write error len:%d [%s:%d]", len, __FILE__, __LINE__); break; } wrotelen += len; if (wrotelen == length) { break; } if (!tfserver->waitForBytesWritten(1000)) { tSystemError("PIPE wait error [%s:%d]", __FILE__, __LINE__); break; } } } } buf.remove(0, length); if (buf.isEmpty()) break; if (!socket->waitForReadyRead(1000)) { tSystemError("Invalid frame [%s:%d]", __FILE__, __LINE__); break; } } } /* Data format 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +---------------+-----------------------------------------------+ | opcode (8) | Payload length (32) | |---------------+-----------------------------------------------+ | | Payload data ... | */ void SystemBusDaemon::handleDisconnect() { QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender()); if (socket) { socketSet.remove(socket); tSystemDebug("disconnected local socket : %p", socket); } } SystemBusDaemon *SystemBusDaemon::instance() { return systemBusDaemon; } void SystemBusDaemon::instantiate() { if (!systemBusDaemon) { systemBusDaemon = new SystemBusDaemon; systemBusDaemon->open(); maxServers = Tf::app()->maxNumberOfAppServers(); } } void SystemBusDaemon::releaseResource(qint64 pid) { #ifdef Q_OS_UNIX // UNIX QFile file(QLatin1String("/tmp/") + TSystemBus::connectionName(pid)); if (file.exists()) { file.remove(); tSystemWarn("File removed for UNIX domain socket : %s", qPrintable(file.fileName())); } #else Q_UNUSED(pid); #endif } <|endoftext|>
<commit_before>#pragma once // valid.hpp: definition of arbitrary valid number configurations // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <limits> namespace sw { namespace unum { template<size_t nbits, size_t es> class valid { static_assert(es + 3 <= nbits, "Value for 'es' is too large for this 'nbits' value"); //static_assert(sizeof(long double) == 16, "Valid library requires compiler support for 128 bit long double."); template <typename T> valid<nbits, es>& _assign(const T& rhs) { constexpr int fbits = std::numeric_limits<T>::digits - 1; value<fbits> v((T)rhs); return *this; } public: static constexpr size_t somebits = 10; valid<nbits, es>() { clear(); } valid(const valid&) = default; valid(valid&&) = default; valid& operator=(const valid&) = default; valid& operator=(valid&&) = default; valid(long initial_value) { *this = initial_value; } valid(unsigned long long initial_value) { *this = initial_value; } valid(double initial_value) { *this = initial_value; } valid(long double initial_value) { *this = initial_value; } valid& operator=(int rhs) { return _assign(rhs); } valid& operator=(unsigned long long rhs) { return _assign(rhs); } valid& operator=(double rhs) { return _assign(rhs); } valid& operator=(long double rhs) { return _assign(rhs); } valid& operator+=(const valid& rhs) { return *this; } valid& operator-=(const valid& rhs) { return *this; } valid& operator*=(const valid& rhs) { return *this; } valid& operator/=(const valid& rhs) { return *this; } // conversion operators // selectors inline bool isOpen() const { return !isClosed(); } inline bool isClosed() const { return lubit && uubit; } inline bool isOpenLower() const { return lubit; } inline bool isOpenUpper() const { return uubit; } inline bool getlb(sw::unum::posit<nbits, es>& _lb) const { _lb = lb; return lubit; } inline bool getub(sw::unum::posit<nbits, es>& _ub) const { _ub = ub; return uubit; } // modifiers // TODO: do we clear to exact 0, or [-inf, inf]? inline void clear() { lb.clear(); ub.clear(); lubit = true; uubit = true; } inline void setToInclusive() { lb.setToNaR(); ub.setToNaR(); lubit = true; uubit = true; } inline void setlb(sw::unum::posit<nbits, es>& _lb, bool ubit) { lb = _lb; lubit = ubit; } inline void setub(sw::unum::posit<nbits, es>& _ub, bool ubit) { ub = _ub; uubit = ubit; } private: // member variables sw::unum::posit<nbits, es> lb, ub; // lower_bound and upper_bound of the tile bool lubit, uubit; // lower ubit, upper ubit // helper methods // friends // template parameters need names different from class template parameters (for gcc and clang) template<size_t nnbits, size_t ees> friend std::ostream& operator<< (std::ostream& ostr, const valid<nnbits, ees>& p); template<size_t nnbits, size_t ees> friend std::istream& operator>> (std::istream& istr, valid<nnbits, ees>& p); template<size_t nnbits, size_t ees> friend bool operator==(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator!=(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator< (const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator> (const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator<=(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator>=(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); }; // VALID operators template<size_t nbits, size_t es> inline std::ostream& operator<<(std::ostream& ostr, const valid<nbits, es>& v) { // determine lower bound if (v.lubit == true) { // exact lower bound ostr << '[' << v.lb << ", "; } else { // inexact lower bound ostr << '(' << v.lb << ", "; } if (v.uubit == true) { // exact upper bound ostr << v.ub << ']'; } else { // inexact upper bound ostr << v.ub << ')'; } return ostr; } template<size_t nbits, size_t es> inline std::istream& operator>> (std::istream& istr, const valid<nbits, es>& v) { istr >> p._Bits; return istr; } } // namespace unum } // namespace sw <commit_msg>WIP: compilation fix<commit_after>#pragma once // valid.hpp: definition of arbitrary valid number configurations // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <limits> namespace sw { namespace unum { template<size_t nbits, size_t es> class valid { static_assert(es + 3 <= nbits, "Value for 'es' is too large for this 'nbits' value"); //static_assert(sizeof(long double) == 16, "Valid library requires compiler support for 128 bit long double."); template <typename T> valid<nbits, es>& _assign(const T& rhs) { constexpr int fbits = std::numeric_limits<T>::digits - 1; value<fbits> v((T)rhs); return *this; } public: static constexpr size_t somebits = 10; valid<nbits, es>() { clear(); } valid(const valid&) = default; valid(valid&&) = default; valid& operator=(const valid&) = default; valid& operator=(valid&&) = default; valid(long initial_value) { *this = initial_value; } valid(unsigned long long initial_value) { *this = initial_value; } valid(double initial_value) { *this = initial_value; } valid(long double initial_value) { *this = initial_value; } valid& operator=(int rhs) { return _assign(rhs); } valid& operator=(unsigned long long rhs) { return _assign(rhs); } valid& operator=(double rhs) { return _assign(rhs); } valid& operator=(long double rhs) { return _assign(rhs); } valid& operator+=(const valid& rhs) { return *this; } valid& operator-=(const valid& rhs) { return *this; } valid& operator*=(const valid& rhs) { return *this; } valid& operator/=(const valid& rhs) { return *this; } // conversion operators // selectors inline bool isOpen() const { return !isClosed(); } inline bool isClosed() const { return lubit && uubit; } inline bool isOpenLower() const { return lubit; } inline bool isOpenUpper() const { return uubit; } inline bool getlb(sw::unum::posit<nbits, es>& _lb) const { _lb = lb; return lubit; } inline bool getub(sw::unum::posit<nbits, es>& _ub) const { _ub = ub; return uubit; } // modifiers // TODO: do we clear to exact 0, or [-inf, inf]? inline void clear() { lb.clear(); ub.clear(); lubit = true; uubit = true; } inline void setToInclusive() { lb.setToNaR(); ub.setToNaR(); lubit = true; uubit = true; } inline void setlb(sw::unum::posit<nbits, es>& _lb, bool ubit) { lb = _lb; lubit = ubit; } inline void setub(sw::unum::posit<nbits, es>& _ub, bool ubit) { ub = _ub; uubit = ubit; } private: // member variables sw::unum::posit<nbits, es> lb, ub; // lower_bound and upper_bound of the tile bool lubit, uubit; // lower ubit, upper ubit // helper methods // friends // template parameters need names different from class template parameters (for gcc and clang) template<size_t nnbits, size_t ees> friend std::ostream& operator<< (std::ostream& ostr, const valid<nnbits, ees>& p); template<size_t nnbits, size_t ees> friend std::istream& operator>> (std::istream& istr, valid<nnbits, ees>& p); template<size_t nnbits, size_t ees> friend bool operator==(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator!=(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator< (const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator> (const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator<=(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); template<size_t nnbits, size_t ees> friend bool operator>=(const valid<nnbits, ees>& lhs, const valid<nnbits, ees>& rhs); }; // VALID operators template<size_t nbits, size_t es> inline std::ostream& operator<<(std::ostream& ostr, const valid<nbits, es>& v) { // determine lower bound if (v.lubit == true) { // exact lower bound ostr << '[' << v.lb << ", "; } else { // inexact lower bound ostr << '(' << v.lb << ", "; } if (v.uubit == true) { // exact upper bound ostr << v.ub << ']'; } else { // inexact upper bound ostr << v.ub << ')'; } return ostr; } template<size_t nbits, size_t es> inline std::istream& operator>> (std::istream& istr, const valid<nbits, es>& v) { istr >> v._Bits; return istr; } } // namespace unum } // namespace sw <|endoftext|>
<commit_before>#include <math.h> #include <vector> #include "drake/systems/plants/collision/DrakeCollision.h" #include "drake/systems/plants/collision/Model.h" #include "gtest/gtest.h" using Eigen::Isometry3d; using Eigen::Vector3d; namespace DrakeCollision { namespace { /* * Three bodies (cube (1 m edges) and two spheres (0.5 m radii) arranged like *this * * ***** * ** ** * * 3 * --+-- * ** ** | * ***** | * | * ^ 2 m * y | | * | | * +---+---+ ***** | * | | | ** * | * | +---+----> * 2 * --+-- * | 1 | x ** ** * +-------+ ***** * | | * +------ 2 m ---------+ * | | * */ TEST(ModelTest, ClosestPointsAllToAll) { // Set up the geometry. Isometry3d T_body1_to_world, T_body2_to_world, T_body3_to_world, T_elem2_to_body; T_body1_to_world.setIdentity(); T_body2_to_world.setIdentity(); T_body3_to_world.setIdentity(); T_body2_to_world.translation() << 1, 0, 0; T_elem2_to_body.setIdentity(); T_elem2_to_body.translation() << 1, 0, 0; T_body3_to_world.translation() << 2, 2, 0; T_body3_to_world.matrix().block<2, 2>(0, 0) << 0, -1, 1, 0; // rotate 90 degrees in z DrakeShapes::Box geometry_1(Vector3d(1, 1, 1)); DrakeShapes::Sphere geometry_2(0.5); DrakeShapes::Sphere geometry_3(0.5); Element element_1(geometry_1); Element element_2(geometry_2, T_elem2_to_body); Element element_3(geometry_3); ElementId id1, id2, id3; // Populate the model. std::shared_ptr<Model> model = newModel(); id1 = model->addElement(element_1); id2 = model->addElement(element_2); id3 = model->addElement(element_3); model->updateElementWorldTransform(id1, T_body1_to_world); model->updateElementWorldTransform(id2, T_body2_to_world); model->updateElementWorldTransform(id3, T_body3_to_world); // Compute the closest points. const std::vector<ElementId> ids_to_check = {id1, id2, id3}; std::vector<PointPair> points; model->closestPointsAllToAll(ids_to_check, true, points); ASSERT_EQ(3, points.size()); // Check the closest point between object 1 and object 2. // TODO(david-german-tri): Migrate this test to use Eigen matchers once // they are available. EXPECT_EQ(id1, points[0].getIdA()); EXPECT_EQ(id2, points[0].getIdB()); EXPECT_EQ(1.0, points[0].getDistance()); EXPECT_EQ(Vector3d(-1, 0, 0), points[0].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtA()).isZero()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtB()).isZero()); // Check the closest point between object 1 and object 3. EXPECT_EQ(id1, points[1].getIdA()); EXPECT_EQ(id3, points[1].getIdB()); EXPECT_EQ(1.6213203435596428, points[1].getDistance()); EXPECT_EQ(Vector3d(-sqrt(2) / 2, -sqrt(2) / 2, 0), points[1].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0.5, 0) - points[1].getPtA()).isZero()); EXPECT_TRUE( (Vector3d(-sqrt(2) / 4, sqrt(2) / 4, 0) - points[1].getPtB()).isZero()); // Check the closest point between object 2 and object 3. EXPECT_EQ(id2, points[2].getIdA()); EXPECT_EQ(id3, points[2].getIdB()); EXPECT_EQ(1.0, points[2].getDistance()); EXPECT_EQ(Vector3d(0, -1, 0), points[2].getNormal()); EXPECT_TRUE((Vector3d(1, 0.5, 0) - points[2].getPtA()).isZero()); EXPECT_TRUE((Vector3d(-0.5, 0, 0) - points[2].getPtB()).isZero()); } } // namespace } // namespace DrakeCollision <commit_msg>Initialize ElementIds upon declaration.<commit_after>#include <cmath> #include <vector> #include "drake/systems/plants/collision/DrakeCollision.h" #include "drake/systems/plants/collision/Model.h" #include "gtest/gtest.h" using Eigen::Isometry3d; using Eigen::Vector3d; namespace DrakeCollision { namespace { /* * Three bodies (cube (1 m edges) and two spheres (0.5 m radii) arranged like *this * * ***** * ** ** * * 3 * --+-- * ** ** | * ***** | * | * ^ 2 m * y | | * | | * +---+---+ ***** | * | | | ** * | * | +---+----> * 2 * --+-- * | 1 | x ** ** * +-------+ ***** * | | * +------ 2 m ---------+ * | | * */ TEST(ModelTest, ClosestPointsAllToAll) { // Set up the geometry. Isometry3d T_body1_to_world, T_body2_to_world, T_body3_to_world, T_elem2_to_body; T_body1_to_world.setIdentity(); T_body2_to_world.setIdentity(); T_body3_to_world.setIdentity(); T_body2_to_world.translation() << 1, 0, 0; T_elem2_to_body.setIdentity(); T_elem2_to_body.translation() << 1, 0, 0; T_body3_to_world.translation() << 2, 2, 0; T_body3_to_world.matrix().block<2, 2>(0, 0) << 0, -1, 1, 0; // rotate 90 degrees in z DrakeShapes::Box geometry_1(Vector3d(1, 1, 1)); DrakeShapes::Sphere geometry_2(0.5); DrakeShapes::Sphere geometry_3(0.5); Element element_1(geometry_1); Element element_2(geometry_2, T_elem2_to_body); Element element_3(geometry_3); // Populate the model. std::shared_ptr<Model> model = newModel(); ElementId id1 = model->addElement(element_1); ElementId id2 = model->addElement(element_2); ElementId id3 = model->addElement(element_3); model->updateElementWorldTransform(id1, T_body1_to_world); model->updateElementWorldTransform(id2, T_body2_to_world); model->updateElementWorldTransform(id3, T_body3_to_world); // Compute the closest points. const std::vector<ElementId> ids_to_check = {id1, id2, id3}; std::vector<PointPair> points; model->closestPointsAllToAll(ids_to_check, true, points); ASSERT_EQ(3, points.size()); // Check the closest point between object 1 and object 2. // TODO(david-german-tri): Migrate this test to use Eigen matchers once // they are available. EXPECT_EQ(id1, points[0].getIdA()); EXPECT_EQ(id2, points[0].getIdB()); EXPECT_EQ(1.0, points[0].getDistance()); EXPECT_EQ(Vector3d(-1, 0, 0), points[0].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtA()).isZero()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtB()).isZero()); // Check the closest point between object 1 and object 3. EXPECT_EQ(id1, points[1].getIdA()); EXPECT_EQ(id3, points[1].getIdB()); EXPECT_EQ(1.6213203435596428, points[1].getDistance()); EXPECT_EQ(Vector3d(-sqrt(2) / 2, -sqrt(2) / 2, 0), points[1].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0.5, 0) - points[1].getPtA()).isZero()); EXPECT_TRUE( (Vector3d(-sqrt(2) / 4, sqrt(2) / 4, 0) - points[1].getPtB()).isZero()); // Check the closest point between object 2 and object 3. EXPECT_EQ(id2, points[2].getIdA()); EXPECT_EQ(id3, points[2].getIdB()); EXPECT_EQ(1.0, points[2].getDistance()); EXPECT_EQ(Vector3d(0, -1, 0), points[2].getNormal()); EXPECT_TRUE((Vector3d(1, 0.5, 0) - points[2].getPtA()).isZero()); EXPECT_TRUE((Vector3d(-0.5, 0, 0) - points[2].getPtB()).isZero()); } } // namespace } // namespace DrakeCollision <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "TraverserEngineRegistry.h" #include "Basics/Exceptions.h" #include "Basics/ReadLocker.h" #include "Basics/WriteLocker.h" #include "Cluster/TraverserEngine.h" #include "VocBase/ticks.h" using namespace arangodb::traverser; TraverserEngineRegistry::EngineInfo::EngineInfo(TRI_vocbase_t* vocbase, VPackSlice info) : _isInUse(false), _engine(new TraverserEngine(vocbase, info)), _timeToLive(0), _expires(0) {} TraverserEngineRegistry::EngineInfo::~EngineInfo() { } TraverserEngineRegistry::~TraverserEngineRegistry() { WRITE_LOCKER(writeLocker, _lock); for (auto const& it : _engines) { destroy(it.first, false); } } /// @brief Create a new Engine and return it's id TraverserEngineID TraverserEngineRegistry::createNew(TRI_vocbase_t* vocbase, VPackSlice engineInfo) { TraverserEngineID id = TRI_NewTickServer(); TRI_ASSERT(id != 0); auto info = std::make_unique<EngineInfo>(vocbase, engineInfo); WRITE_LOCKER(writeLocker, _lock); TRI_ASSERT(_engines.find(id) == _engines.end()); _engines.emplace(id, info.get()); info.release(); return id; } /// @brief Destroy the engine with the given id void TraverserEngineRegistry::destroy(TraverserEngineID id) { destroy(id, true); } /// @brief Get the engine with the given id TraverserEngine* TraverserEngineRegistry::get(TraverserEngineID id) { WRITE_LOCKER(writeLocker, _lock); auto e = _engines.find(id); if (e == _engines.end()) { // Nothing to hand out // TODO: Should we throw an error instead? return nullptr; } if (e->second->_isInUse) { // Someone is still working with this engine. // TODO can we just delete it? Or throw an error? THROW_ARANGO_EXCEPTION(TRI_ERROR_DEADLOCK); } e->second->_isInUse = true; return e->second->_engine.get(); } /// @brief Returns the engine to the registry. Someone else can now use it. void TraverserEngineRegistry::returnEngine(TraverserEngineID id) { WRITE_LOCKER(writeLocker, _lock); auto e = _engines.find(id); if (e == _engines.end()) { // Nothing to return // TODO: Should we throw an error instead? return; } if (e->second->_isInUse) { e->second->_isInUse = false; } // TODO Should we throw an error if we are not allowed to return this } /// @brief Destroy the engine with the given id, worker function void TraverserEngineRegistry::destroy(TraverserEngineID id, bool doLock) { EngineInfo* engine = nullptr; { CONDITIONAL_WRITE_LOCKER(writeLocker, _lock, doLock); auto e = _engines.find(id); if (e == _engines.end()) { // Nothing to destroy // TODO: Should we throw an error instead? return; } // TODO what about shard locking? // TODO what about multiple dbs? if (e->second->_isInUse) { // Someone is still working with this engine. // TODO can we just delete it? Or throw an error? THROW_ARANGO_EXCEPTION(TRI_ERROR_DEADLOCK); } engine = e->second; _engines.erase(id); } delete engine; } <commit_msg>Added enterprise fork in TraverserEngineRegistry.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "TraverserEngineRegistry.h" #include "Basics/Exceptions.h" #include "Basics/ReadLocker.h" #include "Basics/WriteLocker.h" #include "Cluster/TraverserEngine.h" #include "VocBase/ticks.h" using namespace arangodb::traverser; #ifndef USE_ENTERPRISE TraverserEngineRegistry::EngineInfo::EngineInfo(TRI_vocbase_t* vocbase, VPackSlice info) : _isInUse(false), _engine(new TraverserEngine(vocbase, info)), _timeToLive(0), _expires(0) {} TraverserEngineRegistry::EngineInfo::~EngineInfo() { } #endif TraverserEngineRegistry::~TraverserEngineRegistry() { WRITE_LOCKER(writeLocker, _lock); for (auto const& it : _engines) { destroy(it.first, false); } } /// @brief Create a new Engine and return it's id TraverserEngineID TraverserEngineRegistry::createNew(TRI_vocbase_t* vocbase, VPackSlice engineInfo) { TraverserEngineID id = TRI_NewTickServer(); TRI_ASSERT(id != 0); auto info = std::make_unique<EngineInfo>(vocbase, engineInfo); WRITE_LOCKER(writeLocker, _lock); TRI_ASSERT(_engines.find(id) == _engines.end()); _engines.emplace(id, info.get()); info.release(); return id; } /// @brief Destroy the engine with the given id void TraverserEngineRegistry::destroy(TraverserEngineID id) { destroy(id, true); } /// @brief Get the engine with the given id TraverserEngine* TraverserEngineRegistry::get(TraverserEngineID id) { WRITE_LOCKER(writeLocker, _lock); auto e = _engines.find(id); if (e == _engines.end()) { // Nothing to hand out // TODO: Should we throw an error instead? return nullptr; } if (e->second->_isInUse) { // Someone is still working with this engine. // TODO can we just delete it? Or throw an error? THROW_ARANGO_EXCEPTION(TRI_ERROR_DEADLOCK); } e->second->_isInUse = true; return e->second->_engine.get(); } /// @brief Returns the engine to the registry. Someone else can now use it. void TraverserEngineRegistry::returnEngine(TraverserEngineID id) { WRITE_LOCKER(writeLocker, _lock); auto e = _engines.find(id); if (e == _engines.end()) { // Nothing to return // TODO: Should we throw an error instead? return; } if (e->second->_isInUse) { e->second->_isInUse = false; } // TODO Should we throw an error if we are not allowed to return this } /// @brief Destroy the engine with the given id, worker function void TraverserEngineRegistry::destroy(TraverserEngineID id, bool doLock) { EngineInfo* engine = nullptr; { CONDITIONAL_WRITE_LOCKER(writeLocker, _lock, doLock); auto e = _engines.find(id); if (e == _engines.end()) { // Nothing to destroy // TODO: Should we throw an error instead? return; } // TODO what about shard locking? // TODO what about multiple dbs? if (e->second->_isInUse) { // Someone is still working with this engine. // TODO can we just delete it? Or throw an error? THROW_ARANGO_EXCEPTION(TRI_ERROR_DEADLOCK); } engine = e->second; _engines.erase(id); } delete engine; } <|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. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include <algorithm> #include "base/file_path.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/installer/util/google_update_settings.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingNoDelayFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, bool exclude_id, void* reserved); } // extern "C". RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingNoDelayFn send_ping_no_delay = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { if (!module) return NULL; void* entry_point = ::GetProcAddress(module, export_name); return reinterpret_cast<FuncT>(entry_point); } HMODULE LoadRLZLibraryInternal(int directory_key) { FilePath rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; rlz_path = rlz_path.AppendASCII("rlz.dll"); return ::LoadLibraryW(rlz_path.value().c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping_no_delay = WireExport<SendFinancialPingNoDelayFn>(rlz_dll, "SendFinancialPingNoDelay"); return (record_event && get_access_point && clear_all_events && send_ping_no_delay); } return false; } bool SendFinancialPing(const wchar_t* brand, const wchar_t* lang, const wchar_t* referral, bool exclude_id) { RLZTracker::AccessPoint points[] = {RLZTracker::CHROME_OMNIBOX, RLZTracker::CHROME_HOME_PAGE, RLZTracker::NO_ACCESS_POINT}; if (!send_ping_no_delay) return false; return send_ping_no_delay(RLZTracker::CHROME, points, L"chrome", brand, referral, lang, exclude_id, NULL); } // This class leverages the AutocompleteEditModel notification to know when // the user first interacted with the omnibox and set a global accordingly. class OmniBoxUsageObserver : public NotificationObserver { public: OmniBoxUsageObserver() { registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL, NotificationService::AllSources()); omnibox_used_ = false; DCHECK(!instance_); instance_ = this; } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Try to record event now, else set the flag to try later when we // attempt the ping. if (!RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH)) omnibox_used_ = true; delete this; } static bool used() { return omnibox_used_; } // Deletes the single instance of OmniBoxUsageObserver. static void DeleteInstance() { delete instance_; } private: // Dtor is private so the object cannot be created on the stack. ~OmniBoxUsageObserver() { instance_ = NULL; } static bool omnibox_used_; // There should only be one instance created at a time, and instance_ points // to that instance. // NOTE: this is only non-null for the amount of time it is needed. Once the // instance_ is no longer needed (or Chrome is exiting), this is null. static OmniBoxUsageObserver* instance_; NotificationRegistrar registrar_; }; bool OmniBoxUsageObserver::omnibox_used_ = false; OmniBoxUsageObserver* OmniBoxUsageObserver::instance_ = NULL; // This task is run in the file thread, so to not block it for a long time // we use a throwaway thread to do the blocking url request. class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); std::wstring referral; GoogleUpdateSettings::GetReferral(&referral); if (SendFinancialPing(brand.c_str(), lang.c_str(), referral.c_str(), is_organic(brand))) { access_values_state = ACCESS_VALUES_STALE; GoogleUpdateSettings::ClearReferral(); } } // Organic brands all start with GG, such as GGCM. static bool is_organic(const std::wstring& brand) { return (brand.size() < 2) ? false : (brand.substr(0, 2) == L"GG"); } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(ASCIIToWide(env_vars::kHeadless).c_str(), NULL, 0)) { return; } // For organic brandcodes do not use rlz at all. Empty brandcode usually // means a chromium install. This is ok. std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); if (is_strict_organic(brand)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } } // Record first user interaction with the omnibox. We call this all the // time but the rlz lib should ingore all but the first one. if (OmniBoxUsageObserver::used()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH); } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; FilePath user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; const TemplateURLRef* urlref = url_template->url(); if (!urlref) return false; return urlref->HasGoogleBaseURLs(); } static bool is_strict_organic(const std::wstring& brand) { static const wchar_t* kBrands[] = { L"CHFO", L"CHFT", L"CHMA", L"CHMB", L"CHME", L"CHMF", L"CHMG", L"CHMH", L"CHMI", L"CHMQ", L"CHMV", L"CHNB", L"CHNC", L"CHNG", L"CHNH", L"CHNI", L"CHOA", L"CHOB", L"CHOC", L"CHON", L"CHOO", L"CHOP", L"CHOQ", L"CHOR", L"CHOS", L"CHOT", L"CHOU", L"CHOX", L"CHOY", L"CHOZ", L"CHPD", L"CHPE", L"CHPF", L"CHPG", L"EUBB", L"EUBC", L"GGLA", L"GGLS" }; const wchar_t** end = &kBrands[arraysize(kBrands)]; const wchar_t** found = std::find(&kBrands[0], end, brand); if (found != end) return true; if (StartsWith(brand, L"EUB", true) || StartsWith(brand, L"EUC", true) || StartsWith(brand, L"GGR", true)) return true; return false; } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run, int delay) { // Maximum and minimum delay we would allow to be set through master // preferences. Somewhat arbitrary, may need to be adjusted in future. const int kMaxDelay = 200 * 1000; const int kMinDelay = 20 * 1000; delay *= 1000; delay = (delay < kMinDelay) ? kMinDelay : delay; delay = (delay > kMaxDelay) ? kMaxDelay : delay; if (!OmniBoxUsageObserver::used()) new OmniBoxUsageObserver(); // Schedule the delayed init items. MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), delay); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } // static void RLZTracker::CleanupRlz() { OmniBoxUsageObserver::DeleteInstance(); } <commit_msg>Adds brand codes CHHS and CHHM to "organic" list.<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. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include <algorithm> #include "base/file_path.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/installer/util/google_update_settings.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingNoDelayFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, bool exclude_id, void* reserved); } // extern "C". RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingNoDelayFn send_ping_no_delay = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { if (!module) return NULL; void* entry_point = ::GetProcAddress(module, export_name); return reinterpret_cast<FuncT>(entry_point); } HMODULE LoadRLZLibraryInternal(int directory_key) { FilePath rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; rlz_path = rlz_path.AppendASCII("rlz.dll"); return ::LoadLibraryW(rlz_path.value().c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping_no_delay = WireExport<SendFinancialPingNoDelayFn>(rlz_dll, "SendFinancialPingNoDelay"); return (record_event && get_access_point && clear_all_events && send_ping_no_delay); } return false; } bool SendFinancialPing(const wchar_t* brand, const wchar_t* lang, const wchar_t* referral, bool exclude_id) { RLZTracker::AccessPoint points[] = {RLZTracker::CHROME_OMNIBOX, RLZTracker::CHROME_HOME_PAGE, RLZTracker::NO_ACCESS_POINT}; if (!send_ping_no_delay) return false; return send_ping_no_delay(RLZTracker::CHROME, points, L"chrome", brand, referral, lang, exclude_id, NULL); } // This class leverages the AutocompleteEditModel notification to know when // the user first interacted with the omnibox and set a global accordingly. class OmniBoxUsageObserver : public NotificationObserver { public: OmniBoxUsageObserver() { registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL, NotificationService::AllSources()); omnibox_used_ = false; DCHECK(!instance_); instance_ = this; } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Try to record event now, else set the flag to try later when we // attempt the ping. if (!RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH)) omnibox_used_ = true; delete this; } static bool used() { return omnibox_used_; } // Deletes the single instance of OmniBoxUsageObserver. static void DeleteInstance() { delete instance_; } private: // Dtor is private so the object cannot be created on the stack. ~OmniBoxUsageObserver() { instance_ = NULL; } static bool omnibox_used_; // There should only be one instance created at a time, and instance_ points // to that instance. // NOTE: this is only non-null for the amount of time it is needed. Once the // instance_ is no longer needed (or Chrome is exiting), this is null. static OmniBoxUsageObserver* instance_; NotificationRegistrar registrar_; }; bool OmniBoxUsageObserver::omnibox_used_ = false; OmniBoxUsageObserver* OmniBoxUsageObserver::instance_ = NULL; // This task is run in the file thread, so to not block it for a long time // we use a throwaway thread to do the blocking url request. class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); std::wstring referral; GoogleUpdateSettings::GetReferral(&referral); if (SendFinancialPing(brand.c_str(), lang.c_str(), referral.c_str(), is_organic(brand))) { access_values_state = ACCESS_VALUES_STALE; GoogleUpdateSettings::ClearReferral(); } } // Organic brands all start with GG, such as GGCM. static bool is_organic(const std::wstring& brand) { return (brand.size() < 2) ? false : (brand.substr(0, 2) == L"GG"); } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(ASCIIToWide(env_vars::kHeadless).c_str(), NULL, 0)) { return; } // For organic brandcodes do not use rlz at all. Empty brandcode usually // means a chromium install. This is ok. std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); if (is_strict_organic(brand)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } } // Record first user interaction with the omnibox. We call this all the // time but the rlz lib should ingore all but the first one. if (OmniBoxUsageObserver::used()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH); } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; FilePath user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; const TemplateURLRef* urlref = url_template->url(); if (!urlref) return false; return urlref->HasGoogleBaseURLs(); } static bool is_strict_organic(const std::wstring& brand) { static const wchar_t* kBrands[] = { L"CHFO", L"CHFT", L"CHHS", L"CHHM", L"CHMA", L"CHMB", L"CHME", L"CHMF", L"CHMG", L"CHMH", L"CHMI", L"CHMQ", L"CHMV", L"CHNB", L"CHNC", L"CHNG", L"CHNH", L"CHNI", L"CHOA", L"CHOB", L"CHOC", L"CHON", L"CHOO", L"CHOP", L"CHOQ", L"CHOR", L"CHOS", L"CHOT", L"CHOU", L"CHOX", L"CHOY", L"CHOZ", L"CHPD", L"CHPE", L"CHPF", L"CHPG", L"EUBB", L"EUBC", L"GGLA", L"GGLS" }; const wchar_t** end = &kBrands[arraysize(kBrands)]; const wchar_t** found = std::find(&kBrands[0], end, brand); if (found != end) return true; if (StartsWith(brand, L"EUB", true) || StartsWith(brand, L"EUC", true) || StartsWith(brand, L"GGR", true)) return true; return false; } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run, int delay) { // Maximum and minimum delay we would allow to be set through master // preferences. Somewhat arbitrary, may need to be adjusted in future. const int kMaxDelay = 200 * 1000; const int kMinDelay = 20 * 1000; delay *= 1000; delay = (delay < kMinDelay) ? kMinDelay : delay; delay = (delay > kMaxDelay) ? kMaxDelay : delay; if (!OmniBoxUsageObserver::used()) new OmniBoxUsageObserver(); // Schedule the delayed init items. MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), delay); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } // static void RLZTracker::CleanupRlz() { OmniBoxUsageObserver::DeleteInstance(); } <|endoftext|>
<commit_before>#ifndef CONCURRENCY_WATCHABLE_HPP_ #define CONCURRENCY_WATCHABLE_HPP_ #include "errors.hpp" #include <boost/function.hpp> #include <boost/utility/result_of.hpp> #include "concurrency/mutex_assertion.hpp" #include "concurrency/pubsub.hpp" #include "concurrency/signal.hpp" #include "containers/clone_ptr.hpp" /* `watchable_t` represents a variable that you can get the value of and also subscribe to further changes to the value. To get the value of a `watchable_t`, just call `get()`. To subscribe to further changes to the value, construct a `watchable_t::freeze_t` and then construct a `watchable_t::subscription_t`, passing it the `watchable_t` and the `freeze_t`. To create a `watchable_t`, construct a `watchable_variable_t` and then call its `get_watchable()` method. You can change the value of the `watchable_t` by calling `watchable_variable_t::set_value()`. `watchable_t` has a home thread; it can only be accessed from that thread. If you need to access it from another thread, consider using `cross_thread_watchable_variable_t` to create a proxy-watchable with a different home thread. */ template <class value_t> class watchable_t : public home_thread_mixin_t { public: class subscription_t; /* The purpose of the `freeze_t` is to assert that the value of the `watchable_t` doesn't change for as long as it exists. You should not block while the `freeze_t` exists. It's kind of like `mutex_assertion_t`. A common pattern is to construct a `freeze_t`, then call `get()` to initialize some object or objects that mirrors the `watchable_t`'s value, then construct a `subscription_t` to continually keep in sync with the `watchable_t`, then destroy the `freeze_t`. If it weren't for the `freeze_t`, a change might "slip through the cracks" if it happened after `get()` but before constructing the `subscription_t`. If you constructed the `subscription_t` before calling `get()`, then the callback might get run before the objects were first initialized. */ class freeze_t { public: explicit freeze_t(const clone_ptr_t<watchable_t> &watchable) : rwi_lock_acquisition(watchable->get_rwi_lock_assertion()) { watchable->assert_thread(); } void assert_is_holding(const clone_ptr_t<watchable_t> &watchable) { rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion()); } private: friend class watchable_t<value_t>::subscription_t; rwi_lock_assertion_t::read_acq_t rwi_lock_acquisition; }; class subscription_t { public: /* The `boost::function<void()>` passed to the constructor is a callback that will be called whenever the value changes. The callback must not block, and it must not create or destroy `subscription_t` objects. */ explicit subscription_t(boost::function<void()> f) : subscription(f) { } subscription_t(boost::function<void()> f, const clone_ptr_t<watchable_t> &watchable, freeze_t *freeze) : subscription(f, watchable->get_publisher()) { watchable->assert_thread(); freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion()); } void reset() { subscription.reset(); } void reset(const clone_ptr_t<watchable_t> &watchable, freeze_t *freeze) { watchable->assert_thread(); freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion()); subscription.reset(watchable->get_publisher()); } private: typename publisher_t<boost::function<void()> >::subscription_t subscription; }; virtual ~watchable_t() { } virtual watchable_t *clone() const = 0; virtual value_t get() = 0; /* These are internal; the reason they're public is so that `subview()` and similar things can be implemented. */ virtual publisher_t<boost::function<void()> > *get_publisher() = 0; virtual rwi_lock_assertion_t *get_rwi_lock_assertion() = 0; /* `subview()` returns another `watchable_t` whose value is derived from this one by calling `lens` on it. */ template<class callable_type> clone_ptr_t<watchable_t<typename boost::result_of<callable_type(value_t)>::type> > subview(const callable_type &lens); /* `run_until_satisfied()` repeatedly calls `fun` on the current value of `this` until either `fun` returns `true` or `interruptor` is pulsed. It's efficient because it only retries `fun` when the value changes. */ template<class callable_type> void run_until_satisfied(const callable_type &fun, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t); protected: watchable_t() { } private: DISABLE_COPYING(watchable_t); }; /* `run_until_satisfied_2()` repeatedly calls `fun(a->get(), b->get())` until `fun` returns `true` or `interruptor` is pulsed. It's efficient because it only retries `fun` when the value of `a` or `b` changes. */ template<class a_type, class b_type, class callable_type> void run_until_satisfied_2( const clone_ptr_t<watchable_t<a_type> > &a, const clone_ptr_t<watchable_t<b_type> > &b, const callable_type &fun, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t); inline void call_function(const boost::function<void()> &f) { f(); } template <class value_t> class watchable_variable_t { public: explicit watchable_variable_t(const value_t &_value) : value(_value), watchable(this) { } clone_ptr_t<watchable_t<value_t> > get_watchable() { return clone_ptr_t<watchable_t<value_t> >(watchable.clone()); } void set_value(const value_t &_value) { rwi_lock_assertion_t::write_acq_t acquisition(&rwi_lock_assertion); value = _value; publisher_controller.publish(&call_function); } private: class w_t : public watchable_t<value_t> { public: explicit w_t(watchable_variable_t<value_t> *p) : parent(p) { } w_t *clone() const { return new w_t(parent); } value_t get() { return parent->value; } publisher_t<boost::function<void()> > *get_publisher() { return parent->publisher_controller.get_publisher(); } rwi_lock_assertion_t *get_rwi_lock_assertion() { return &parent->rwi_lock_assertion; } watchable_variable_t<value_t> *parent; }; publisher_controller_t<boost::function<void()> > publisher_controller; value_t value; rwi_lock_assertion_t rwi_lock_assertion; w_t watchable; DISABLE_COPYING(watchable_variable_t); }; #include "concurrency/watchable.tcc" #endif /* CONCURRENCY_WATCHABLE_HPP_ */ <commit_msg>Moved watchable_freeze_t and watchable_subscription_t outside of watchable_t.<commit_after>#ifndef CONCURRENCY_WATCHABLE_HPP_ #define CONCURRENCY_WATCHABLE_HPP_ #include "errors.hpp" #include <boost/function.hpp> #include <boost/utility/result_of.hpp> #include "concurrency/mutex_assertion.hpp" #include "concurrency/pubsub.hpp" #include "concurrency/signal.hpp" #include "containers/clone_ptr.hpp" /* `watchable_t` represents a variable that you can get the value of and also subscribe to further changes to the value. To get the value of a `watchable_t`, just call `get()`. To subscribe to further changes to the value, construct a `watchable_t::freeze_t` and then construct a `watchable_t::subscription_t`, passing it the `watchable_t` and the `freeze_t`. To create a `watchable_t`, construct a `watchable_variable_t` and then call its `get_watchable()` method. You can change the value of the `watchable_t` by calling `watchable_variable_t::set_value()`. `watchable_t` has a home thread; it can only be accessed from that thread. If you need to access it from another thread, consider using `cross_thread_watchable_variable_t` to create a proxy-watchable with a different home thread. */ template <class value_t> class watchable_t; template <class value_t> class watchable_freeze_t; template <class value_t> class watchable_subscription_t { public: /* The `boost::function<void()>` passed to the constructor is a callback that will be called whenever the value changes. The callback must not block, and it must not create or destroy `subscription_t` objects. */ explicit watchable_subscription_t(const boost::function<void()> &f) : subscription(f) { } watchable_subscription_t(const boost::function<void()> &f, const clone_ptr_t<watchable_t<value_t> > &watchable, watchable_freeze_t<value_t> *freeze) : subscription(f, watchable->get_publisher()) { watchable->assert_thread(); freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion()); } void reset() { subscription.reset(); } void reset(const clone_ptr_t<watchable_t<value_t> > &watchable, watchable_freeze_t<value_t> *freeze) { watchable->assert_thread(); freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion()); subscription.reset(watchable->get_publisher()); } private: typename publisher_t<boost::function<void()> >::subscription_t subscription; DISABLE_COPYING(watchable_subscription_t); }; /* The purpose of the `freeze_t` is to assert that the value of the `watchable_t` doesn't change for as long as it exists. You should not block while the `freeze_t` exists. It's kind of like `mutex_assertion_t`. A common pattern is to construct a `freeze_t`, then call `get()` to initialize some object or objects that mirrors the `watchable_t`'s value, then construct a `subscription_t` to continually keep in sync with the `watchable_t`, then destroy the `freeze_t`. If it weren't for the `freeze_t`, a change might "slip through the cracks" if it happened after `get()` but before constructing the `subscription_t`. If you constructed the `subscription_t` before calling `get()`, then the callback might get run before the objects were first initialized. */ template <class value_t> class watchable_freeze_t { public: explicit watchable_freeze_t(const clone_ptr_t<watchable_t<value_t> > &watchable) : rwi_lock_acquisition(watchable->get_rwi_lock_assertion()) { watchable->assert_thread(); } void assert_is_holding(const clone_ptr_t<watchable_t<value_t> > &watchable) { rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion()); } private: friend class watchable_subscription_t<value_t>; rwi_lock_assertion_t::read_acq_t rwi_lock_acquisition; DISABLE_COPYING(watchable_freeze_t); }; template <class value_t> class watchable_t : public home_thread_mixin_t { public: typedef watchable_freeze_t<value_t> freeze_t; typedef watchable_subscription_t<value_t> subscription_t; virtual ~watchable_t() { } virtual watchable_t *clone() const = 0; virtual value_t get() = 0; /* These are internal; the reason they're public is so that `subview()` and similar things can be implemented. */ virtual publisher_t<boost::function<void()> > *get_publisher() = 0; virtual rwi_lock_assertion_t *get_rwi_lock_assertion() = 0; /* `subview()` returns another `watchable_t` whose value is derived from this one by calling `lens` on it. */ template<class callable_type> clone_ptr_t<watchable_t<typename boost::result_of<callable_type(value_t)>::type> > subview(const callable_type &lens); /* `run_until_satisfied()` repeatedly calls `fun` on the current value of `this` until either `fun` returns `true` or `interruptor` is pulsed. It's efficient because it only retries `fun` when the value changes. */ template<class callable_type> void run_until_satisfied(const callable_type &fun, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t); protected: watchable_t() { } private: DISABLE_COPYING(watchable_t); }; /* `run_until_satisfied_2()` repeatedly calls `fun(a->get(), b->get())` until `fun` returns `true` or `interruptor` is pulsed. It's efficient because it only retries `fun` when the value of `a` or `b` changes. */ template<class a_type, class b_type, class callable_type> void run_until_satisfied_2( const clone_ptr_t<watchable_t<a_type> > &a, const clone_ptr_t<watchable_t<b_type> > &b, const callable_type &fun, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t); inline void call_function(const boost::function<void()> &f) { f(); } template <class value_t> class watchable_variable_t { public: explicit watchable_variable_t(const value_t &_value) : value(_value), watchable(this) { } clone_ptr_t<watchable_t<value_t> > get_watchable() { return clone_ptr_t<watchable_t<value_t> >(watchable.clone()); } void set_value(const value_t &_value) { rwi_lock_assertion_t::write_acq_t acquisition(&rwi_lock_assertion); value = _value; publisher_controller.publish(&call_function); } private: class w_t : public watchable_t<value_t> { public: explicit w_t(watchable_variable_t<value_t> *p) : parent(p) { } w_t *clone() const { return new w_t(parent); } value_t get() { return parent->value; } publisher_t<boost::function<void()> > *get_publisher() { return parent->publisher_controller.get_publisher(); } rwi_lock_assertion_t *get_rwi_lock_assertion() { return &parent->rwi_lock_assertion; } watchable_variable_t<value_t> *parent; }; publisher_controller_t<boost::function<void()> > publisher_controller; value_t value; rwi_lock_assertion_t rwi_lock_assertion; w_t watchable; DISABLE_COPYING(watchable_variable_t); }; #include "concurrency/watchable.tcc" #endif /* CONCURRENCY_WATCHABLE_HPP_ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Romain Létendart * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "configurationprovider.h" #include <iostream> #include <sstream> #include <string> #include <vector> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace geecxx { ConfigurationProvider::ConfigurationProvider() : _help(false) { po::options_description mandatory("Mandatory arguments"); mandatory.add_options() ("server", po::value<std::string>()->required(), "the irc server to connect to") ("port", po::value<std::uint16_t>()->required(), "the port to connect to") ("channel", po::value<std::string>()->required(), "the channel to connect to") ; po::options_description optional("Optional arguments"); optional.add_options() ("key", po::value<std::string>(), "the protection key for the channel") ("nick", po::value<std::string>()->default_value(std::string("geecxx")), "the bot's nickname") ; po::options_description generic("Generic options"); generic.add_options() ("help,h", "produce help message") ; _cliOptions.add(mandatory).add(optional).add(generic); _helpOptions.add(optional).add(generic); } bool ConfigurationProvider::parseCommandLineArgs(int argc, char *argv[]) { try { po::positional_options_description p; p.add("server", 1); p.add("port", 1); p.add("channel", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(_cliOptions).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { _help = true; return true; } _server = vm["server"].as<std::string>(); _portNumber = vm["port"].as<std::uint16_t>(); _channelName = vm["channel"].as<std::string>(); if (vm.count("key")) { _channelKey = vm["key"].as<std::string>(); } if (vm.count("nick")) { _nickname = vm["nick"].as<std::string>(); } } catch(std::exception& e) { std::cerr << e.what() << std::endl; return false; } return true; } std::string ConfigurationProvider::help() { std::ostringstream oss; oss << "Usage: geecxx [options] <server> <port> <channel>" << std::endl; oss << _helpOptions; return oss.str(); } std::string ConfigurationProvider::getServer() const { return _server; } std::uint16_t ConfigurationProvider::getPortNumber() const { return _portNumber; } std::string ConfigurationProvider::getNickname() const { return _nickname; } std::string ConfigurationProvider::getChannelName() const { return _channelName; } std::string ConfigurationProvider::getChannelKey() const { return _channelKey; } bool ConfigurationProvider::needsHelp() const { return _help; } } <commit_msg>Command line parsing code improvment<commit_after>/* * Copyright (c) 2015, Romain Létendart * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "configurationprovider.h" #include <iostream> #include <sstream> #include <string> #include <vector> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace geecxx { ConfigurationProvider::ConfigurationProvider() : _help(false) { po::options_description mandatory("Mandatory arguments"); mandatory.add_options() ("server", po::value<std::string>(&_server)->required(), "the irc server to connect to") ("port", po::value<std::uint16_t>(&_portNumber)->required(), "the port to connect to") ("channel", po::value<std::string>(&_channelName)->required(), "the channel to connect to") ; po::options_description optional("Optional arguments"); optional.add_options() ("key", po::value<std::string>(&_channelKey)->default_value(std::string()), "the protection key for the channel") ("nick", po::value<std::string>(&_nickname)->default_value(std::string("geecxx")), "the bot's nickname") ; po::options_description generic("Generic options"); generic.add_options() ("help,h", "produce help message") ; _cliOptions.add(mandatory).add(optional).add(generic); _helpOptions.add(optional).add(generic); } bool ConfigurationProvider::parseCommandLineArgs(int argc, char *argv[]) { try { po::positional_options_description p; p.add("server", 1); p.add("port", 1); p.add("channel", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(_cliOptions).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { _help = true; return true; } } catch(std::exception& e) { std::cerr << e.what() << std::endl; return false; } return true; } std::string ConfigurationProvider::help() { std::ostringstream oss; oss << "Usage: geecxx [options] <server> <port> <channel>" << std::endl; oss << _helpOptions; return oss.str(); } std::string ConfigurationProvider::getServer() const { return _server; } std::uint16_t ConfigurationProvider::getPortNumber() const { return _portNumber; } std::string ConfigurationProvider::getNickname() const { return _nickname; } std::string ConfigurationProvider::getChannelName() const { return _channelName; } std::string ConfigurationProvider::getChannelKey() const { return _channelKey; } bool ConfigurationProvider::needsHelp() const { return _help; } } <|endoftext|>
<commit_before>// // List.c // Emojicode // // Created by Theo Weidmann on 18.01.15. // Copyright (c) 2015 Theo Weidmann. All rights reserved. // #include "List.hpp" #include "String.hpp" #include "Thread.hpp" #include "Memory.hpp" #include <algorithm> #include <cstring> #include <random> #include <utility> namespace Emojicode { void expandListSize(RetainedObjectPointer listObject, Thread *thread) { #define initialSize 7 auto *list = listObject->val<List>(); if (list->capacity == 0) { Object *object = newArray(sizeof(Box) * initialSize); list = listObject->val<List>(); list->items = object; list->capacity = initialSize; } else { size_t newSize = list->capacity + (list->capacity >> 1); Object *object = resizeArray(list->items, sizeCalculationWithOverflowProtection(newSize, sizeof(Box)), thread); list = listObject->val<List>(); list->items = object; list->capacity = newSize; } #undef initialSize } void listEnsureCapacity(Thread *thread, size_t size) { auto *list = thread->thisObject()->val<List>(); if (list->capacity < size) { Object *object; if (list->capacity == 0) { object = newArray(sizeCalculationWithOverflowProtection(size, sizeof(Box))); } else { object = resizeArray(list->items, sizeCalculationWithOverflowProtection(size, sizeof(Box)), thread); } list = thread->thisObject()->val<List>(); list->items = object; list->capacity = size; } } void listMark(Object *self) { auto *list = self->val<List>(); if (list->items) { mark(&list->items); } for (size_t i = 0; i < list->count; i++) { markBox(&list->elements()[i]); } } Box* listAppendDestination(RetainedObjectPointer listObject, Thread *thread) { auto *list = listObject->val<List>(); if (list->capacity - list->count == 0) { expandListSize(listObject, thread); } list = listObject->val<List>(); return list->elements() + list->count++; } void listAppendList(Thread *thread) { auto *copyList = thread->variable(0).object->val<List>(); listEnsureCapacity(thread, thread->thisObject()->val<List>()->count + copyList->count); auto *list = thread->thisObject()->val<List>(); copyList = thread->variable(0).object->val<List>(); std::memcpy(list->elements() + list->count, copyList->elements(), copyList->count * sizeof(Box)); list->count += copyList->count; } void listCountBridge(Thread *thread) { thread->returnFromFunction(static_cast<EmojicodeInteger>(thread->thisObject()->val<List>()->count)); } void listAppendBridge(Thread *thread) { *listAppendDestination(thread->thisObjectAsRetained(), thread) = *reinterpret_cast<Box *>(thread->variableDestination(0)); thread->returnFromFunction(); } void listGetBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); EmojicodeInteger index = thread->variable(0).raw; if (index < 0) { index += list->count; } if (index < 0 || list->count <= index) { thread->returnNothingnessFromFunction(); return; } thread->returnFromFunction(list->elements()[index]); } void listRemoveBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); EmojicodeInteger index = thread->variable(0).raw; if (index < 0) { index += list->count; } if (index < 0 || list->count <= index) { thread->returnFromFunction(false); return; } std::memmove(list->elements() + index, list->elements() + index + 1, sizeof(Box) * (list->count - index - 1)); list->elements()[--list->count].makeNothingness(); thread->returnFromFunction(true); } void listPopBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); if (list->count == 0) { thread->returnNothingnessFromFunction(); return; } size_t index = --list->count; Box v = list->elements()[index]; list->elements()[index].makeNothingness(); thread->returnFromFunction(v); } void listInsertBridge(Thread *thread) { EmojicodeInteger index = thread->variable(0).raw; auto *list = thread->thisObject()->val<List>(); if (index < 0) { index += list->count; } if (index < 0 || list->count <= index) { thread->returnFromFunction(); return; } if (list->capacity - list->count == 0) { expandListSize(thread->thisObjectAsRetained(), thread); } list = thread->thisObject()->val<List>(); std::memmove(list->elements() + index + 1, list->elements() + index, sizeof(Box) * (list->count++ - index)); list->elements()[index].copy(thread->variableDestination(1)); thread->returnFromFunction(); } void listSort(Thread *thread) { auto *list = thread->thisObject()->val<List>(); std::sort(list->elements(), list->elements() + list->count, [thread](const Box &a, const Box &b) { Value args[2 * kBoxValueSize]; a.copyTo(args); b.copyTo(args + kBoxValueSize); Value c; executeCallableExtern(thread->variable(0).object, args, sizeof(args) / sizeof(Value), thread); return c.raw < 0; }); thread->returnFromFunction(); } void listFromListBridge(Thread *thread) { auto listO = thread->retain(newObject(CL_LIST)); auto *list = listO->val<List>(); auto *originalList = thread->thisObject()->val<List>(); list->count = originalList->count; list->capacity = originalList->capacity; Object *items = newArray(sizeof(Box) * originalList->capacity); list = listO->val<List>(); originalList = thread->thisObject()->val<List>(); list->items = items; std::memcpy(list->elements(), originalList->elements(), originalList->count * sizeof(Box)); thread->release(1); thread->returnFromFunction(listO.unretainedPointer()); } void listRemoveAllBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); std::memset(list->elements(), 0, list->count * sizeof(Box)); list->count = 0; thread->returnFromFunction(); } void listSetBridge(Thread *thread) { EmojicodeInteger index = thread->variable(0).raw; listEnsureCapacity(thread, index + 1); auto *list = thread->thisObject()->val<List>(); if (list->count <= index) { list->count = index + 1; } list->elements()[index].copy(thread->variableDestination(1)); thread->returnFromFunction(); } void listShuffleInPlaceBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); auto rng = std::mt19937_64(std::random_device()()); std::shuffle(list->elements(), list->elements() + list->count, rng); thread->returnFromFunction(); } void listEnsureCapacityBridge(Thread *thread) { listEnsureCapacity(thread, thread->variable(0).raw); thread->returnFromFunction(); } void initListEmptyBridge(Thread *thread) { // The Real-Time Engine guarantees pre-nulled objects. thread->returnFromFunction(thread->thisContext()); } void initListWithCapacity(Thread *thread) { EmojicodeInteger capacity = thread->variable(0).raw; Object *n = newArray(sizeCalculationWithOverflowProtection(capacity, sizeof(Box))); auto *list = thread->thisObject()->val<List>(); list->capacity = capacity; list->items = n; thread->returnFromFunction(thread->thisContext()); } } // namespace Emojicode <commit_msg>🛵 Make listSort use return<commit_after>// // List.c // Emojicode // // Created by Theo Weidmann on 18.01.15. // Copyright (c) 2015 Theo Weidmann. All rights reserved. // #include "List.hpp" #include "String.hpp" #include "Thread.hpp" #include "Memory.hpp" #include <algorithm> #include <cstring> #include <random> #include <utility> namespace Emojicode { void expandListSize(RetainedObjectPointer listObject, Thread *thread) { #define initialSize 7 auto *list = listObject->val<List>(); if (list->capacity == 0) { Object *object = newArray(sizeof(Box) * initialSize); list = listObject->val<List>(); list->items = object; list->capacity = initialSize; } else { size_t newSize = list->capacity + (list->capacity >> 1); Object *object = resizeArray(list->items, sizeCalculationWithOverflowProtection(newSize, sizeof(Box)), thread); list = listObject->val<List>(); list->items = object; list->capacity = newSize; } #undef initialSize } void listEnsureCapacity(Thread *thread, size_t size) { auto *list = thread->thisObject()->val<List>(); if (list->capacity < size) { Object *object; if (list->capacity == 0) { object = newArray(sizeCalculationWithOverflowProtection(size, sizeof(Box))); } else { object = resizeArray(list->items, sizeCalculationWithOverflowProtection(size, sizeof(Box)), thread); } list = thread->thisObject()->val<List>(); list->items = object; list->capacity = size; } } void listMark(Object *self) { auto *list = self->val<List>(); if (list->items) { mark(&list->items); } for (size_t i = 0; i < list->count; i++) { markBox(&list->elements()[i]); } } Box* listAppendDestination(RetainedObjectPointer listObject, Thread *thread) { auto *list = listObject->val<List>(); if (list->capacity - list->count == 0) { expandListSize(listObject, thread); } list = listObject->val<List>(); return list->elements() + list->count++; } void listAppendList(Thread *thread) { auto *copyList = thread->variable(0).object->val<List>(); listEnsureCapacity(thread, thread->thisObject()->val<List>()->count + copyList->count); auto *list = thread->thisObject()->val<List>(); copyList = thread->variable(0).object->val<List>(); std::memcpy(list->elements() + list->count, copyList->elements(), copyList->count * sizeof(Box)); list->count += copyList->count; } void listCountBridge(Thread *thread) { thread->returnFromFunction(static_cast<EmojicodeInteger>(thread->thisObject()->val<List>()->count)); } void listAppendBridge(Thread *thread) { *listAppendDestination(thread->thisObjectAsRetained(), thread) = *reinterpret_cast<Box *>(thread->variableDestination(0)); thread->returnFromFunction(); } void listGetBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); EmojicodeInteger index = thread->variable(0).raw; if (index < 0) { index += list->count; } if (index < 0 || list->count <= index) { thread->returnNothingnessFromFunction(); return; } thread->returnFromFunction(list->elements()[index]); } void listRemoveBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); EmojicodeInteger index = thread->variable(0).raw; if (index < 0) { index += list->count; } if (index < 0 || list->count <= index) { thread->returnFromFunction(false); return; } std::memmove(list->elements() + index, list->elements() + index + 1, sizeof(Box) * (list->count - index - 1)); list->elements()[--list->count].makeNothingness(); thread->returnFromFunction(true); } void listPopBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); if (list->count == 0) { thread->returnNothingnessFromFunction(); return; } size_t index = --list->count; Box v = list->elements()[index]; list->elements()[index].makeNothingness(); thread->returnFromFunction(v); } void listInsertBridge(Thread *thread) { EmojicodeInteger index = thread->variable(0).raw; auto *list = thread->thisObject()->val<List>(); if (index < 0) { index += list->count; } if (index < 0 || list->count <= index) { thread->returnFromFunction(); return; } if (list->capacity - list->count == 0) { expandListSize(thread->thisObjectAsRetained(), thread); } list = thread->thisObject()->val<List>(); std::memmove(list->elements() + index + 1, list->elements() + index, sizeof(Box) * (list->count++ - index)); list->elements()[index].copy(thread->variableDestination(1)); thread->returnFromFunction(); } void listSort(Thread *thread) { auto *list = thread->thisObject()->val<List>(); std::sort(list->elements(), list->elements() + list->count, [thread](const Box &a, const Box &b) { Value args[2 * kBoxValueSize]; a.copyTo(args); b.copyTo(args + kBoxValueSize); executeCallableExtern(thread->variable(0).object, args, sizeof(args) / sizeof(Value), thread); return thread->popOpr().raw < 0; }); thread->returnFromFunction(); } void listFromListBridge(Thread *thread) { auto listO = thread->retain(newObject(CL_LIST)); auto *list = listO->val<List>(); auto *originalList = thread->thisObject()->val<List>(); list->count = originalList->count; list->capacity = originalList->capacity; Object *items = newArray(sizeof(Box) * originalList->capacity); list = listO->val<List>(); originalList = thread->thisObject()->val<List>(); list->items = items; std::memcpy(list->elements(), originalList->elements(), originalList->count * sizeof(Box)); thread->release(1); thread->returnFromFunction(listO.unretainedPointer()); } void listRemoveAllBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); std::memset(list->elements(), 0, list->count * sizeof(Box)); list->count = 0; thread->returnFromFunction(); } void listSetBridge(Thread *thread) { EmojicodeInteger index = thread->variable(0).raw; listEnsureCapacity(thread, index + 1); auto *list = thread->thisObject()->val<List>(); if (list->count <= index) { list->count = index + 1; } list->elements()[index].copy(thread->variableDestination(1)); thread->returnFromFunction(); } void listShuffleInPlaceBridge(Thread *thread) { auto *list = thread->thisObject()->val<List>(); auto rng = std::mt19937_64(std::random_device()()); std::shuffle(list->elements(), list->elements() + list->count, rng); thread->returnFromFunction(); } void listEnsureCapacityBridge(Thread *thread) { listEnsureCapacity(thread, thread->variable(0).raw); thread->returnFromFunction(); } void initListEmptyBridge(Thread *thread) { // The Real-Time Engine guarantees pre-nulled objects. thread->returnFromFunction(thread->thisContext()); } void initListWithCapacity(Thread *thread) { EmojicodeInteger capacity = thread->variable(0).raw; Object *n = newArray(sizeCalculationWithOverflowProtection(capacity, sizeof(Box))); auto *list = thread->thisObject()->val<List>(); list->capacity = capacity; list->items = n; thread->returnFromFunction(thread->thisContext()); } } // namespace Emojicode <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 "google/cloud/spanner/client.h" #include <iostream> #include <stdexcept> #include <chrono> namespace { namespace spanner = ::google::cloud::spanner; using google::cloud::StatusOr; const std::int64_t DEFAULTGAP = 100; const std::int64_t BATCHSIZE = 1000; int batchUpdateData(spanner::Client readClient, spanner::Client writeClient, std::int64_t batchSize) { auto rows = readClient.Read("TestModels", spanner::KeySet::All(), {"CdsId", "ExpirationTime", "TrainingTime"}); int updatedRecord = 0; spanner::Mutations mutations; std::int64_t i = 0; for(const auto& row : rows) { if(!row) throw std::runtime_error(row.status().message()); spanner::Value cds = (*row).get(0).value(); spanner::Value expiration = (*row).get(1).value(); spanner::Value training = (*row).get(2).value(); std::int64_t cdsId = cds.get<std::int64_t>().value(); StatusOr<spanner::Timestamp> expirationTime = expiration.get<spanner::Timestamp>(); StatusOr<spanner::Timestamp> trainingTime = training.get<spanner::Timestamp>(); if(!trainingTime) { throw std::runtime_error("TrainingTime shouldn't be null."); } if(expirationTime) { spanner::sys_time<std::chrono::nanoseconds> trainingNS = (*expirationTime).get<spanner::sys_time<std::chrono::nanoseconds>>().value() - 60*std::chrono::hours(24); spanner::Timestamp supposedTraining = spanner::MakeTimestamp(trainingNS).value(); if(*trainingTime != supposedTraining) { throw std::runtime_error("Time gap for " + std::to_string(cdsId) + " is not correct."); } } else { spanner::sys_time<std::chrono::nanoseconds> expirationNS = (*trainingTime).get<spanner::sys_time<std::chrono::nanoseconds>>().value() + 60*std::chrono::hours(24); spanner::Timestamp newExpiration = spanner::MakeTimestamp(expirationNS).value(); mutations.push_back(spanner::UpdateMutationBuilder( "TestModels", {"CdsId", "ExpirationTime", "TrainingTime"}) .EmplaceRow(cdsId, newExpiration, *trainingTime) .Build()); ++i; if(i%batchSize == 0) { auto commit_result = writeClient.Commit(mutations); if (!commit_result) { throw std::runtime_error(commit_result.status().message()); } updatedRecord += mutations.size(); mutations.clear(); i = 0; } } } if(!mutations.empty()) { auto commit_result = writeClient.Commit(mutations); if (!commit_result) { throw std::runtime_error(commit_result.status().message()); } updatedRecord += mutations.size(); } return updatedRecord; } void batchInsertData(google::cloud::spanner::Client client, std::int64_t batchSize) { namespace spanner = ::google::cloud::spanner; using ::google::cloud::StatusOr; auto commit_result = client.Commit( [&client, &batchSize]( spanner::Transaction const& txn) -> StatusOr<spanner::Mutations> { spanner::Mutations mutations; spanner::sys_time<std::chrono::nanoseconds> trainingNS = std::chrono::system_clock::now(); spanner::Timestamp trainingTime = spanner::MakeTimestamp(trainingNS).value(); for(std::int64_t i = 3; i <= batchSize; i++) { mutations.push_back(spanner::InsertMutationBuilder( "TestModels", {"CdsId", "TrainingTime"}) .EmplaceRow(i, trainingTime) .Build()); } return mutations; }); if (!commit_result) { throw std::runtime_error(commit_result.status().message()); } } } // namespace int main(int argc, char* argv[]) try { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " project-id instance-id database-id\n"; return 1; } spanner::Client readClient( spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3]))); spanner::Client writeClient( spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3]))); auto start = std::chrono::high_resolution_clock::now(); int updatedRecord = batchUpdateData(readClient, writeClient, BATCHSIZE); // batchInsertData(writeClient, BATCHSIZE); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start); std::cout << "Time taken : " << duration.count() << " milliseconds" << std::endl; std::cout << "Total updated records : " << updatedRecord << " milliseconds" << std::endl; return 1; } catch (std::exception const& ex) { std::cerr << "Standard exception raised: " << ex.what() << "\n"; return 1; }<commit_msg>add const<commit_after>// Copyright 2020 Google LLC // // 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 "google/cloud/spanner/client.h" #include <iostream> #include <stdexcept> #include <chrono> namespace { namespace spanner = ::google::cloud::spanner; using google::cloud::StatusOr; const std::int64_t DAYINTERVAL = 60; const std::int64_t BATCHSIZE = 1000; // mutations per commit const std::string TABLE = "TestModels"; int batchUpdateData(spanner::Client readClient, spanner::Client writeClient, std::int64_t batchSize) { auto rows = readClient.Read(TABLE, spanner::KeySet::All(), {"CdsId", "ExpirationTime", "TrainingTime"}); int updatedRecord = 0; spanner::Mutations mutations; std::int64_t i = 0; for(const auto& row : rows) { if(!row) throw std::runtime_error(row.status().message()); spanner::Value cds = (*row).get(0).value(); spanner::Value expiration = (*row).get(1).value(); spanner::Value training = (*row).get(2).value(); std::int64_t cdsId = cds.get<std::int64_t>().value(); StatusOr<spanner::Timestamp> expirationTime = expiration.get<spanner::Timestamp>(); StatusOr<spanner::Timestamp> trainingTime = training.get<spanner::Timestamp>(); if(!trainingTime) { throw std::runtime_error("TrainingTime shouldn't be null."); } if(expirationTime) { spanner::sys_time<std::chrono::nanoseconds> trainingNS = (*expirationTime).get<spanner::sys_time<std::chrono::nanoseconds>>().value() - DAYINTERVAL*std::chrono::hours(24); spanner::Timestamp supposedTraining = spanner::MakeTimestamp(trainingNS).value(); if(*trainingTime != supposedTraining) { throw std::runtime_error("Time gap for " + std::to_string(cdsId) + " is not correct."); } } else { spanner::sys_time<std::chrono::nanoseconds> expirationNS = (*trainingTime).get<spanner::sys_time<std::chrono::nanoseconds>>().value() + DAYINTERVAL*std::chrono::hours(24); spanner::Timestamp newExpiration = spanner::MakeTimestamp(expirationNS).value(); mutations.push_back(spanner::UpdateMutationBuilder( TABLE, {"CdsId", "ExpirationTime", "TrainingTime"}) .EmplaceRow(cdsId, newExpiration, *trainingTime) .Build()); ++i; if(i%batchSize == 0) { auto commit_result = writeClient.Commit(mutations); if (!commit_result) { throw std::runtime_error(commit_result.status().message()); } updatedRecord += mutations.size(); mutations.clear(); i = 0; } } } if(!mutations.empty()) { auto commit_result = writeClient.Commit(mutations); if (!commit_result) { throw std::runtime_error(commit_result.status().message()); } updatedRecord += mutations.size(); } return updatedRecord; } void batchInsertData(google::cloud::spanner::Client client, std::int64_t batchSize) { namespace spanner = ::google::cloud::spanner; using ::google::cloud::StatusOr; auto commit_result = client.Commit( [&client, &batchSize]( spanner::Transaction const& txn) -> StatusOr<spanner::Mutations> { spanner::Mutations mutations; spanner::sys_time<std::chrono::nanoseconds> trainingNS = std::chrono::system_clock::now(); spanner::Timestamp trainingTime = spanner::MakeTimestamp(trainingNS).value(); for(std::int64_t i = 3; i <= batchSize; i++) { mutations.push_back(spanner::InsertMutationBuilder( "TestModels", {"CdsId", "TrainingTime"}) .EmplaceRow(i, trainingTime) .Build()); } return mutations; }); if (!commit_result) { throw std::runtime_error(commit_result.status().message()); } } } // namespace int main(int argc, char* argv[]) try { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " project-id instance-id database-id\n"; return 1; } spanner::Client readClient( spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3]))); spanner::Client writeClient( spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3]))); auto start = std::chrono::high_resolution_clock::now(); int updatedRecord = batchUpdateData(readClient, writeClient, BATCHSIZE); // batchInsertData(writeClient, BATCHSIZE); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start); std::cout << "Time taken : " << duration.count() << " milliseconds" << std::endl; std::cout << "Total updated records : " << updatedRecord << " milliseconds" << std::endl; return 1; } catch (std::exception const& ex) { std::cerr << "Standard exception raised: " << ex.what() << "\n"; return 1; }<|endoftext|>
<commit_before>#include "tentacle-arduino.h" #include "Arduino.h" #include <vector> TentacleArduino::TentacleArduino() { numPins = NUM_DIGITAL_PINS; // for(int i = 0; i < numPins; i++) { // config.push_back(Pin(i)); // } // Serial.flush(); } void TentacleArduino::setMode(Pin pin){ int input_mode = (pin.getPullup() ? INPUT_PULLUP : INPUT ); switch(pin.getAction()) { case Pin::digitalRead : case Pin::analogRead : default: pinMode(pin.getNumber(), input_mode); break; case Pin::digitalWrite : case Pin::servoWrite : case Pin::pwmWrite : pinMode(pin.getNumber(), OUTPUT); break; } } void TentacleArduino::digitalWrite(int pin, int value){ ::digitalWrite(pin, value); } void TentacleArduino::analogWrite(int pin, int value){ ::analogWrite(pin, value); } bool TentacleArduino::digitalRead(int pin){ return ::digitalRead(pin); } int TentacleArduino::analogRead(int pin){ return ::analogRead(pin); } <commit_msg>Erik tried to use pointers<commit_after>#include "tentacle-arduino.h" #include "Arduino.h" #include <vector> TentacleArduino::TentacleArduino() { numPins = NUM_DIGITAL_PINS; } void TentacleArduino::setMode(Pin pin){ int input_mode = (pin.getPullup() ? INPUT_PULLUP : INPUT ); switch(pin.getAction()) { case Pin::digitalRead : case Pin::analogRead : default: pinMode(pin.getNumber(), input_mode); break; case Pin::digitalWrite : case Pin::servoWrite : case Pin::pwmWrite : pinMode(pin.getNumber(), OUTPUT); break; } } void TentacleArduino::digitalWrite(int pin, int value){ ::digitalWrite(pin, value); } void TentacleArduino::analogWrite(int pin, int value){ ::analogWrite(pin, value); } bool TentacleArduino::digitalRead(int pin){ return ::digitalRead(pin); } int TentacleArduino::analogRead(int pin){ return ::analogRead(pin); } <|endoftext|>
<commit_before>// Copyright (c) 2012-2013 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sstream> #include <numeric> #include <boost/utility/value_init.hpp> #include <boost/interprocess/detail/atomic.hpp> #include <boost/limits.hpp> #include <boost/foreach.hpp> #include "misc_language.h" #include "include_base_utils.h" #include "cryptonote_basic_impl.h" #include "cryptonote_format_utils.h" #include "file_io_utils.h" #include "common/command_line.h" #include "string_coding.h" #include "storages/portable_storage_template_helper.h" using namespace epee; #include "miner.h" namespace cryptonote { namespace { const command_line::arg_descriptor<std::string> arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true}; const command_line::arg_descriptor<std::string> arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true}; const command_line::arg_descriptor<uint32_t> arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true}; } miner::miner(i_miner_handler* phandler):m_stop(1), m_template(boost::value_initialized<block>()), m_template_no(0), m_diffic(0), m_thread_index(0), m_phandler(phandler), m_height(0), m_pausers_count(0), m_threads_total(0), m_starter_nonce(0), m_last_hr_merge_time(0), m_hashes(0), m_do_print_hashrate(false), m_do_mining(false), m_current_hash_rate(0) { } //----------------------------------------------------------------------------------------------------- miner::~miner() { stop(); } //----------------------------------------------------------------------------------------------------- bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height) { CRITICAL_REGION_LOCAL(m_template_lock); m_template = bl; m_diffic = di; m_height = height; ++m_template_no; m_starter_nonce = crypto::rand<uint32_t>(); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_block_chain_update() { if(!is_mining()) return true; return request_block_template(); } //----------------------------------------------------------------------------------------------------- bool miner::request_block_template() { block bl = AUTO_VAL_INIT(bl); difficulty_type di = AUTO_VAL_INIT(di); uint64_t height = AUTO_VAL_INIT(height); cryptonote::blobdata extra_nonce; if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size()) { extra_nonce = m_extra_messages[m_config.current_extra_message_index]; } if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce)) { LOG_ERROR("Failed to get_block_template(), stopping mining"); return false; } set_block_template(bl, di, height); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_idle() { m_update_block_template_interval.do_call([&](){ if(is_mining())request_block_template(); return true; }); m_update_merge_hr_interval.do_call([&](){ merge_hr(); return true; }); return true; } //----------------------------------------------------------------------------------------------------- void miner::do_print_hashrate(bool do_hr) { m_do_print_hashrate = do_hr; } //----------------------------------------------------------------------------------------------------- void miner::merge_hr() { if(m_last_hr_merge_time && is_mining()) { m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1)); CRITICAL_REGION_LOCAL(m_last_hash_rates_lock); m_last_hash_rates.push_back(m_current_hash_rate); if(m_last_hash_rates.size() > 19) m_last_hash_rates.pop_front(); if(m_do_print_hashrate) { uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0); float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size()); std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << ENDL; } } m_last_hr_merge_time = misc_utils::get_tick_count(); m_hashes = 0; } //----------------------------------------------------------------------------------------------------- void miner::init_options(boost::program_options::options_description& desc) { command_line::add_arg(desc, arg_extra_messages); command_line::add_arg(desc, arg_start_mining); command_line::add_arg(desc, arg_mining_threads); } //----------------------------------------------------------------------------------------------------- bool miner::init(const boost::program_options::variables_map& vm) { if(command_line::has_arg(vm, arg_extra_messages)) { std::string buff; bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff); CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages)); std::vector<std::string> extra_vec; boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on ); m_extra_messages.resize(extra_vec.size()); for(size_t i = 0; i != extra_vec.size(); i++) { string_tools::trim(extra_vec[i]); if(!extra_vec[i].size()) continue; std::string buff = string_encoding::base64_decode(extra_vec[i]); if(buff != "0") m_extra_messages[i] = buff; } m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string(); m_config = AUTO_VAL_INIT(m_config); epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); LOG_PRINT_L0("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index); } if(command_line::has_arg(vm, arg_start_mining)) { if(!cryptonote::get_account_address_from_str(m_mine_address, command_line::get_arg(vm, arg_start_mining))) { LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled"); return false; } m_threads_total = 1; m_do_mining = true; if(command_line::has_arg(vm, arg_mining_threads)) { m_threads_total = command_line::get_arg(vm, arg_mining_threads); } } return true; } //----------------------------------------------------------------------------------------------------- bool miner::is_mining() { return !m_stop; } //----------------------------------------------------------------------------------------------------- bool miner::start(const account_public_address& adr, size_t threads_count, const boost::thread::attributes& attrs) { m_mine_address = adr; m_threads_total = static_cast<uint32_t>(threads_count); m_starter_nonce = crypto::rand<uint32_t>(); CRITICAL_REGION_LOCAL(m_threads_lock); if(is_mining()) { LOG_ERROR("Starting miner but it's already started"); return false; } if(!m_threads.empty()) { LOG_ERROR("Unable to start miner because there are active mining threads"); return false; } if(!m_template_no) request_block_template();//lets update block template boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0); boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0); for(size_t i = 0; i != threads_count; i++) { m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this))); } LOG_PRINT_L0("Mining has started with " << threads_count << " threads, good luck!" ) return true; } //----------------------------------------------------------------------------------------------------- uint64_t miner::get_speed() { if(is_mining()) return m_current_hash_rate; else return 0; } //----------------------------------------------------------------------------------------------------- void miner::send_stop_signal() { boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1); } //----------------------------------------------------------------------------------------------------- bool miner::stop() { send_stop_signal(); CRITICAL_REGION_LOCAL(m_threads_lock); BOOST_FOREACH(boost::thread& th, m_threads) th.join(); m_threads.clear(); LOG_PRINT_L0("Mining has been stopped, " << m_threads.size() << " finished" ); return true; } //----------------------------------------------------------------------------------------------------- bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height) { for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) { crypto::hash h; get_block_longhash(bl, h, height); if(check_hash(h, diffic)) { return true; } } return false; } //----------------------------------------------------------------------------------------------------- void miner::on_synchronized() { if(m_do_mining) { boost::thread::attributes attrs; attrs.set_stack_size(THREAD_STACK_SIZE); start(m_mine_address, m_threads_total, attrs); } } //----------------------------------------------------------------------------------------------------- void miner::pause() { CRITICAL_REGION_LOCAL(m_miners_count_lock); ++m_pausers_count; if(m_pausers_count == 1 && is_mining()) LOG_PRINT_L2("MINING PAUSED"); } //----------------------------------------------------------------------------------------------------- void miner::resume() { CRITICAL_REGION_LOCAL(m_miners_count_lock); --m_pausers_count; if(m_pausers_count < 0) { m_pausers_count = 0; LOG_PRINT_RED_L0("Unexpected miner::resume() called"); } if(!m_pausers_count && is_mining()) LOG_PRINT_L2("MINING RESUMED"); } //----------------------------------------------------------------------------------------------------- bool miner::worker_thread() { uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index); LOG_PRINT_L0("Miner thread was started ["<< th_local_index << "]"); log_space::log_singletone::set_thread_log_prefix(std::string("[miner ") + std::to_string(th_local_index) + "]"); uint32_t nonce = m_starter_nonce + th_local_index; uint64_t height = 0; difficulty_type local_diff = 0; uint32_t local_template_ver = 0; block b; while(!m_stop) { if(m_pausers_count)//anti split workaround { misc_utils::sleep_no_w(100); continue; } if(local_template_ver != m_template_no) { CRITICAL_REGION_BEGIN(m_template_lock); b = m_template; local_diff = m_diffic; height = m_height; CRITICAL_REGION_END(); local_template_ver = m_template_no; nonce = m_starter_nonce + th_local_index; } if(!local_template_ver)//no any set_block_template call { LOG_PRINT_L2("Block template not set yet"); epee::misc_utils::sleep_no_w(1000); continue; } b.nonce = nonce; crypto::hash h; get_block_longhash(b, h, height); if(check_hash(h, local_diff)) { //we lucky! ++m_config.current_extra_message_index; LOG_PRINT_GREEN("Found block for difficulty: " << local_diff, LOG_LEVEL_0); if(!m_phandler->handle_block_found(b)) { --m_config.current_extra_message_index; }else { //success update, lets update config epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); } } nonce+=m_threads_total; ++m_hashes; } LOG_PRINT_L0("Miner thread stopped ["<< th_local_index << "]"); return true; } //----------------------------------------------------------------------------------------------------- } <commit_msg>Update miner.cpp<commit_after>// Copyright (c) 2012-2013 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sstream> #include <numeric> #include <boost/utility/value_init.hpp> #include <boost/interprocess/detail/atomic.hpp> #include <boost/limits.hpp> #include <boost/foreach.hpp> #include "misc_language.h" #include "include_base_utils.h" #include "cryptonote_basic_impl.h" #include "cryptonote_format_utils.h" #include "file_io_utils.h" #include "common/command_line.h" #include "string_coding.h" #include "storages/portable_storage_template_helper.h" using namespace epee; #include "miner.h" extern "C" void slow_hash_allocate_state(); extern "C" void slow_hash_free_state(); namespace cryptonote { namespace { const command_line::arg_descriptor<std::string> arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true}; const command_line::arg_descriptor<std::string> arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true}; const command_line::arg_descriptor<uint32_t> arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true}; } miner::miner(i_miner_handler* phandler):m_stop(1), m_template(boost::value_initialized<block>()), m_template_no(0), m_diffic(0), m_thread_index(0), m_phandler(phandler), m_height(0), m_pausers_count(0), m_threads_total(0), m_starter_nonce(0), m_last_hr_merge_time(0), m_hashes(0), m_do_print_hashrate(false), m_do_mining(false), m_current_hash_rate(0) { } //----------------------------------------------------------------------------------------------------- miner::~miner() { stop(); } //----------------------------------------------------------------------------------------------------- bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height) { CRITICAL_REGION_LOCAL(m_template_lock); m_template = bl; m_diffic = di; m_height = height; ++m_template_no; m_starter_nonce = crypto::rand<uint32_t>(); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_block_chain_update() { if(!is_mining()) return true; return request_block_template(); } //----------------------------------------------------------------------------------------------------- bool miner::request_block_template() { block bl = AUTO_VAL_INIT(bl); difficulty_type di = AUTO_VAL_INIT(di); uint64_t height = AUTO_VAL_INIT(height); cryptonote::blobdata extra_nonce; if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size()) { extra_nonce = m_extra_messages[m_config.current_extra_message_index]; } if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce)) { LOG_ERROR("Failed to get_block_template(), stopping mining"); return false; } set_block_template(bl, di, height); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_idle() { m_update_block_template_interval.do_call([&](){ if(is_mining())request_block_template(); return true; }); m_update_merge_hr_interval.do_call([&](){ merge_hr(); return true; }); return true; } //----------------------------------------------------------------------------------------------------- void miner::do_print_hashrate(bool do_hr) { m_do_print_hashrate = do_hr; } //----------------------------------------------------------------------------------------------------- void miner::merge_hr() { if(m_last_hr_merge_time && is_mining()) { m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1)); CRITICAL_REGION_LOCAL(m_last_hash_rates_lock); m_last_hash_rates.push_back(m_current_hash_rate); if(m_last_hash_rates.size() > 19) m_last_hash_rates.pop_front(); if(m_do_print_hashrate) { uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0); float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size()); std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << ENDL; } } m_last_hr_merge_time = misc_utils::get_tick_count(); m_hashes = 0; } //----------------------------------------------------------------------------------------------------- void miner::init_options(boost::program_options::options_description& desc) { command_line::add_arg(desc, arg_extra_messages); command_line::add_arg(desc, arg_start_mining); command_line::add_arg(desc, arg_mining_threads); } //----------------------------------------------------------------------------------------------------- bool miner::init(const boost::program_options::variables_map& vm) { if(command_line::has_arg(vm, arg_extra_messages)) { std::string buff; bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff); CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages)); std::vector<std::string> extra_vec; boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on ); m_extra_messages.resize(extra_vec.size()); for(size_t i = 0; i != extra_vec.size(); i++) { string_tools::trim(extra_vec[i]); if(!extra_vec[i].size()) continue; std::string buff = string_encoding::base64_decode(extra_vec[i]); if(buff != "0") m_extra_messages[i] = buff; } m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string(); m_config = AUTO_VAL_INIT(m_config); epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); LOG_PRINT_L0("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index); } if(command_line::has_arg(vm, arg_start_mining)) { if(!cryptonote::get_account_address_from_str(m_mine_address, command_line::get_arg(vm, arg_start_mining))) { LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled"); return false; } m_threads_total = 1; m_do_mining = true; if(command_line::has_arg(vm, arg_mining_threads)) { m_threads_total = command_line::get_arg(vm, arg_mining_threads); } } return true; } //----------------------------------------------------------------------------------------------------- bool miner::is_mining() const { return !m_stop; } //----------------------------------------------------------------------------------------------------- const account_public_address& miner::get_mining_address() const { return m_mine_address; } //----------------------------------------------------------------------------------------------------- uint32_t miner::get_threads_count() const { return m_threads_total; } //----------------------------------------------------------------------------------------------------- bool miner::start(const account_public_address& adr, size_t threads_count, const boost::thread::attributes& attrs) { m_mine_address = adr; m_threads_total = static_cast<uint32_t>(threads_count); m_starter_nonce = crypto::rand<uint32_t>(); CRITICAL_REGION_LOCAL(m_threads_lock); if(is_mining()) { LOG_ERROR("Starting miner but it's already started"); return false; } if(!m_threads.empty()) { LOG_ERROR("Unable to start miner because there are active mining threads"); return false; } if(!m_template_no) request_block_template();//lets update block template boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0); boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0); for(size_t i = 0; i != threads_count; i++) { m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this))); } LOG_PRINT_L0("Mining has started with " << threads_count << " threads, good luck!" ) return true; } //----------------------------------------------------------------------------------------------------- uint64_t miner::get_speed() const { if(is_mining()) { return m_current_hash_rate; } else { return 0; } } //----------------------------------------------------------------------------------------------------- void miner::send_stop_signal() { boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1); } //----------------------------------------------------------------------------------------------------- bool miner::stop() { send_stop_signal(); CRITICAL_REGION_LOCAL(m_threads_lock); BOOST_FOREACH(boost::thread& th, m_threads) th.join(); m_threads.clear(); LOG_PRINT_L0("Mining has been stopped, " << m_threads.size() << " finished" ); return true; } //----------------------------------------------------------------------------------------------------- bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height) { for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) { crypto::hash h; get_block_longhash(bl, h, height); if(check_hash(h, diffic)) { return true; } } return false; } //----------------------------------------------------------------------------------------------------- void miner::on_synchronized() { if(m_do_mining) { boost::thread::attributes attrs; attrs.set_stack_size(THREAD_STACK_SIZE); start(m_mine_address, m_threads_total, attrs); } } //----------------------------------------------------------------------------------------------------- void miner::pause() { CRITICAL_REGION_LOCAL(m_miners_count_lock); ++m_pausers_count; if(m_pausers_count == 1 && is_mining()) LOG_PRINT_L2("MINING PAUSED"); } //----------------------------------------------------------------------------------------------------- void miner::resume() { CRITICAL_REGION_LOCAL(m_miners_count_lock); --m_pausers_count; if(m_pausers_count < 0) { m_pausers_count = 0; LOG_PRINT_RED_L0("Unexpected miner::resume() called"); } if(!m_pausers_count && is_mining()) LOG_PRINT_L2("MINING RESUMED"); } //----------------------------------------------------------------------------------------------------- bool miner::worker_thread() { uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index); LOG_PRINT_L0("Miner thread was started ["<< th_local_index << "]"); log_space::log_singletone::set_thread_log_prefix(std::string("[miner ") + std::to_string(th_local_index) + "]"); uint32_t nonce = m_starter_nonce + th_local_index; uint64_t height = 0; difficulty_type local_diff = 0; uint32_t local_template_ver = 0; block b; slow_hash_allocate_state(); while(!m_stop) { if(m_pausers_count)//anti split workaround { misc_utils::sleep_no_w(100); continue; } if(local_template_ver != m_template_no) { CRITICAL_REGION_BEGIN(m_template_lock); b = m_template; local_diff = m_diffic; height = m_height; CRITICAL_REGION_END(); local_template_ver = m_template_no; nonce = m_starter_nonce + th_local_index; } if(!local_template_ver)//no any set_block_template call { LOG_PRINT_L2("Block template not set yet"); epee::misc_utils::sleep_no_w(1000); continue; } b.nonce = nonce; crypto::hash h; get_block_longhash(b, h, height); if(check_hash(h, local_diff)) { //we lucky! ++m_config.current_extra_message_index; LOG_PRINT_GREEN("Found block for difficulty: " << local_diff, LOG_LEVEL_0); if(!m_phandler->handle_block_found(b)) { --m_config.current_extra_message_index; }else { //success update, lets update config epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); } } nonce+=m_threads_total; ++m_hashes; } slow_hash_free_state(); LOG_PRINT_L0("Miner thread stopped ["<< th_local_index << "]"); return true; } //----------------------------------------------------------------------------------------------------- } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_SEQUENCES_MAKE_SEQUENCE_HPP #define BOOST_BRIGAND_SEQUENCES_MAKE_SEQUENCE_HPP #include <brigand/functions/arithmetic/next.hpp> #include <brigand/functions/lambda/apply.hpp> #include <brigand/sequences/append.hpp> #include <brigand/sequences/list.hpp> namespace brigand { namespace detail { template<class Start, unsigned N, class Next, class... E> struct mksq8 : mksq8<brigand::apply<Next, Start>, N-1, Next, E..., Start> {}; template<class Start, class Next, class... E> struct mksq8<Start, 0, Next, E...> { using type = list<E...>; }; template<class Start, class Next, class... E> struct mksq8<Start, 1, Next, E...> { using type = list<E..., Start>; }; template<class Start, class Next> struct mksq8<Start, 8, Next> { using t1 = brigand::apply<Next, Start>; using t2 = brigand::apply<Next, t1>; using t3 = brigand::apply<Next, t2>; using t4 = brigand::apply<Next, t3>; using t5 = brigand::apply<Next, t4>; using t6 = brigand::apply<Next, t5>; using t7 = brigand::apply<Next, t6>; using type = list<Start, t1, t2, t3, t4, t5, t6, t7>; }; template<template<class...> class List, class Start, unsigned N, class Next, bool, class... L> struct make_sequence_impl : make_sequence_impl< List, brigand::apply<Next, typename mksq8<Start, 8, Next>::t7>, N-8, Next, (N-8<=8), L..., typename mksq8<Start, 8, Next>::type > {}; template<template<class...> class List, class Start, unsigned N, class Next, class... L> struct make_sequence_impl<List, Start, N, Next, true, L...> { using type = append<List<>, L..., typename mksq8<Start, N, Next>::type>; }; } template<class Start, unsigned N, class Next = next<_1>, template<class...> class List = list> using make_sequence = typename detail::make_sequence_impl<List, Start, N, Next, (N<=8)>::type; } #endif <commit_msg>Delete make_sequence.hpp<commit_after><|endoftext|>
<commit_before>#include "customfilesystemmodel.h" CustomFileSystemModel::CustomFileSystemModel() { } CustomFileSystemModel::~CustomFileSystemModel() { } QList<QPersistentModelIndex> CustomFileSystemModel::checkedIndexes() { return _checklist.toList(); } Qt::ItemFlags CustomFileSystemModel::flags(const QModelIndex &index) const { return QFileSystemModel::flags(index) | Qt::ItemIsUserCheckable; } QVariant CustomFileSystemModel::data(const QModelIndex &index, int role) const { if(role == Qt::CheckStateRole && index.column() == 0) { if(_checklist.contains(index)) { return Qt::Checked; } else if(_partialChecklist.contains(index)) { return Qt::PartiallyChecked; } else { // Return PartiallyChecked if any ancestor is checked. QModelIndex parent = index.parent(); while(parent.isValid()) { if(_checklist.contains(parent)) return Qt::PartiallyChecked; parent = parent.parent(); } } return Qt::Unchecked; } return QFileSystemModel::data(index, role); } QVariant CustomFileSystemModel::dataInternal(const QModelIndex &index) const { if(_checklist.contains(index)) return Qt::Checked; else if(_partialChecklist.contains(index)) return Qt::PartiallyChecked; else return Qt::Unchecked; } void CustomFileSystemModel::setIndexCheckState(const QModelIndex &index, const Qt::CheckState state) { if(dataInternal(index) != state) setDataInternal(index, state); } bool CustomFileSystemModel::hasCheckedSibling(const QModelIndex &index) { for(int i = 0; i < rowCount(index.parent()); i++) { QModelIndex sibling = index.sibling(i, index.column()); if(sibling.isValid()) { if(sibling == index) continue; if(dataInternal(sibling) != Qt::Unchecked) return true; } } return false; } bool CustomFileSystemModel::hasCheckedAncestor(const QModelIndex &index) { QModelIndex ancestor = index.parent(); while(ancestor.isValid()) { if(ancestor.data(Qt::CheckStateRole) == Qt::Checked) return true; ancestor = ancestor.parent(); } return false; } void CustomFileSystemModel::setUncheckedRecursive(const QModelIndex &index) { if(isDir(index)) { for(int i = 0; i < rowCount(index); i++) { QModelIndex child = index.child(i, index.column()); if(child.isValid()) { // Only alter a child if it was previously Checked or // PartiallyChecked. if(dataInternal(child) != Qt::Unchecked) { setDataInternal(child, Qt::Unchecked); if(isDir(child)) setUncheckedRecursive(child); } } } } } bool CustomFileSystemModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(role == Qt::CheckStateRole) { setDataInternal(index, value); QVector<int> selectionChangedRole; selectionChangedRole << SELECTION_CHANGED_ROLE; emit dataChanged(index, index, selectionChangedRole); return true; } return QFileSystemModel::setData(index, value, role); } void CustomFileSystemModel::setDataInternal(const QModelIndex &index, const QVariant &value) { if(value == Qt::Checked) { _partialChecklist.remove(index); _checklist.insert(index); // Recursively set PartiallyChecked on all ancestors, and make an // ordered list of checked ancestors. QModelIndex parent = index.parent(); QList<QModelIndex> checkedAncestors; while(parent.isValid()) { if((dataInternal(parent) == Qt::Checked) || hasCheckedAncestor(parent)) checkedAncestors << parent; // Set parent to be PartiallyChecked. setIndexCheckState(parent, Qt::PartiallyChecked); // Ascend to higher level of ancestor. parent = parent.parent(); } // Uncheck partially-selected siblings. Must be done after // unchecking ancestors (above), otherwise the emit() generated by // an unchecked sibling will still report PartiallyChecked. parent = index.parent(); QModelIndex previousParent = index; for(int j = 0; j < checkedAncestors.count(); j++) { parent = checkedAncestors.at(j); // Set any partially-selected siblings to be unchecked. for(int i = 0; i < rowCount(parent); i++) { QModelIndex child = parent.child(i, index.column()); if(child.isValid()) { // Avoid unchecking previous parent. if(child == previousParent) continue; if(data(child, Qt::CheckStateRole) == Qt::PartiallyChecked) setIndexCheckState(child, Qt::Unchecked); } } // Ascend to higher level of ancestor. previousParent = parent; parent = parent.parent(); } // Check descendants setUncheckedRecursive(index); } else if(value == Qt::PartiallyChecked) { _checklist.remove(index); _partialChecklist.insert(index); QModelIndex parent = index.parent(); if(parent.isValid() && (parent.data(Qt::CheckStateRole) == Qt::Unchecked)) setIndexCheckState(parent, Qt::PartiallyChecked); } else if(value == Qt::Unchecked) { _partialChecklist.remove(index); _checklist.remove(index); // Check ancestor QModelIndex parent = index.parent(); if(parent.isValid() && (parent.data(Qt::CheckStateRole) != Qt::Checked)) { if(hasCheckedSibling(index)) setIndexCheckState(parent, Qt::PartiallyChecked); else setIndexCheckState(parent, Qt::Unchecked); } } } void CustomFileSystemModel::reset() { _checklist.clear(); _partialChecklist.clear(); } <commit_msg>CustomFileSystemModel: re-indent<commit_after>#include "customfilesystemmodel.h" CustomFileSystemModel::CustomFileSystemModel() { } CustomFileSystemModel::~CustomFileSystemModel() { } QList<QPersistentModelIndex> CustomFileSystemModel::checkedIndexes() { return _checklist.toList(); } Qt::ItemFlags CustomFileSystemModel::flags(const QModelIndex &index) const { return QFileSystemModel::flags(index) | Qt::ItemIsUserCheckable; } QVariant CustomFileSystemModel::data(const QModelIndex &index, int role) const { if(role == Qt::CheckStateRole && index.column() == 0) { if(_checklist.contains(index)) { return Qt::Checked; } else if(_partialChecklist.contains(index)) { return Qt::PartiallyChecked; } else { // Return PartiallyChecked if any ancestor is checked. QModelIndex parent = index.parent(); while(parent.isValid()) { if(_checklist.contains(parent)) return Qt::PartiallyChecked; parent = parent.parent(); } } return Qt::Unchecked; } return QFileSystemModel::data(index, role); } QVariant CustomFileSystemModel::dataInternal(const QModelIndex &index) const { if(_checklist.contains(index)) return Qt::Checked; else if(_partialChecklist.contains(index)) return Qt::PartiallyChecked; else return Qt::Unchecked; } void CustomFileSystemModel::setIndexCheckState(const QModelIndex &index, const Qt::CheckState state) { if(dataInternal(index) != state) setDataInternal(index, state); } bool CustomFileSystemModel::hasCheckedSibling(const QModelIndex &index) { for(int i = 0; i < rowCount(index.parent()); i++) { QModelIndex sibling = index.sibling(i, index.column()); if(sibling.isValid()) { if(sibling == index) continue; if(dataInternal(sibling) != Qt::Unchecked) return true; } } return false; } bool CustomFileSystemModel::hasCheckedAncestor(const QModelIndex &index) { QModelIndex ancestor = index.parent(); while(ancestor.isValid()) { if(ancestor.data(Qt::CheckStateRole) == Qt::Checked) return true; ancestor = ancestor.parent(); } return false; } void CustomFileSystemModel::setUncheckedRecursive(const QModelIndex &index) { if(isDir(index)) { for(int i = 0; i < rowCount(index); i++) { QModelIndex child = index.child(i, index.column()); if(child.isValid()) { // Only alter a child if it was previously Checked or // PartiallyChecked. if(dataInternal(child) != Qt::Unchecked) { setDataInternal(child, Qt::Unchecked); if(isDir(child)) setUncheckedRecursive(child); } } } } } bool CustomFileSystemModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(role == Qt::CheckStateRole) { setDataInternal(index, value); QVector<int> selectionChangedRole; selectionChangedRole << SELECTION_CHANGED_ROLE; emit dataChanged(index, index, selectionChangedRole); return true; } return QFileSystemModel::setData(index, value, role); } void CustomFileSystemModel::setDataInternal(const QModelIndex &index, const QVariant &value) { if(value == Qt::Checked) { _partialChecklist.remove(index); _checklist.insert(index); // Recursively set PartiallyChecked on all ancestors, and make an // ordered list of checked ancestors. QModelIndex parent = index.parent(); QList<QModelIndex> checkedAncestors; while(parent.isValid()) { if((dataInternal(parent) == Qt::Checked) || hasCheckedAncestor(parent)) checkedAncestors << parent; // Set parent to be PartiallyChecked. setIndexCheckState(parent, Qt::PartiallyChecked); // Ascend to higher level of ancestor. parent = parent.parent(); } // Uncheck partially-selected siblings. Must be done after // unchecking ancestors (above), otherwise the emit() generated by // an unchecked sibling will still report PartiallyChecked. parent = index.parent(); QModelIndex previousParent = index; for(int j = 0; j < checkedAncestors.count(); j++) { parent = checkedAncestors.at(j); // Set any partially-selected siblings to be unchecked. for(int i = 0; i < rowCount(parent); i++) { QModelIndex child = parent.child(i, index.column()); if(child.isValid()) { // Avoid unchecking previous parent. if(child == previousParent) continue; if(data(child, Qt::CheckStateRole) == Qt::PartiallyChecked) setIndexCheckState(child, Qt::Unchecked); } } // Ascend to higher level of ancestor. previousParent = parent; parent = parent.parent(); } // Check descendants setUncheckedRecursive(index); } else if(value == Qt::PartiallyChecked) { _checklist.remove(index); _partialChecklist.insert(index); QModelIndex parent = index.parent(); if(parent.isValid() && (parent.data(Qt::CheckStateRole) == Qt::Unchecked)) setIndexCheckState(parent, Qt::PartiallyChecked); } else if(value == Qt::Unchecked) { _partialChecklist.remove(index); _checklist.remove(index); // Check ancestor QModelIndex parent = index.parent(); if(parent.isValid() && (parent.data(Qt::CheckStateRole) != Qt::Checked)) { if(hasCheckedSibling(index)) setIndexCheckState(parent, Qt::PartiallyChecked); else setIndexCheckState(parent, Qt::Unchecked); } } } void CustomFileSystemModel::reset() { _checklist.clear(); _partialChecklist.clear(); } <|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #include "granary/base/cast.h" #include "granary/cfg/instruction.h" #include "granary/cfg/iterator.h" #include "granary/cfg/operand.h" #include "granary/code/assemble/fragment.h" #include "granary/logging.h" #include "granary/module.h" namespace granary { namespace { // Log an individual edge between two fragments. static void LogFragmentEdge(LogLevel level, const Fragment *pred, const Fragment *frag) { Log(level, "f%p -> f%p;\n", reinterpret_cast<const void *>(pred), reinterpret_cast<const void *>(frag)); } // Log the outgoing edges of a fragment. static void LogFragmentEdges(LogLevel level, Fragment *frag) { for (auto succ : frag->successors) { if (succ) { LogFragmentEdge(level, frag, succ); } } } static const char *partition_color[] = { "aliceblue", "aquamarine", "aquamarine3", "bisque2", "brown1", "burlywood1", "cadetblue1", "chartreuse1", "chocolate1", "darkolivegreen3", "darkorchid2" }; enum { NUM_COLORS = sizeof partition_color / sizeof partition_color[0] }; static const char *FragmentBorder(const Fragment *frag) { if (auto code = DynamicCast<CodeFragment *>(frag)) { if (!code->stack.is_checked) { return "red"; } else if (!code->stack.is_valid) { return "white"; } } return "black"; } // Color the fragment according to the partition to which it belongs. This is // meant to be a visual cue, not a perfect association with the fragment's // partition id. static const char *FragmentBackground(const Fragment *frag) { if (IsA<ExitFragment *>(frag)) { return "white"; } auto stack_id = static_cast<size_t>(frag->partition->id); return stack_id ? partition_color[stack_id % NUM_COLORS] : "white"; } // Log the input-only operands. static void LogInputOperands(LogLevel level, NativeInstruction *instr) { auto sep = " "; instr->ForEachOperand([&] (Operand *op) { if (!op->IsWrite()) { OperandString op_str; op->EncodeToString(&op_str); auto prefix = op->IsConditionalRead() ? "cr " : ""; Log(level, "%s%s%s", sep, prefix, static_cast<const char *>(op_str)); sep = ", "; } }); } // Log the output operands. Some of these operands might also be inputs. static void LogOutputOperands(LogLevel level, NativeInstruction *instr) { auto sep = " -&gt; "; instr->ForEachOperand([&] (Operand *op) { if (op->IsWrite()) { auto prefix = op->IsRead() ? (op->IsConditionalWrite() ? "r/cw " : "r/w ") : (op->IsConditionalWrite() ? "cw " : ""); OperandString op_str; op->EncodeToString(&op_str); Log(level, "%s%s%s", sep, prefix, static_cast<const char *>(op_str)); sep = ", "; } }); } // Log the instructions of a fragment. static void LogInstructions(LogLevel level, const Fragment *frag) { for (auto instr : InstructionListIterator(frag->instrs)) { if (auto ninstr = DynamicCast<NativeInstruction *>(instr)) { if (ninstr->IsAppInstruction()) { Log(level, "<FONT POINT-SIZE=\"11\" FACE=\"Courier-Bold\">"); } Log(level, "%s", ninstr->OpCodeName()); LogInputOperands(level, ninstr); LogOutputOperands(level, ninstr); if (ninstr->IsAppInstruction()) { Log(level, "</FONT>"); } Log(level, "<BR ALIGN=\"LEFT\"/>"); // Keep instructions left-aligned. } } } // If this fragment is the head of a basic block then log the basic block's // entry address. static void LogBlockHeader(LogLevel level, const Fragment *frag) { if (IsA<PartitionEntryFragment *>(frag)) { Log(level, "partition entry|"); } else if (IsA<PartitionExitFragment *>(frag)) { Log(level, "partition exit|"); } else if (IsA<FlagEntryFragment *>(frag)) { Log(level, "flag entry|"); } else if (IsA<FlagExitFragment *>(frag)) { Log(level, "flag exit|"); } else if (IsA<ExitFragment *>(frag)) { Log(level, "exit"); } else if (auto code = DynamicCast<CodeFragment *>(frag)) { if (code->attr.block_meta && code->attr.is_block_head) { auto meta = MetaDataCast<ModuleMetaData *>(code->attr.block_meta); Log(level, "%p|", meta->start_pc); } } } // Log info about a fragment, including its decoded instructions. static void LogFragment(LogLevel level, const Fragment *frag) { Log(level, "f%p [fillcolor=%s color=%s label=<{", reinterpret_cast<const void *>(frag), FragmentBackground(frag), FragmentBorder(frag)); LogBlockHeader(level, frag); if (!IsA<ExitFragment *>(frag)) { LogInstructions(level, frag); Log(level, "}"); } Log(level, "}>];\n"); } } // namespace // Log a list of fragments as a DOT digraph. void Log(LogLevel level, FragmentList *frags) { Log(level, "digraph {\n" "node [fontname=courier shape=record" " nojustify=false labeljust=l style=filled];\n" "f0 [label=enter];\n"); LogFragmentEdge(level, nullptr, frags->First()); for (auto frag : FragmentIterator(frags)) { LogFragmentEdges(level, frag); LogFragment(level, frag); } Log(level, "}\n"); } } // namespace granary <commit_msg>Minor visual change to make instrumentation instructions indented instead of making app instructions a slightly different font.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #include "granary/base/cast.h" #include "granary/cfg/instruction.h" #include "granary/cfg/iterator.h" #include "granary/cfg/operand.h" #include "granary/code/assemble/fragment.h" #include "granary/logging.h" #include "granary/module.h" namespace granary { namespace { // Log an individual edge between two fragments. static void LogFragmentEdge(LogLevel level, const Fragment *pred, const Fragment *frag) { Log(level, "f%p -> f%p;\n", reinterpret_cast<const void *>(pred), reinterpret_cast<const void *>(frag)); } // Log the outgoing edges of a fragment. static void LogFragmentEdges(LogLevel level, Fragment *frag) { for (auto succ : frag->successors) { if (succ) { LogFragmentEdge(level, frag, succ); } } } static const char *partition_color[] = { "aliceblue", "aquamarine", "aquamarine3", "bisque2", "brown1", "burlywood1", "cadetblue1", "chartreuse1", "chocolate1", "darkolivegreen3", "darkorchid2" }; enum { NUM_COLORS = sizeof partition_color / sizeof partition_color[0] }; static const char *FragmentBorder(const Fragment *frag) { if (auto code = DynamicCast<CodeFragment *>(frag)) { if (!code->stack.is_checked) { return "red"; } else if (!code->stack.is_valid) { return "white"; } } return "black"; } // Color the fragment according to the partition to which it belongs. This is // meant to be a visual cue, not a perfect association with the fragment's // partition id. static const char *FragmentBackground(const Fragment *frag) { if (IsA<ExitFragment *>(frag)) { return "white"; } auto stack_id = static_cast<size_t>(frag->partition->id); return stack_id ? partition_color[stack_id % NUM_COLORS] : "white"; } // Log the input-only operands. static void LogInputOperands(LogLevel level, NativeInstruction *instr) { auto sep = " "; instr->ForEachOperand([&] (Operand *op) { if (!op->IsWrite()) { OperandString op_str; op->EncodeToString(&op_str); auto prefix = op->IsConditionalRead() ? "cr " : ""; Log(level, "%s%s%s", sep, prefix, static_cast<const char *>(op_str)); sep = ", "; } }); } // Log the output operands. Some of these operands might also be inputs. static void LogOutputOperands(LogLevel level, NativeInstruction *instr) { auto sep = " -&gt; "; instr->ForEachOperand([&] (Operand *op) { if (op->IsWrite()) { auto prefix = op->IsRead() ? (op->IsConditionalWrite() ? "r/cw " : "r/w ") : (op->IsConditionalWrite() ? "cw " : ""); OperandString op_str; op->EncodeToString(&op_str); Log(level, "%s%s%s", sep, prefix, static_cast<const char *>(op_str)); sep = ", "; } }); } // Log the instructions of a fragment. static void LogInstructions(LogLevel level, const Fragment *frag) { for (auto instr : InstructionListIterator(frag->instrs)) { if (auto ninstr = DynamicCast<NativeInstruction *>(instr)) { if (!ninstr->IsAppInstruction()) { Log(level, "&nbsp; "); } Log(level, "%s", ninstr->OpCodeName()); LogInputOperands(level, ninstr); LogOutputOperands(level, ninstr); Log(level, "<BR ALIGN=\"LEFT\"/>"); // Keep instructions left-aligned. } } } // If this fragment is the head of a basic block then log the basic block's // entry address. static void LogBlockHeader(LogLevel level, const Fragment *frag) { if (IsA<PartitionEntryFragment *>(frag)) { Log(level, "partition entry|"); } else if (IsA<PartitionExitFragment *>(frag)) { Log(level, "partition exit|"); } else if (IsA<FlagEntryFragment *>(frag)) { Log(level, "flag entry|"); } else if (IsA<FlagExitFragment *>(frag)) { Log(level, "flag exit|"); } else if (IsA<ExitFragment *>(frag)) { Log(level, "exit"); } else if (auto code = DynamicCast<CodeFragment *>(frag)) { if (code->attr.block_meta && code->attr.is_block_head) { auto meta = MetaDataCast<ModuleMetaData *>(code->attr.block_meta); Log(level, "%p|", meta->start_pc); } } } // Log info about a fragment, including its decoded instructions. static void LogFragment(LogLevel level, const Fragment *frag) { Log(level, "f%p [fillcolor=%s color=%s label=<{", reinterpret_cast<const void *>(frag), FragmentBackground(frag), FragmentBorder(frag)); LogBlockHeader(level, frag); if (!IsA<ExitFragment *>(frag)) { LogInstructions(level, frag); Log(level, "}"); } Log(level, "}>];\n"); } } // namespace // Log a list of fragments as a DOT digraph. void Log(LogLevel level, FragmentList *frags) { Log(level, "digraph {\n" "node [fontname=courier shape=record" " nojustify=false labeljust=l style=filled];\n" "f0 [label=enter];\n"); LogFragmentEdge(level, nullptr, frags->First()); for (auto frag : FragmentIterator(frags)) { LogFragmentEdges(level, frag); LogFragment(level, frag); } Log(level, "}\n"); } } // namespace granary <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "SimpleFontData.h" #include "Font.h" #include "FontCache.h" #include "FloatRect.h" #include "FontDescription.h" #include "Logging.h" #include "NotImplemented.h" #include "SkPaint.h" #include "SkTypeface.h" #include "SkTime.h" namespace WebCore { // Smallcaps versions of fonts are 70% the size of the normal font. static const float kSmallCapsFraction = 0.7f; void SimpleFontData::platformInit() { SkPaint paint; SkPaint::FontMetrics metrics; m_font.setupPaint(&paint); paint.getFontMetrics(&metrics); // Beware those who step here: This code is designed to match Win32 font // metrics *exactly*. if (metrics.fVDMXMetricsValid) { m_ascent = metrics.fVDMXAscent; m_descent = metrics.fVDMXDescent; } else { m_ascent = SkScalarCeil(-metrics.fAscent); m_descent = SkScalarCeil(metrics.fHeight) - m_ascent; } if (metrics.fXHeight) { m_xHeight = metrics.fXHeight; } else { // hack taken from the Windows port m_xHeight = static_cast<float>(m_ascent) * 0.56; } m_lineGap = SkScalarRound(metrics.fLeading); m_lineSpacing = m_ascent + m_descent + m_lineGap; // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is // calculated for us, but we need to calculate m_maxCharWidth and // m_avgCharWidth in order for text entry widgets to be sized correctly. m_maxCharWidth = SkScalarRound(metrics.fXRange * SkScalarRound(m_font.size())); if (metrics.fAvgCharWidth) { m_avgCharWidth = SkScalarRound(metrics.fAvgCharWidth); } else { m_avgCharWidth = m_xHeight; GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page(); if (glyphPageZero) { static const UChar32 x_char = 'x'; const Glyph x_glyph = glyphPageZero->glyphDataForCharacter(x_char).glyph; if (x_glyph) { m_avgCharWidth = widthForGlyph(x_glyph); } } } } void SimpleFontData::platformDestroy() { delete m_smallCapsFontData; } SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const { if (!m_smallCapsFontData) { m_smallCapsFontData = new SimpleFontData(FontPlatformData(m_font, fontDescription.computedSize() * kSmallCapsFraction)); } return m_smallCapsFontData; } bool SimpleFontData::containsCharacters(const UChar* characters, int length) const { SkPaint paint; static const unsigned kMaxBufferCount = 64; uint16_t glyphs[kMaxBufferCount]; m_font.setupPaint(&paint); paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); while (length > 0) { int n = SkMin32(length, SK_ARRAY_COUNT(glyphs)); // textToGlyphs takes a byte count so we double the character count. int count = paint.textToGlyphs(characters, n * 2, glyphs); for (int i = 0; i < count; i++) { if (0 == glyphs[i]) { return false; // missing glyph } } characters += n; length -= n; } return true; } void SimpleFontData::determinePitch() { m_treatAsFixedPitch = platformData().isFixedPitch(); } float SimpleFontData::platformWidthForGlyph(Glyph glyph) const { SkASSERT(sizeof(glyph) == 2); // compile-time assert SkPaint paint; m_font.setupPaint(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); SkScalar width = paint.measureText(&glyph, 2); return SkScalarToFloat(width); } } // namespace WebCore <commit_msg>Linux: Round font heights.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "SimpleFontData.h" #include "Font.h" #include "FontCache.h" #include "FloatRect.h" #include "FontDescription.h" #include "Logging.h" #include "NotImplemented.h" #include "SkPaint.h" #include "SkTypeface.h" #include "SkTime.h" namespace WebCore { // Smallcaps versions of fonts are 70% the size of the normal font. static const float kSmallCapsFraction = 0.7f; void SimpleFontData::platformInit() { SkPaint paint; SkPaint::FontMetrics metrics; m_font.setupPaint(&paint); paint.getFontMetrics(&metrics); // Beware those who step here: This code is designed to match Win32 font // metrics *exactly*. if (metrics.fVDMXMetricsValid) { m_ascent = metrics.fVDMXAscent; m_descent = metrics.fVDMXDescent; } else { m_ascent = SkScalarCeil(-metrics.fAscent); m_descent = SkScalarRound(metrics.fHeight) - m_ascent; } if (metrics.fXHeight) { m_xHeight = metrics.fXHeight; } else { // hack taken from the Windows port m_xHeight = static_cast<float>(m_ascent) * 0.56; } m_lineGap = SkScalarRound(metrics.fLeading); m_lineSpacing = m_ascent + m_descent + m_lineGap; // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is // calculated for us, but we need to calculate m_maxCharWidth and // m_avgCharWidth in order for text entry widgets to be sized correctly. m_maxCharWidth = SkScalarRound(metrics.fXRange * SkScalarRound(m_font.size())); if (metrics.fAvgCharWidth) { m_avgCharWidth = SkScalarRound(metrics.fAvgCharWidth); } else { m_avgCharWidth = m_xHeight; GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page(); if (glyphPageZero) { static const UChar32 x_char = 'x'; const Glyph x_glyph = glyphPageZero->glyphDataForCharacter(x_char).glyph; if (x_glyph) { m_avgCharWidth = widthForGlyph(x_glyph); } } } } void SimpleFontData::platformDestroy() { delete m_smallCapsFontData; } SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const { if (!m_smallCapsFontData) { m_smallCapsFontData = new SimpleFontData(FontPlatformData(m_font, fontDescription.computedSize() * kSmallCapsFraction)); } return m_smallCapsFontData; } bool SimpleFontData::containsCharacters(const UChar* characters, int length) const { SkPaint paint; static const unsigned kMaxBufferCount = 64; uint16_t glyphs[kMaxBufferCount]; m_font.setupPaint(&paint); paint.setTextEncoding(SkPaint::kUTF16_TextEncoding); while (length > 0) { int n = SkMin32(length, SK_ARRAY_COUNT(glyphs)); // textToGlyphs takes a byte count so we double the character count. int count = paint.textToGlyphs(characters, n * 2, glyphs); for (int i = 0; i < count; i++) { if (0 == glyphs[i]) { return false; // missing glyph } } characters += n; length -= n; } return true; } void SimpleFontData::determinePitch() { m_treatAsFixedPitch = platformData().isFixedPitch(); } float SimpleFontData::platformWidthForGlyph(Glyph glyph) const { SkASSERT(sizeof(glyph) == 2); // compile-time assert SkPaint paint; m_font.setupPaint(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); SkScalar width = paint.measureText(&glyph, 2); return SkScalarToFloat(width); } } // namespace WebCore <|endoftext|>
<commit_before>/* * mmapifstream.cpp * openc2e * * Created by Alyssa Milburn on Sat Jul 24 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. * */ #include "mmapifstream.h" #include "openc2e.h" #ifdef _WIN32 #include <windows.h> #else // assume POSIX #include <sys/types.h> #include <sys/mman.h> #endif #include <iostream> // debug needs only mmapifstream::mmapifstream(std::string filename) { live = false; mmapopen(filename); } void mmapifstream::mmapopen(std::string filename) { open(filename.c_str()); if (!is_open()) return; #ifdef _WIN32 // todo: store the handle somewhere? HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); void *mapr = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0); #else // todo: store the FILE* somewhere? FILE *f = fopen(filename.c_str(), "r"); assert(f); /* if (!f) { close(); setstate(failbit); perror("fopen"); return; } */ // now do the mmap (work out filesize, then mmap) int fno = fileno(f); seekg(0, std::ios::end); filesize = tellg(); assert((int)filesize != -1); seekg(0, std::ios::beg); void *mapr = mmap(0, filesize, PROT_READ, MAP_PRIVATE, fno, 0); #endif assert(mapr != (void *)-1); map = (char *)mapr; live = true; } mmapifstream::~mmapifstream() { if (live) #ifdef _WIN32 UnmapViewOfFile(map); #else munmap(map, filesize); #endif } /* vim: set noet: */ <commit_msg>close the file handle on POSIX after we're done with it<commit_after>/* * mmapifstream.cpp * openc2e * * Created by Alyssa Milburn on Sat Jul 24 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. * */ #include "mmapifstream.h" #include "openc2e.h" #ifdef _WIN32 #include <windows.h> #else // assume POSIX #include <sys/types.h> #include <sys/mman.h> #endif #include <iostream> // debug needs only mmapifstream::mmapifstream(std::string filename) { live = false; mmapopen(filename); } void mmapifstream::mmapopen(std::string filename) { open(filename.c_str()); if (!is_open()) return; #ifdef _WIN32 // todo: store the handle somewhere? HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); void *mapr = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0); #else FILE *f = fopen(filename.c_str(), "r"); assert(f); /* if (!f) { close(); setstate(failbit); perror("fopen"); return; } */ // now do the mmap (work out filesize, then mmap) int fno = fileno(f); seekg(0, std::ios::end); filesize = tellg(); assert((int)filesize != -1); seekg(0, std::ios::beg); void *mapr = mmap(0, filesize, PROT_READ, MAP_PRIVATE, fno, 0); fclose(f); // we don't need it, now! #endif assert(mapr != (void *)-1); map = (char *)mapr; live = true; } mmapifstream::~mmapifstream() { if (live) #ifdef _WIN32 UnmapViewOfFile(map); #else munmap(map, filesize); #endif } /* vim: set noet: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: htmlfile.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-12-14 15:35:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <toolkit/htmlfile.hxx> // NOT FULLY DECLARED SERVICES #include <cosv/file.hxx> #include <udm/html/htmlitem.hxx> namespace { bool bUse_OOoFrameDiv = true; const String C_sOOoFrameDiv_IdlId("adc-idlref"); } using namespace csi; using csi::xml::AnAttribute; DocuFile_Html::DocuFile_Html() : sFilePath(), sTitle(), sLocation(), sStyle(), sCssFile(), sCopyright(), aBodyData(), aBuffer(60000) // Grows dynamically, when necessary. { } void DocuFile_Html::SetLocation( const csv::ploc::Path & i_rFilePath ) { StreamLock sPath(1000); i_rFilePath.Get( sPath() ); sFilePath = sPath().c_str(); } void DocuFile_Html::SetTitle( const char * i_sTitle ) { sTitle = i_sTitle; } void DocuFile_Html::SetInlineStyle( const char * i_sStyle ) { sStyle = i_sStyle; } void DocuFile_Html::SetRelativeCssPath( const char * i_sCssFile_relativePath ) { sCssFile = i_sCssFile_relativePath; } void DocuFile_Html::SetCopyright( const char * i_sCopyright ) { sCopyright = i_sCopyright; } void DocuFile_Html::EmptyBody() { aBodyData.SetContent(0); if (bUse_OOoFrameDiv) { // Insert <div> tag to allow better formatting for OOo. aBodyData << new xml::XmlCode("<div id=\"") << new xml::XmlCode(C_sOOoFrameDiv_IdlId) << new xml::XmlCode("\">\n\n"); } aBodyData >> *new html::Label( "_top_" ) << " "; } bool DocuFile_Html::CreateFile() { csv::File aFile(sFilePath, csv::CFM_CREATE); if (NOT aFile.open()) { Cerr() << "Can't create file " << sFilePath << "." << Endl(); return false; } WriteHeader(aFile); WriteBody(aFile); // Write end static const char sCompletion[] = "\n</html>\n"; aFile.write( sCompletion ); aFile.close(); Cout() << '.' << Flush(); return true; } void DocuFile_Html::WriteHeader( csv::File & io_aFile ) { aBuffer.reset(); static const char s1[] = "<html>\n<head>\n<title>"; static const char s2[] = "</title>\n" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"; aBuffer.write( s1 ); aBuffer.write( sTitle ); aBuffer.write( s2 ); if (NOT sCssFile.empty()) { static const char s3[] = "<link rel=\"stylesheet\" type=\"text/css\" href=\""; static const char s4[] = "\">\n"; aBuffer.write(s3); aBuffer.write(sCssFile); aBuffer.write(s4); } if (NOT sStyle.empty()) { static const char s5[] = "<style>"; static const char s6[] = "</style>\n"; aBuffer.write(s5); aBuffer.write(sStyle); aBuffer.write(s6); } static const char s7[] = "</head>\n"; aBuffer.write(s7); io_aFile.write(aBuffer.c_str(), aBuffer.size()); } void DocuFile_Html::WriteBody( csv::File & io_aFile ) { aBuffer.reset(); aBodyData >> *new html::Link( "#_top_" ) << "Top of Page"; if ( sCopyright.length() > 0 ) { aBodyData << new xml::XmlCode("<hr size=\"3\">"); aBodyData >> *new html::Paragraph << new html::ClassAttr( "copyright" ) << new xml::AnAttribute( "align", "center" ) << new xml::XmlCode(sCopyright); } if (bUse_OOoFrameDiv) { // Insert <div> tag to allow better formatting for OOo. aBodyData << new xml::XmlCode("\n</div> <!-- id=\"") << new xml::XmlCode(C_sOOoFrameDiv_IdlId) << new xml::XmlCode("\" -->\n"); } aBodyData.WriteOut(aBuffer); io_aFile.write(aBuffer.c_str(), aBuffer.size()); } <commit_msg>INTEGRATION: CWS pchfix02 (1.6.18); FILE MERGED 2006/09/01 17:15:38 kaib 1.6.18.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: htmlfile.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 16:53:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_autodoc.hxx" #include <precomp.h> #include <toolkit/htmlfile.hxx> // NOT FULLY DECLARED SERVICES #include <cosv/file.hxx> #include <udm/html/htmlitem.hxx> namespace { bool bUse_OOoFrameDiv = true; const String C_sOOoFrameDiv_IdlId("adc-idlref"); } using namespace csi; using csi::xml::AnAttribute; DocuFile_Html::DocuFile_Html() : sFilePath(), sTitle(), sLocation(), sStyle(), sCssFile(), sCopyright(), aBodyData(), aBuffer(60000) // Grows dynamically, when necessary. { } void DocuFile_Html::SetLocation( const csv::ploc::Path & i_rFilePath ) { StreamLock sPath(1000); i_rFilePath.Get( sPath() ); sFilePath = sPath().c_str(); } void DocuFile_Html::SetTitle( const char * i_sTitle ) { sTitle = i_sTitle; } void DocuFile_Html::SetInlineStyle( const char * i_sStyle ) { sStyle = i_sStyle; } void DocuFile_Html::SetRelativeCssPath( const char * i_sCssFile_relativePath ) { sCssFile = i_sCssFile_relativePath; } void DocuFile_Html::SetCopyright( const char * i_sCopyright ) { sCopyright = i_sCopyright; } void DocuFile_Html::EmptyBody() { aBodyData.SetContent(0); if (bUse_OOoFrameDiv) { // Insert <div> tag to allow better formatting for OOo. aBodyData << new xml::XmlCode("<div id=\"") << new xml::XmlCode(C_sOOoFrameDiv_IdlId) << new xml::XmlCode("\">\n\n"); } aBodyData >> *new html::Label( "_top_" ) << " "; } bool DocuFile_Html::CreateFile() { csv::File aFile(sFilePath, csv::CFM_CREATE); if (NOT aFile.open()) { Cerr() << "Can't create file " << sFilePath << "." << Endl(); return false; } WriteHeader(aFile); WriteBody(aFile); // Write end static const char sCompletion[] = "\n</html>\n"; aFile.write( sCompletion ); aFile.close(); Cout() << '.' << Flush(); return true; } void DocuFile_Html::WriteHeader( csv::File & io_aFile ) { aBuffer.reset(); static const char s1[] = "<html>\n<head>\n<title>"; static const char s2[] = "</title>\n" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"; aBuffer.write( s1 ); aBuffer.write( sTitle ); aBuffer.write( s2 ); if (NOT sCssFile.empty()) { static const char s3[] = "<link rel=\"stylesheet\" type=\"text/css\" href=\""; static const char s4[] = "\">\n"; aBuffer.write(s3); aBuffer.write(sCssFile); aBuffer.write(s4); } if (NOT sStyle.empty()) { static const char s5[] = "<style>"; static const char s6[] = "</style>\n"; aBuffer.write(s5); aBuffer.write(sStyle); aBuffer.write(s6); } static const char s7[] = "</head>\n"; aBuffer.write(s7); io_aFile.write(aBuffer.c_str(), aBuffer.size()); } void DocuFile_Html::WriteBody( csv::File & io_aFile ) { aBuffer.reset(); aBodyData >> *new html::Link( "#_top_" ) << "Top of Page"; if ( sCopyright.length() > 0 ) { aBodyData << new xml::XmlCode("<hr size=\"3\">"); aBodyData >> *new html::Paragraph << new html::ClassAttr( "copyright" ) << new xml::AnAttribute( "align", "center" ) << new xml::XmlCode(sCopyright); } if (bUse_OOoFrameDiv) { // Insert <div> tag to allow better formatting for OOo. aBodyData << new xml::XmlCode("\n</div> <!-- id=\"") << new xml::XmlCode(C_sOOoFrameDiv_IdlId) << new xml::XmlCode("\" -->\n"); } aBodyData.WriteOut(aBuffer); io_aFile.write(aBuffer.c_str(), aBuffer.size()); } <|endoftext|>
<commit_before>/* * kmeans.cpp * * Created on: Mar 13, 2016 * Author: zxi */ /* * kmeans.cpp * * Created on: Mar 12, 2016 * Author: zxi */ #include <iostream> #include "libclustering/Clustering.h" using namespace masc::clustering; int main(int argc, char** argv) { auto X = Eigen::MatrixXd::Random(100, 3); KMeans kmeans(4); auto labels = kmeans.fit_predit(X); for (int i = 0; i < labels.rows(); ++i) std::cout << X.row(i) << " " << labels(i) << std::endl; } <commit_msg>Update kmeans.cpp<commit_after>/* * kmeans.cpp * * Created on: Mar 13, 2016 * Author: zxi */ #include <iostream> #include "libclustering/Clustering.h" using namespace masc::clustering; int main(int argc, char** argv) { auto X = Eigen::MatrixXd::Random(100, 3); KMeans kmeans(4); auto labels = kmeans.fit_predit(X); for (int i = 0; i < labels.rows(); ++i) std::cout << X.row(i) << " " << labels(i) << std::endl; } <|endoftext|>