text
stringlengths
54
60.6k
<commit_before>#include "cnn/devices.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <unsupported/Eigen/CXX11/Tensor> #include "cnn/cuda.h" #include "cnn/cnn.h" using namespace std; namespace cnn { DeviceMempoolSizes::DeviceMempoolSizes(size_t total_size) { used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } DeviceMempoolSizes::DeviceMempoolSizes(size_t fx_s, size_t dEdfs_s, size_t ps_s) { used[0] = fx_s; used[1] = dEdfs_s; used[2] = ps_s; } DeviceMempoolSizes::DeviceMempoolSizes(const std::string & descriptor) { vector<string> strs; boost::algorithm::split(strs, descriptor, boost::is_any_of(",")); if(strs.size() == 1) { size_t total_size = stoi(strs[0]); used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } else if(strs.size() == 3) { used[0] = stoi(strs[0]); used[1] = stoi(strs[1]); used[2] = stoi(strs[2]); } } Device::~Device() {} DeviceMempoolSizes Device::mark(ComputationGraph *cg) { cg->incremental_forward(); // needed so that we actually allocate the needed memory // for all existing nodes. return DeviceMempoolSizes(pools[0]->used, pools[1]->used, pools[2]->used); } void Device::revert(const DeviceMempoolSizes & cp) { assert(cp.used[0] <= pools[0]->used); pools[0]->used = cp.used[0]; assert(cp.used[1] <= pools[1]->used); pools[1]->used = cp.used[1]; assert(cp.used[2] <= pools[2]->used); pools[2]->used = cp.used[2]; } void Device::allocate_tensor(DeviceMempool mp, Tensor & tens) { assert(mp != DeviceMempool::NONE); assert(pools[(int)mp] != nullptr); tens.v = (float*)pools[(int)mp]->allocate(tens.d.size() * sizeof(float)); tens.mem_pool = mp; } #if HAVE_CUDA Device_GPU::Device_GPU(int my_id, const DeviceMempoolSizes & mbs, int device_id) : Device(my_id, DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) { CUDA_CHECK(cudaSetDevice(device_id)); CUBLAS_CHECK(cublasCreate(&cublas_handle)); CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE)); kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float)); float minusone = -1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice)); float one = 1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice)); float zero = 0; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice)); // Initialize the Eigen device estream = new Eigen::CudaStreamDevice(device_id); edevice = new Eigen::GpuDevice(estream); // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &gpu_mem); } Device_GPU::~Device_GPU() {} #endif Device_CPU::Device_CPU(int my_id, const DeviceMempoolSizes & mbs, bool shared) : Device(my_id, DeviceType::CPU, &cpu_mem), shmem(mem) { if (shared) shmem = new SharedAllocator(); kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_ONE = 1; kSCALAR_ZERO = (float*) mem->malloc(sizeof(float)); *kSCALAR_ZERO = 0; // Initialize the Eigen device edevice = new Eigen::DefaultDevice; // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &cpu_mem); } Device_CPU::~Device_CPU() {} } // namespace cnn <commit_msg>Fixed accidental removal of support for shared memory parameters<commit_after>#include "cnn/devices.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <unsupported/Eigen/CXX11/Tensor> #include "cnn/cuda.h" #include "cnn/cnn.h" using namespace std; namespace cnn { DeviceMempoolSizes::DeviceMempoolSizes(size_t total_size) { used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } DeviceMempoolSizes::DeviceMempoolSizes(size_t fx_s, size_t dEdfs_s, size_t ps_s) { used[0] = fx_s; used[1] = dEdfs_s; used[2] = ps_s; } DeviceMempoolSizes::DeviceMempoolSizes(const std::string & descriptor) { vector<string> strs; boost::algorithm::split(strs, descriptor, boost::is_any_of(",")); if(strs.size() == 1) { size_t total_size = stoi(strs[0]); used[0] = total_size/3; used[1] = total_size/3; used[2] = total_size/3; } else if(strs.size() == 3) { used[0] = stoi(strs[0]); used[1] = stoi(strs[1]); used[2] = stoi(strs[2]); } } Device::~Device() {} DeviceMempoolSizes Device::mark(ComputationGraph *cg) { cg->incremental_forward(); // needed so that we actually allocate the needed memory // for all existing nodes. return DeviceMempoolSizes(pools[0]->used, pools[1]->used, pools[2]->used); } void Device::revert(const DeviceMempoolSizes & cp) { assert(cp.used[0] <= pools[0]->used); pools[0]->used = cp.used[0]; assert(cp.used[1] <= pools[1]->used); pools[1]->used = cp.used[1]; assert(cp.used[2] <= pools[2]->used); pools[2]->used = cp.used[2]; } void Device::allocate_tensor(DeviceMempool mp, Tensor & tens) { assert(mp != DeviceMempool::NONE); assert(pools[(int)mp] != nullptr); tens.v = (float*)pools[(int)mp]->allocate(tens.d.size() * sizeof(float)); tens.mem_pool = mp; } #if HAVE_CUDA Device_GPU::Device_GPU(int my_id, const DeviceMempoolSizes & mbs, int device_id) : Device(my_id, DeviceType::GPU, &gpu_mem), cuda_device_id(device_id), gpu_mem(device_id) { CUDA_CHECK(cudaSetDevice(device_id)); CUBLAS_CHECK(cublasCreate(&cublas_handle)); CUBLAS_CHECK(cublasSetPointerMode(cublas_handle, CUBLAS_POINTER_MODE_DEVICE)); kSCALAR_MINUSONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ONE = (float*)gpu_mem.malloc(sizeof(float)); kSCALAR_ZERO = (float*)gpu_mem.malloc(sizeof(float)); float minusone = -1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_MINUSONE, &minusone, sizeof(float), cudaMemcpyHostToDevice)); float one = 1; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ONE, &one, sizeof(float), cudaMemcpyHostToDevice)); float zero = 0; CUDA_CHECK(cudaMemcpyAsync(kSCALAR_ZERO, &zero, sizeof(float), cudaMemcpyHostToDevice)); // Initialize the Eigen device estream = new Eigen::CudaStreamDevice(device_id); edevice = new Eigen::GpuDevice(estream); // this is the big memory allocation. for(size_t i = 0; i < 3; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &gpu_mem); } Device_GPU::~Device_GPU() {} #endif Device_CPU::Device_CPU(int my_id, const DeviceMempoolSizes & mbs, bool shared) : Device(my_id, DeviceType::CPU, &cpu_mem), shmem(mem) { if (shared) shmem = new SharedAllocator(); kSCALAR_MINUSONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (float*) mem->malloc(sizeof(float)); *kSCALAR_ONE = 1; kSCALAR_ZERO = (float*) mem->malloc(sizeof(float)); *kSCALAR_ZERO = 0; // Initialize the Eigen device edevice = new Eigen::DefaultDevice; // this is the big memory allocation. for(size_t i = 0; i < 2; ++i) pools[i] = new AlignedMemoryPool((mbs.used[i] << 20), &cpu_mem); pools[2] = new AlignedMemoryPool((mbs.used[2] << 20), shmem); } Device_CPU::~Device_CPU() {} } // namespace cnn <|endoftext|>
<commit_before>// Copyright © 2012, Université catholique de Louvain // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <mozart.hh> #include <boostenv.hh> #include <iostream> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/program_options.hpp> using namespace mozart; namespace fs = boost::filesystem; namespace po = boost::program_options; std::string envVarToOptionName(const std::string& varName) { if ((varName == "OZ_HOME") || (varName == "OZHOME")) return "home"; else return ""; } atom_t strToAtom(VM vm, const std::string& str) { auto mozartStr = toUTF<nchar>(makeLString(str.c_str(), str.size())); return vm->getAtom(mozartStr.length, mozartStr.string); } atom_t pathToAtom(VM vm, const fs::path& path) { return strToAtom(vm, path.native()); } int main(int argc, char** argv) { // CONFIGURATION VARIABLES fs::path ozHome, initFunctorPath, baseFunctorPath; std::string ozSearchPath, ozSearchLoad, appURL; std::vector<std::string> appArgs; bool appGUI; // DEFINE OPTIONS po::options_description generic("Generic options"); generic.add_options() ("help", "produce help message"); po::options_description config("Configuration"); config.add_options() ("home", po::value<fs::path>(&ozHome), "path to the home of the installation") ("init", po::value<fs::path>(&initFunctorPath), "path to the Init.ozf functor") ("search-path", po::value<std::string>(&ozSearchPath), "search path") ("search-load", po::value<std::string>(&ozSearchLoad), "search load") ("gui", "GUI mode"); po::options_description hidden("Hidden options"); hidden.add_options() ("base", po::value<fs::path>(&baseFunctorPath), "path to the Base.ozf functor") ("app-url", po::value<std::string>(&appURL), "application URL") ("app-args", po::value<std::vector<std::string>>(&appArgs), "application arguments"); po::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); po::options_description environment_options; environment_options.add(config); po::options_description visible_options("Allowed options"); visible_options.add(generic).add(config); po::positional_options_description positional_options; positional_options.add("app-url", 1); positional_options.add("app-args", -1); // PARSE OPTIONS po::variables_map varMap; po::store(po::command_line_parser(argc, argv) .options(cmdline_options) .positional(positional_options) .run(), varMap); po::store(po::parse_environment(environment_options, &envVarToOptionName), varMap); po::notify(varMap); // READ OPTIONS if (varMap.count("help") != 0) { std::cout << visible_options << "\n"; return 0; } // Hacky way to guess if we are in a build setting fs::path appPath = fs::path(argv[0]).parent_path(); bool isBuildSetting = appPath.filename() == "emulator"; if (ozHome.empty()) { if (isBuildSetting) ozHome = appPath.parent_path().parent_path(); else ozHome = appPath.parent_path(); if (ozHome.empty()) ozHome = "."; } if (initFunctorPath.empty()) { if (isBuildSetting) initFunctorPath = ozHome / "lib" / "cache" / "Init.ozf"; else initFunctorPath = ozHome / "share" / "mozart" / "cache" / "Init.ozf"; } bool useBaseFunctor = varMap.count("base") != 0; appGUI = varMap.count("gui") != 0; // SET UP THE VM AND RUN boostenv::BoostBasedVM boostBasedVM; VM vm = boostBasedVM.vm; // Set some properties { auto& properties = vm->getPropertyRegistry(); atom_t ozHomeAtom = pathToAtom(vm, ozHome); properties.registerValueProp( vm, MOZART_STR("oz.home"), ozHomeAtom); properties.registerValueProp( vm, MOZART_STR("oz.emulator.home"), ozHomeAtom); properties.registerValueProp( vm, MOZART_STR("oz.configure.home"), ozHomeAtom); if (varMap.count("search-path") != 0) properties.registerValueProp( vm, MOZART_STR("oz.search.path"), strToAtom(vm, ozSearchPath)); if (varMap.count("search-load") != 0) properties.registerValueProp( vm, MOZART_STR("oz.search.load"), strToAtom(vm, ozSearchLoad)); auto decodedURL = toUTF<nchar>(makeLString(appURL.c_str())); auto appURLAtom = vm->getAtom(decodedURL.length, decodedURL.string); properties.registerValueProp( vm, MOZART_STR("application.url"), appURLAtom); OzListBuilder argsBuilder(vm); for (auto& arg: appArgs) { auto decodedArg = toUTF<nchar>(makeLString(arg.c_str())); argsBuilder.push_back(vm, vm->getAtom(decodedArg.length, decodedArg.string)); } properties.registerValueProp( vm, MOZART_STR("application.args"), argsBuilder.get(vm)); properties.registerValueProp( vm, MOZART_STR("application.gui"), appGUI); } // Some protected nodes ProtectedNode baseEnv, initFunctor; // Load the Base environment if required if (useBaseFunctor) { baseEnv = vm->protect(OptVar::build(vm)); UnstableNode baseValue; auto& bootLoader = boostBasedVM.getBootLoader(); if (!bootLoader(vm, baseFunctorPath.native(), baseValue)) { std::cerr << "panic: could not load Base functor at " << baseFunctorPath << std::endl; return 1; } // Create the thread that loads the Base environment if (Callable(baseValue).isProcedure(vm)) { ozcalls::asyncOzCall(vm, baseValue, *baseEnv); } else { // Assume it is a functor that does not import anything UnstableNode applyAtom = build(vm, MOZART_STR("apply")); UnstableNode applyProc = Dottable(baseValue).dot(vm, applyAtom); UnstableNode importParam = build(vm, MOZART_STR("import")); ozcalls::asyncOzCall(vm, applyProc, importParam, *baseEnv); } boostBasedVM.run(); } // Load the Init functor { initFunctor = vm->protect(OptVar::build(vm)); UnstableNode initValue; auto& bootLoader = boostBasedVM.getBootLoader(); if (!bootLoader(vm, initFunctorPath.native(), initValue)) { std::cerr << "panic: could not load Init functor at " << initFunctorPath << std::endl; return 1; } // Create the thread that loads the Init functor if (Callable(initValue).isProcedure(vm)) { if (!useBaseFunctor) { std::cerr << "panic: Init.ozf is a procedure, " << "but I have no Base to give to it" << std::endl; return 1; } ozcalls::asyncOzCall(vm, initValue, *baseEnv, *initFunctor); boostBasedVM.run(); } else { // Assume it is already the Init functor DataflowVariable(*initFunctor).bind(vm, initValue); } } // Apply the Init functor { auto ApplyAtom = build(vm, MOZART_STR("apply")); auto ApplyProc = Dottable(*initFunctor).dot(vm, ApplyAtom); auto BootModule = vm->findBuiltinModule(MOZART_STR("Boot")); auto ImportRecord = buildRecord( vm, buildArity(vm, MOZART_STR("import"), MOZART_STR("Boot")), BootModule); ozcalls::asyncOzCall(vm, ApplyProc, ImportRecord, OptVar::build(vm)); baseEnv.reset(); initFunctor.reset(); boostBasedVM.run(); } } <commit_msg>Separate parsing of env vars and fallback env vars.<commit_after>// Copyright © 2012, Université catholique de Louvain // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <mozart.hh> #include <boostenv.hh> #include <iostream> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/program_options.hpp> using namespace mozart; namespace fs = boost::filesystem; namespace po = boost::program_options; std::string envVarToOptionName(const std::string& varName) { if (varName == "OZ_HOME") return "home"; else return ""; } std::string envVarToOptionNameFallback(const std::string& varName) { if (varName == "OZHOME") return "home"; else return ""; } atom_t strToAtom(VM vm, const std::string& str) { auto mozartStr = toUTF<nchar>(makeLString(str.c_str(), str.size())); return vm->getAtom(mozartStr.length, mozartStr.string); } atom_t pathToAtom(VM vm, const fs::path& path) { return strToAtom(vm, path.native()); } int main(int argc, char** argv) { // CONFIGURATION VARIABLES fs::path ozHome, initFunctorPath, baseFunctorPath; std::string ozSearchPath, ozSearchLoad, appURL; std::vector<std::string> appArgs; bool appGUI; // DEFINE OPTIONS po::options_description generic("Generic options"); generic.add_options() ("help", "produce help message"); po::options_description config("Configuration"); config.add_options() ("home", po::value<fs::path>(&ozHome), "path to the home of the installation") ("init", po::value<fs::path>(&initFunctorPath), "path to the Init.ozf functor") ("search-path", po::value<std::string>(&ozSearchPath), "search path") ("search-load", po::value<std::string>(&ozSearchLoad), "search load") ("gui", "GUI mode"); po::options_description hidden("Hidden options"); hidden.add_options() ("base", po::value<fs::path>(&baseFunctorPath), "path to the Base.ozf functor") ("app-url", po::value<std::string>(&appURL), "application URL") ("app-args", po::value<std::vector<std::string>>(&appArgs), "application arguments"); po::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); po::options_description environment_options; environment_options.add(config); po::options_description visible_options("Allowed options"); visible_options.add(generic).add(config); po::positional_options_description positional_options; positional_options.add("app-url", 1); positional_options.add("app-args", -1); // PARSE OPTIONS po::variables_map varMap; po::store(po::command_line_parser(argc, argv) .options(cmdline_options) .positional(positional_options) .run(), varMap); po::store(po::parse_environment(environment_options, &envVarToOptionName), varMap); po::store(po::parse_environment(environment_options, &envVarToOptionNameFallback), varMap); po::notify(varMap); // READ OPTIONS if (varMap.count("help") != 0) { std::cout << visible_options << "\n"; return 0; } // Hacky way to guess if we are in a build setting fs::path appPath = fs::path(argv[0]).parent_path(); bool isBuildSetting = appPath.filename() == "emulator"; if (ozHome.empty()) { if (isBuildSetting) ozHome = appPath.parent_path().parent_path(); else ozHome = appPath.parent_path(); if (ozHome.empty()) ozHome = "."; } if (initFunctorPath.empty()) { if (isBuildSetting) initFunctorPath = ozHome / "lib" / "cache" / "Init.ozf"; else initFunctorPath = ozHome / "share" / "mozart" / "cache" / "Init.ozf"; } bool useBaseFunctor = varMap.count("base") != 0; appGUI = varMap.count("gui") != 0; // SET UP THE VM AND RUN boostenv::BoostBasedVM boostBasedVM; VM vm = boostBasedVM.vm; // Set some properties { auto& properties = vm->getPropertyRegistry(); atom_t ozHomeAtom = pathToAtom(vm, ozHome); properties.registerValueProp( vm, MOZART_STR("oz.home"), ozHomeAtom); properties.registerValueProp( vm, MOZART_STR("oz.emulator.home"), ozHomeAtom); properties.registerValueProp( vm, MOZART_STR("oz.configure.home"), ozHomeAtom); if (varMap.count("search-path") != 0) properties.registerValueProp( vm, MOZART_STR("oz.search.path"), strToAtom(vm, ozSearchPath)); if (varMap.count("search-load") != 0) properties.registerValueProp( vm, MOZART_STR("oz.search.load"), strToAtom(vm, ozSearchLoad)); auto decodedURL = toUTF<nchar>(makeLString(appURL.c_str())); auto appURLAtom = vm->getAtom(decodedURL.length, decodedURL.string); properties.registerValueProp( vm, MOZART_STR("application.url"), appURLAtom); OzListBuilder argsBuilder(vm); for (auto& arg: appArgs) { auto decodedArg = toUTF<nchar>(makeLString(arg.c_str())); argsBuilder.push_back(vm, vm->getAtom(decodedArg.length, decodedArg.string)); } properties.registerValueProp( vm, MOZART_STR("application.args"), argsBuilder.get(vm)); properties.registerValueProp( vm, MOZART_STR("application.gui"), appGUI); } // Some protected nodes ProtectedNode baseEnv, initFunctor; // Load the Base environment if required if (useBaseFunctor) { baseEnv = vm->protect(OptVar::build(vm)); UnstableNode baseValue; auto& bootLoader = boostBasedVM.getBootLoader(); if (!bootLoader(vm, baseFunctorPath.native(), baseValue)) { std::cerr << "panic: could not load Base functor at " << baseFunctorPath << std::endl; return 1; } // Create the thread that loads the Base environment if (Callable(baseValue).isProcedure(vm)) { ozcalls::asyncOzCall(vm, baseValue, *baseEnv); } else { // Assume it is a functor that does not import anything UnstableNode applyAtom = build(vm, MOZART_STR("apply")); UnstableNode applyProc = Dottable(baseValue).dot(vm, applyAtom); UnstableNode importParam = build(vm, MOZART_STR("import")); ozcalls::asyncOzCall(vm, applyProc, importParam, *baseEnv); } boostBasedVM.run(); } // Load the Init functor { initFunctor = vm->protect(OptVar::build(vm)); UnstableNode initValue; auto& bootLoader = boostBasedVM.getBootLoader(); if (!bootLoader(vm, initFunctorPath.native(), initValue)) { std::cerr << "panic: could not load Init functor at " << initFunctorPath << std::endl; return 1; } // Create the thread that loads the Init functor if (Callable(initValue).isProcedure(vm)) { if (!useBaseFunctor) { std::cerr << "panic: Init.ozf is a procedure, " << "but I have no Base to give to it" << std::endl; return 1; } ozcalls::asyncOzCall(vm, initValue, *baseEnv, *initFunctor); boostBasedVM.run(); } else { // Assume it is already the Init functor DataflowVariable(*initFunctor).bind(vm, initValue); } } // Apply the Init functor { auto ApplyAtom = build(vm, MOZART_STR("apply")); auto ApplyProc = Dottable(*initFunctor).dot(vm, ApplyAtom); auto BootModule = vm->findBuiltinModule(MOZART_STR("Boot")); auto ImportRecord = buildRecord( vm, buildArity(vm, MOZART_STR("import"), MOZART_STR("Boot")), BootModule); ozcalls::asyncOzCall(vm, ApplyProc, ImportRecord, OptVar::build(vm)); baseEnv.reset(); initFunctor.reset(); boostBasedVM.run(); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: line.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:21:05 $ * * 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 * ************************************************************************/ #define _LINE_CXX #ifndef _LINK_HXX #include <link.hxx> #endif #ifndef _LINE_HXX #include <line.hxx> #endif #ifndef _DEBUG_HXX #include <debug.hxx> #endif #include <cstdlib> #include <cmath> inline long FRound( double fVal ) { return( fVal > 0.0 ? (long) ( fVal + 0.5 ) : -(long) ( -fVal + 0.5 ) ); } // -------- // - Line - // -------- double Line::GetLength() const { return hypot( maStart.X() - maEnd.X(), maStart.Y() - maEnd.Y() ); } // ------------------------------------------------------------------------ BOOL Line::Intersection( const Line& rLine, Point& rIntersection ) const { double fX, fY; BOOL bRet; if( Intersection( rLine, fX, fY ) ) { rIntersection.X() = FRound( fX ); rIntersection.Y() = FRound( fY ); bRet = TRUE; } else bRet = FALSE; return bRet; } // ------------------------------------------------------------------------ BOOL Line::Intersection( const Line& rLine, double& rIntersectionX, double& rIntersectionY ) const { const double fAx = maEnd.X() - maStart.X(); const double fAy = maEnd.Y() - maStart.Y(); const double fBx = rLine.maStart.X() - rLine.maEnd.X(); const double fBy = rLine.maStart.Y() - rLine.maEnd.Y(); const double fDen = fAy * fBx - fAx * fBy; BOOL bOk = FALSE; if( fDen != 0. ) { const double fCx = maStart.X() - rLine.maStart.X(); const double fCy = maStart.Y() - rLine.maStart.Y(); const double fA = fBy * fCx - fBx * fCy; const BOOL bGreater = ( fDen > 0. ); bOk = TRUE; if ( bGreater ) { if ( ( fA < 0. ) || ( fA > fDen ) ) bOk = FALSE; } else if ( ( fA > 0. ) || ( fA < fDen ) ) bOk = FALSE; if ( bOk ) { const double fB = fAx * fCy - fAy * fCx; if ( bGreater ) { if ( ( fB < 0. ) || ( fB > fDen ) ) bOk = FALSE; } else if ( ( fB > 0. ) || ( fB < fDen ) ) bOk = FALSE; if( bOk ) { const double fAlpha = fA / fDen; rIntersectionX = ( maStart.X() + fAlpha * fAx ); rIntersectionY = ( maStart.Y() + fAlpha * fAy ); } } } return bOk; } // ------------------------------------------------------------------------ BOOL Line::Intersection( const Rectangle& rRect, Line& rIntersection ) const { const BOOL bStartInside = rRect.IsInside( maStart ); const BOOL bEndInside = rRect.IsInside( maEnd ); BOOL bRet = TRUE; if( bStartInside && bEndInside ) { // line completely inside rect rIntersection.maStart = maStart; rIntersection.maEnd = maEnd; } else { // calculate intersections const Point aTL( rRect.TopLeft() ), aTR( rRect.TopRight() ); const Point aBR( rRect.BottomRight() ), aBL( rRect.BottomLeft() ); Point aIntersect1, aIntersect2; Point* pCurIntersection = &aIntersect1; if( Intersection( Line( aTL, aTR ), *pCurIntersection ) ) pCurIntersection = &aIntersect2; if( Intersection( Line( aTR, aBR ), *pCurIntersection ) ) pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL; if( pCurIntersection && Intersection( Line( aBR, aBL ), *pCurIntersection ) ) pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL; if( pCurIntersection && Intersection( Line( aBL, aTL ), *pCurIntersection ) ) pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL; if( !pCurIntersection ) { // two intersections rIntersection.maStart = aIntersect1; rIntersection.maEnd = aIntersect2; } else if( pCurIntersection == &aIntersect2 ) { // one intersection rIntersection.maStart = aIntersect1; if( ( maStart != aIntersect1 ) && bStartInside ) rIntersection.maEnd = maStart; else if( ( maEnd != aIntersect1 ) && bEndInside ) rIntersection.maEnd = maEnd; else rIntersection.maEnd = rIntersection.maStart; } else bRet = FALSE; } return bRet; } // ------------------------------------------------------------------------ Point Line::NearestPoint( const Point& rPoint ) const { Point aRetPt; if ( maStart != maEnd ) { const double fDistX = maEnd.X() - maStart.X(); const double fDistY = maStart.Y() - maEnd.Y(); const double fTau = ( ( maStart.Y() - rPoint.Y() ) * fDistY - ( maStart.X() - rPoint.X() ) * fDistX ) / ( fDistX * fDistX + fDistY * fDistY ); if( fTau < 0.0 ) aRetPt = maStart; else if( fTau <= 1.0 ) { aRetPt.X() = FRound( maStart.X() + fTau * fDistX ); aRetPt.Y() = FRound( maStart.Y() - fTau * fDistY ); } else aRetPt = maEnd; } else aRetPt = maStart; return aRetPt; } // ------------------------------------------------------------------------ double Line::GetDistance( const double& rPtX, const double& rPtY ) const { double fDist; if( maStart != maEnd ) { const double fDistX = maEnd.X() - maStart.X(); const double fDistY = maEnd.Y() - maStart.Y(); const double fACX = maStart.X() - rPtX; const double fACY = maStart.Y() - rPtY; const double fL2 = fDistX * fDistX + fDistY * fDistY; const double fR = ( fACY * -fDistY - fACX * fDistX ) / fL2; const double fS = ( fACY * fDistX - fACX * fDistY ) / fL2; if( fR < 0.0 ) { fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY ); if( fS < 0.0 ) fDist *= -1.0; } else if( fR <= 1.0 ) fDist = fS * sqrt( fL2 ); else { fDist = hypot( maEnd.X() - rPtX, maEnd.Y() - rPtY ); if( fS < 0.0 ) fDist *= -1.0; } } else fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY ); return fDist; } // ------------------------------------------------------------------------ void Line::Enum( const Link& rEnumLink ) { DBG_ASSERT( rEnumLink.IsSet(), "This call doesn't make any sense with !rEnumLink.IsSet()" ); Point aEnum; long nX; long nY; if( maStart.X() == maEnd.X() ) { const long nEndY = maEnd.Y(); nX = maStart.X(); nY = maStart.Y(); if( nEndY > nY ) { while( nY <= nEndY ) { aEnum.X() = nX; aEnum.Y() = nY++; rEnumLink.Call( &aEnum ); } } else { while( nY >= nEndY ) { aEnum.X() = nX; aEnum.Y() = nY--; rEnumLink.Call( &aEnum ); } } } else if( maStart.Y() == maEnd.Y() ) { const long nEndX = maEnd.X(); nX = maStart.X(); nY = maStart.Y(); if( nEndX > nX ) { while( nX <= nEndX ) { aEnum.X() = nX++; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); } } else { while( nX >= nEndX ) { aEnum.X() = nX--; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); } } } else { const long nDX = labs( maEnd.X() - maStart.X() ); const long nDY = labs( maEnd.Y() - maStart.Y() ); const long nStartX = maStart.X(); const long nStartY = maStart.Y(); const long nEndX = maEnd.X(); const long nEndY = maEnd.Y(); const long nXInc = ( nStartX < nEndX ) ? 1L : -1L; const long nYInc = ( nStartY < nEndY ) ? 1L : -1L; if( nDX >= nDY ) { const long nDYX = ( nDY - nDX ) << 1; const long nDY2 = nDY << 1; long nD = nDY2 - nDX; for( nX = nStartX, nY = nStartY; nX != nEndX; nX += nXInc ) { aEnum.X() = nX; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); if( nD < 0L ) nD += nDY2; else nD += nDYX, nY += nYInc; } } else { const long nDYX = ( nDX - nDY ) << 1; const long nDY2 = nDX << 1; long nD = nDY2 - nDY; for( nX = nStartX, nY = nStartY; nY != nEndY; nY += nYInc ) { aEnum.X() = nX; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); if( nD < 0L ) nD += nDY2; else nD += nDYX, nX += nXInc; } } // last point aEnum.X() = nEndX; aEnum.Y() = nEndY; rEnumLink.Call( &aEnum ); } } <commit_msg>INTEGRATION: CWS pchfix02 (1.3.120); FILE MERGED 2006/09/01 17:54:52 kaib 1.3.120.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: line.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 00:56:12 $ * * 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_tools.hxx" #define _LINE_CXX #ifndef _LINK_HXX #include <link.hxx> #endif #ifndef _LINE_HXX #include <line.hxx> #endif #ifndef _DEBUG_HXX #include <debug.hxx> #endif #include <cstdlib> #include <cmath> inline long FRound( double fVal ) { return( fVal > 0.0 ? (long) ( fVal + 0.5 ) : -(long) ( -fVal + 0.5 ) ); } // -------- // - Line - // -------- double Line::GetLength() const { return hypot( maStart.X() - maEnd.X(), maStart.Y() - maEnd.Y() ); } // ------------------------------------------------------------------------ BOOL Line::Intersection( const Line& rLine, Point& rIntersection ) const { double fX, fY; BOOL bRet; if( Intersection( rLine, fX, fY ) ) { rIntersection.X() = FRound( fX ); rIntersection.Y() = FRound( fY ); bRet = TRUE; } else bRet = FALSE; return bRet; } // ------------------------------------------------------------------------ BOOL Line::Intersection( const Line& rLine, double& rIntersectionX, double& rIntersectionY ) const { const double fAx = maEnd.X() - maStart.X(); const double fAy = maEnd.Y() - maStart.Y(); const double fBx = rLine.maStart.X() - rLine.maEnd.X(); const double fBy = rLine.maStart.Y() - rLine.maEnd.Y(); const double fDen = fAy * fBx - fAx * fBy; BOOL bOk = FALSE; if( fDen != 0. ) { const double fCx = maStart.X() - rLine.maStart.X(); const double fCy = maStart.Y() - rLine.maStart.Y(); const double fA = fBy * fCx - fBx * fCy; const BOOL bGreater = ( fDen > 0. ); bOk = TRUE; if ( bGreater ) { if ( ( fA < 0. ) || ( fA > fDen ) ) bOk = FALSE; } else if ( ( fA > 0. ) || ( fA < fDen ) ) bOk = FALSE; if ( bOk ) { const double fB = fAx * fCy - fAy * fCx; if ( bGreater ) { if ( ( fB < 0. ) || ( fB > fDen ) ) bOk = FALSE; } else if ( ( fB > 0. ) || ( fB < fDen ) ) bOk = FALSE; if( bOk ) { const double fAlpha = fA / fDen; rIntersectionX = ( maStart.X() + fAlpha * fAx ); rIntersectionY = ( maStart.Y() + fAlpha * fAy ); } } } return bOk; } // ------------------------------------------------------------------------ BOOL Line::Intersection( const Rectangle& rRect, Line& rIntersection ) const { const BOOL bStartInside = rRect.IsInside( maStart ); const BOOL bEndInside = rRect.IsInside( maEnd ); BOOL bRet = TRUE; if( bStartInside && bEndInside ) { // line completely inside rect rIntersection.maStart = maStart; rIntersection.maEnd = maEnd; } else { // calculate intersections const Point aTL( rRect.TopLeft() ), aTR( rRect.TopRight() ); const Point aBR( rRect.BottomRight() ), aBL( rRect.BottomLeft() ); Point aIntersect1, aIntersect2; Point* pCurIntersection = &aIntersect1; if( Intersection( Line( aTL, aTR ), *pCurIntersection ) ) pCurIntersection = &aIntersect2; if( Intersection( Line( aTR, aBR ), *pCurIntersection ) ) pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL; if( pCurIntersection && Intersection( Line( aBR, aBL ), *pCurIntersection ) ) pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL; if( pCurIntersection && Intersection( Line( aBL, aTL ), *pCurIntersection ) ) pCurIntersection = ( pCurIntersection == &aIntersect1 ) ? &aIntersect2 : NULL; if( !pCurIntersection ) { // two intersections rIntersection.maStart = aIntersect1; rIntersection.maEnd = aIntersect2; } else if( pCurIntersection == &aIntersect2 ) { // one intersection rIntersection.maStart = aIntersect1; if( ( maStart != aIntersect1 ) && bStartInside ) rIntersection.maEnd = maStart; else if( ( maEnd != aIntersect1 ) && bEndInside ) rIntersection.maEnd = maEnd; else rIntersection.maEnd = rIntersection.maStart; } else bRet = FALSE; } return bRet; } // ------------------------------------------------------------------------ Point Line::NearestPoint( const Point& rPoint ) const { Point aRetPt; if ( maStart != maEnd ) { const double fDistX = maEnd.X() - maStart.X(); const double fDistY = maStart.Y() - maEnd.Y(); const double fTau = ( ( maStart.Y() - rPoint.Y() ) * fDistY - ( maStart.X() - rPoint.X() ) * fDistX ) / ( fDistX * fDistX + fDistY * fDistY ); if( fTau < 0.0 ) aRetPt = maStart; else if( fTau <= 1.0 ) { aRetPt.X() = FRound( maStart.X() + fTau * fDistX ); aRetPt.Y() = FRound( maStart.Y() - fTau * fDistY ); } else aRetPt = maEnd; } else aRetPt = maStart; return aRetPt; } // ------------------------------------------------------------------------ double Line::GetDistance( const double& rPtX, const double& rPtY ) const { double fDist; if( maStart != maEnd ) { const double fDistX = maEnd.X() - maStart.X(); const double fDistY = maEnd.Y() - maStart.Y(); const double fACX = maStart.X() - rPtX; const double fACY = maStart.Y() - rPtY; const double fL2 = fDistX * fDistX + fDistY * fDistY; const double fR = ( fACY * -fDistY - fACX * fDistX ) / fL2; const double fS = ( fACY * fDistX - fACX * fDistY ) / fL2; if( fR < 0.0 ) { fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY ); if( fS < 0.0 ) fDist *= -1.0; } else if( fR <= 1.0 ) fDist = fS * sqrt( fL2 ); else { fDist = hypot( maEnd.X() - rPtX, maEnd.Y() - rPtY ); if( fS < 0.0 ) fDist *= -1.0; } } else fDist = hypot( maStart.X() - rPtX, maStart.Y() - rPtY ); return fDist; } // ------------------------------------------------------------------------ void Line::Enum( const Link& rEnumLink ) { DBG_ASSERT( rEnumLink.IsSet(), "This call doesn't make any sense with !rEnumLink.IsSet()" ); Point aEnum; long nX; long nY; if( maStart.X() == maEnd.X() ) { const long nEndY = maEnd.Y(); nX = maStart.X(); nY = maStart.Y(); if( nEndY > nY ) { while( nY <= nEndY ) { aEnum.X() = nX; aEnum.Y() = nY++; rEnumLink.Call( &aEnum ); } } else { while( nY >= nEndY ) { aEnum.X() = nX; aEnum.Y() = nY--; rEnumLink.Call( &aEnum ); } } } else if( maStart.Y() == maEnd.Y() ) { const long nEndX = maEnd.X(); nX = maStart.X(); nY = maStart.Y(); if( nEndX > nX ) { while( nX <= nEndX ) { aEnum.X() = nX++; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); } } else { while( nX >= nEndX ) { aEnum.X() = nX--; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); } } } else { const long nDX = labs( maEnd.X() - maStart.X() ); const long nDY = labs( maEnd.Y() - maStart.Y() ); const long nStartX = maStart.X(); const long nStartY = maStart.Y(); const long nEndX = maEnd.X(); const long nEndY = maEnd.Y(); const long nXInc = ( nStartX < nEndX ) ? 1L : -1L; const long nYInc = ( nStartY < nEndY ) ? 1L : -1L; if( nDX >= nDY ) { const long nDYX = ( nDY - nDX ) << 1; const long nDY2 = nDY << 1; long nD = nDY2 - nDX; for( nX = nStartX, nY = nStartY; nX != nEndX; nX += nXInc ) { aEnum.X() = nX; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); if( nD < 0L ) nD += nDY2; else nD += nDYX, nY += nYInc; } } else { const long nDYX = ( nDX - nDY ) << 1; const long nDY2 = nDX << 1; long nD = nDY2 - nDY; for( nX = nStartX, nY = nStartY; nY != nEndY; nY += nYInc ) { aEnum.X() = nX; aEnum.Y() = nY; rEnumLink.Call( &aEnum ); if( nD < 0L ) nD += nDY2; else nD += nDYX, nX += nXInc; } } // last point aEnum.X() = nEndX; aEnum.Y() = nEndY; rEnumLink.Call( &aEnum ); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Regents of the University of California. 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. * * 3. The names of its contributors may not 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. * * *********************************************************************************************** * * CARLsim * created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran * maintained by: * (MA) Mike Avery <averym@uci.edu> * (MB) Michael Beyeler <mbeyeler@uci.edu>, * (KDC) Kristofor Carlson <kdcarlso@uci.edu> * (TSC) Ting-Shuo Chou <tingshuc@uci.edu> * (HK) Hirak J Kashyap <kashyaph@uci.edu> * * CARLsim v1.0: JM, MDR * CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC * CARLsim3: MB, KDC, TSC * CARLsim4: TSC, HK * * CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/ * Ver 12/31/2016 */ #include "stopwatch.h" #include <stdio.h> #include <algorithm> // std::find #include <assert.h> // assert #include <carlsim_log_definitions.h> // CARLSIM_ERROR, CARLSIM_WARN, CARLSIM_INFO // ****************************************************************************************************************** // // STOPWATCH UTILITY PRIVATE IMPLEMENTATION // ****************************************************************************************************************** // /*! * \brief Private implementation of the Stopwatch Utility * * This class provides a timer with milliseconds resolution. * \see http://stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c/1861337#1861337 * \since v3.1 */ class Stopwatch::Impl { public: // +++++ PUBLIC METHODS: CONSTRUCTOR / DESTRUCTOR +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Impl(bool startTimer) { reset(); if (startTimer) { start("start"); } } ~Impl() { // nothing to see here } // resets the timer void reset() { if (_isTimerOn) { CARLSIM_WARN("Stopwatch::reset", "Cannot reset timer when timer is on."); return; } _isTimerOn = false; _startTimeMs.clear(); _stopTimeMs.clear(); _lapTimeMs.clear(); _accumTimeMs = 0; _tags.clear(); } // starts/continues the timer void start(const std::string& tag) { if (_isTimerOn) { CARLSIM_WARN("Stopwatch::start", "Cannot start timer when timer is already on."); return; } // start/continue timer _isTimerOn = true; _tags.push_back(tag); _startTimeMs.push_back( getCurrentTime() ); } // stops the timer uint64_t stop(bool printMessage=true, FILE* fileStream=NULL) { if (!_isTimerOn) { CARLSIM_WARN("Stopwatch::stop", "Cannot stop timer when timer is already off."); return _accumTimeMs; } // pause/stop timer and update exe time _isTimerOn = false; _stopTimeMs.push_back( getCurrentTime() ); uint64_t lapMs = _stopTimeMs.back() - _startTimeMs.back(); _lapTimeMs.push_back(lapMs); // keep track of accumulated record time // check for arithmetic overflow assert(_accumTimeMs + lapMs >= _accumTimeMs); _accumTimeMs += lapMs; if (printMessage) { print(fileStream); } return _accumTimeMs; } // prints a summary to a file void print(FILE* fileStream=NULL) const { if (_isTimerOn) { CARLSIM_WARN("Stopwatch::print", "Cannot print when timer is on."); return; } if (fileStream == NULL) { fileStream = stdout; // default } fprintf(fileStream, "\n--------------------------------------------------------------------------------\n"); fprintf(fileStream, "| Stopwatch |\n"); fprintf(fileStream, "|------------------------------------------------------------------------------|\n"); fprintf(fileStream, "| Tag Start Stop Lap Total |\n"); uint64_t totalMsSoFar = 0; for (unsigned int i=0; i<_lapTimeMs.size(); i++) { totalMsSoFar += _lapTimeMs[i]; uint64_t startMs = _startTimeMs[i] - _startTimeMs[0]; uint64_t stopMs = _stopTimeMs[i] - _startTimeMs[0]; uint64_t lapMs = _lapTimeMs[i]; fprintf(fileStream, "| %20.20s %02lu:%02lu:%02lu.%03lu %02lu:%02lu:%02lu.%03lu " " %02lu:%02lu:%02lu.%03lu %02lu:%02lu:%02lu.%03lu |\n", _tags[i].c_str(), startMs/3600000, (startMs/1000/60)%60, (startMs/1000)%60, startMs%1000, stopMs/3600000, (stopMs/1000/60)%60, (stopMs/1000)%60, stopMs%1000, lapMs/3600000, (lapMs/1000/60)%60, (lapMs/1000)%60, lapMs%1000, totalMsSoFar/3600000, (totalMsSoFar/1000/60)%60, (totalMsSoFar/1000)%60, totalMsSoFar%1000); } fprintf(fileStream, "--------------------------------------------------------------------------------\n"); } // lap is equivalent to stop-start // returns current lap time uint64_t lap(const std::string& tag) { if (!_isTimerOn) { CARLSIM_WARN("Stopwatch::lap", "Cannot use lap when timer is off."); return 0; } stop(false); start(tag); return _lapTimeMs.back(); } // returns lap time, look-up by tag uint64_t getLapTime(const std::string& tag) const { unsigned int pos = std::find(_tags.begin(), _tags.end(), tag) - _tags.begin(); if (pos >=0 && pos < _tags.size()) { if (pos >= _lapTimeMs.size()) { CARLSIM_WARN("Stopwatch::getLapTime(tag)", "Cannot look up current lap time until timer stopped."); return 0; } printf("pos = %u, time = %lu\n",pos,_lapTimeMs[pos]); return _lapTimeMs[pos]; } else { CARLSIM_WARN("Stopwatch::getLapTime(tag)", "Invalid tag specified."); return 0; } } // returns lap time, look-up by index uint64_t getLapTime(unsigned int index) const { if (index < _lapTimeMs.size()) { return _lapTimeMs[index]; } else { CARLSIM_WARN("Stopwatch::getLapTime(index)", "Invalid index specified."); return 0; } } private: // +++++ PRIVATE METHODS ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // uint64_t getCurrentTime() const { #if defined(WIN32) || defined(WIN64) // Windows FILETIME ft; LARGE_INTEGER li; // Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it // to a LARGE_INTEGER structure. GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; uint64_t ret = li.QuadPart; ret -= 116444736000000000LL; // Convert from file time to UNIX epoch time. ret /= 10000; // From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals return ret; #else // Unix struct timeval tv; gettimeofday(&tv, NULL); uint64_t ret = tv.tv_usec; // Convert from micro seconds (10^-6) to milliseconds (10^-3) ret /= 1000; // Adds the seconds (10^0) after converting them to milliseconds (10^-3) ret += (tv.tv_sec * 1000); return ret; #endif } // +++++ PRIVATE STATIC PROPERTIES ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // +++++ PRIVATE PROPERTIES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // std::vector<uint64_t> _startTimeMs; // vector of start times (Unix/Windows timestamps) std::vector<uint64_t> _stopTimeMs; // vector of end times (Unix/Windows timestamps) std::vector<uint64_t> _lapTimeMs; // vector lap times (stop-start for every lap) uint64_t _accumTimeMs; // acumulated record time (sum of all laps) std::vector<std::string> _tags; // string tag for every lap bool _isTimerOn; // flag to indicate whether stopwatch is running (true) or not (false) }; // ****************************************************************************************************************** // // STOPWATCH API IMPLEMENTATION // ****************************************************************************************************************** // // create and destroy a pImpl instance Stopwatch::Stopwatch(bool startTimer) : _impl( new Impl(startTimer) ) {} Stopwatch::~Stopwatch() { delete _impl; } void Stopwatch::start(const std::string& tag) { _impl->start(tag); } uint64_t Stopwatch::stop(bool printMessage, FILE* printFile) { return _impl->stop(printMessage, printFile); } uint64_t Stopwatch::lap(const std::string& tag) { return _impl->lap(tag); } void Stopwatch::reset() { _impl->reset(); } uint64_t Stopwatch::getLapTime(const std::string& tag) const { return _impl->getLapTime(tag); } uint64_t Stopwatch::getLapTime(int index) const { return _impl->getLapTime(index); } void Stopwatch::print(FILE* fileStream) const { _impl->print(fileStream); }<commit_msg>Quick fix initialization bug in stopwatch.cpp<commit_after>/* * Copyright (c) 2016 Regents of the University of California. 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. * * 3. The names of its contributors may not 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. * * *********************************************************************************************** * * CARLsim * created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran * maintained by: * (MA) Mike Avery <averym@uci.edu> * (MB) Michael Beyeler <mbeyeler@uci.edu>, * (KDC) Kristofor Carlson <kdcarlso@uci.edu> * (TSC) Ting-Shuo Chou <tingshuc@uci.edu> * (HK) Hirak J Kashyap <kashyaph@uci.edu> * * CARLsim v1.0: JM, MDR * CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC * CARLsim3: MB, KDC, TSC * CARLsim4: TSC, HK * * CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/ * Ver 12/31/2016 */ #include "stopwatch.h" #include <stdio.h> #include <algorithm> // std::find #include <assert.h> // assert #include <carlsim_log_definitions.h> // CARLSIM_ERROR, CARLSIM_WARN, CARLSIM_INFO // ****************************************************************************************************************** // // STOPWATCH UTILITY PRIVATE IMPLEMENTATION // ****************************************************************************************************************** // /*! * \brief Private implementation of the Stopwatch Utility * * This class provides a timer with milliseconds resolution. * \see http://stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c/1861337#1861337 * \since v3.1 */ class Stopwatch::Impl { public: // +++++ PUBLIC METHODS: CONSTRUCTOR / DESTRUCTOR +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Impl(bool startTimer) { _isTimerOn = false; reset(); if (startTimer) { start("start"); } } ~Impl() { // nothing to see here } // resets the timer void reset() { if (_isTimerOn) { CARLSIM_WARN("Stopwatch::reset", "Cannot reset timer when timer is on."); return; } _isTimerOn = false; _startTimeMs.clear(); _stopTimeMs.clear(); _lapTimeMs.clear(); _accumTimeMs = 0; _tags.clear(); } // starts/continues the timer void start(const std::string& tag) { if (_isTimerOn) { CARLSIM_WARN("Stopwatch::start", "Cannot start timer when timer is already on."); return; } // start/continue timer _isTimerOn = true; _tags.push_back(tag); _startTimeMs.push_back( getCurrentTime() ); } // stops the timer uint64_t stop(bool printMessage=true, FILE* fileStream=NULL) { if (!_isTimerOn) { CARLSIM_WARN("Stopwatch::stop", "Cannot stop timer when timer is already off."); return _accumTimeMs; } // pause/stop timer and update exe time _isTimerOn = false; _stopTimeMs.push_back( getCurrentTime() ); uint64_t lapMs = _stopTimeMs.back() - _startTimeMs.back(); _lapTimeMs.push_back(lapMs); // keep track of accumulated record time // check for arithmetic overflow assert(_accumTimeMs + lapMs >= _accumTimeMs); _accumTimeMs += lapMs; if (printMessage) { print(fileStream); } return _accumTimeMs; } // prints a summary to a file void print(FILE* fileStream=NULL) const { if (_isTimerOn) { CARLSIM_WARN("Stopwatch::print", "Cannot print when timer is on."); return; } if (fileStream == NULL) { fileStream = stdout; // default } fprintf(fileStream, "\n--------------------------------------------------------------------------------\n"); fprintf(fileStream, "| Stopwatch |\n"); fprintf(fileStream, "|------------------------------------------------------------------------------|\n"); fprintf(fileStream, "| Tag Start Stop Lap Total |\n"); uint64_t totalMsSoFar = 0; for (unsigned int i=0; i<_lapTimeMs.size(); i++) { totalMsSoFar += _lapTimeMs[i]; uint64_t startMs = _startTimeMs[i] - _startTimeMs[0]; uint64_t stopMs = _stopTimeMs[i] - _startTimeMs[0]; uint64_t lapMs = _lapTimeMs[i]; fprintf(fileStream, "| %20.20s %02lu:%02lu:%02lu.%03lu %02lu:%02lu:%02lu.%03lu " " %02lu:%02lu:%02lu.%03lu %02lu:%02lu:%02lu.%03lu |\n", _tags[i].c_str(), startMs/3600000, (startMs/1000/60)%60, (startMs/1000)%60, startMs%1000, stopMs/3600000, (stopMs/1000/60)%60, (stopMs/1000)%60, stopMs%1000, lapMs/3600000, (lapMs/1000/60)%60, (lapMs/1000)%60, lapMs%1000, totalMsSoFar/3600000, (totalMsSoFar/1000/60)%60, (totalMsSoFar/1000)%60, totalMsSoFar%1000); } fprintf(fileStream, "--------------------------------------------------------------------------------\n"); } // lap is equivalent to stop-start // returns current lap time uint64_t lap(const std::string& tag) { if (!_isTimerOn) { CARLSIM_WARN("Stopwatch::lap", "Cannot use lap when timer is off."); return 0; } stop(false); start(tag); return _lapTimeMs.back(); } // returns lap time, look-up by tag uint64_t getLapTime(const std::string& tag) const { unsigned int pos = std::find(_tags.begin(), _tags.end(), tag) - _tags.begin(); if (pos >=0 && pos < _tags.size()) { if (pos >= _lapTimeMs.size()) { CARLSIM_WARN("Stopwatch::getLapTime(tag)", "Cannot look up current lap time until timer stopped."); return 0; } printf("pos = %u, time = %lu\n",pos,_lapTimeMs[pos]); return _lapTimeMs[pos]; } else { CARLSIM_WARN("Stopwatch::getLapTime(tag)", "Invalid tag specified."); return 0; } } // returns lap time, look-up by index uint64_t getLapTime(unsigned int index) const { if (index < _lapTimeMs.size()) { return _lapTimeMs[index]; } else { CARLSIM_WARN("Stopwatch::getLapTime(index)", "Invalid index specified."); return 0; } } private: // +++++ PRIVATE METHODS ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // uint64_t getCurrentTime() const { #if defined(WIN32) || defined(WIN64) // Windows FILETIME ft; LARGE_INTEGER li; // Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it // to a LARGE_INTEGER structure. GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; uint64_t ret = li.QuadPart; ret -= 116444736000000000LL; // Convert from file time to UNIX epoch time. ret /= 10000; // From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals return ret; #else // Unix struct timeval tv; gettimeofday(&tv, NULL); uint64_t ret = tv.tv_usec; // Convert from micro seconds (10^-6) to milliseconds (10^-3) ret /= 1000; // Adds the seconds (10^0) after converting them to milliseconds (10^-3) ret += (tv.tv_sec * 1000); return ret; #endif } // +++++ PRIVATE STATIC PROPERTIES ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // +++++ PRIVATE PROPERTIES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // std::vector<uint64_t> _startTimeMs; // vector of start times (Unix/Windows timestamps) std::vector<uint64_t> _stopTimeMs; // vector of end times (Unix/Windows timestamps) std::vector<uint64_t> _lapTimeMs; // vector lap times (stop-start for every lap) uint64_t _accumTimeMs; // acumulated record time (sum of all laps) std::vector<std::string> _tags; // string tag for every lap bool _isTimerOn; // flag to indicate whether stopwatch is running (true) or not (false) }; // ****************************************************************************************************************** // // STOPWATCH API IMPLEMENTATION // ****************************************************************************************************************** // // create and destroy a pImpl instance Stopwatch::Stopwatch(bool startTimer) : _impl( new Impl(startTimer) ) {} Stopwatch::~Stopwatch() { delete _impl; } void Stopwatch::start(const std::string& tag) { _impl->start(tag); } uint64_t Stopwatch::stop(bool printMessage, FILE* printFile) { return _impl->stop(printMessage, printFile); } uint64_t Stopwatch::lap(const std::string& tag) { return _impl->lap(tag); } void Stopwatch::reset() { _impl->reset(); } uint64_t Stopwatch::getLapTime(const std::string& tag) const { return _impl->getLapTime(tag); } uint64_t Stopwatch::getLapTime(int index) const { return _impl->getLapTime(index); } void Stopwatch::print(FILE* fileStream) const { _impl->print(fileStream); }<|endoftext|>
<commit_before>/* * Copyright (C) 2014 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 "builder.h" #include "dex_instruction.h" #include "nodes.h" #include "optimizing_unit_test.h" #include "utils/arena_allocator.h" #include "gtest/gtest.h" namespace art { static void TestCode(const uint16_t* data, const int* blocks, size_t blocks_length) { ArenaPool pool; ArenaAllocator allocator(&pool); HGraphBuilder builder(&allocator); const DexFile::CodeItem* item = reinterpret_cast<const DexFile::CodeItem*>(data); HGraph* graph = builder.BuildGraph(*item); ASSERT_NE(graph, nullptr); graph->BuildDominatorTree(); ASSERT_EQ(graph->blocks()->Size(), blocks_length); for (size_t i = 0; i < blocks_length; i++) { if (blocks[i] == -1) { ASSERT_EQ(nullptr, graph->blocks()->Get(i)->dominator()); } else { ASSERT_NE(nullptr, graph->blocks()->Get(i)->dominator()); ASSERT_EQ(blocks[i], graph->blocks()->Get(i)->dominator()->block_id()); } } } TEST(OptimizerTest, ReturnVoid) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::RETURN_VOID); // Block number 1 const int dominators[] = { -1, 0, 1 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG1) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO | 0x100, // Block number 1 Instruction::RETURN_VOID); // Block number 2 const int dominators[] = { -1, 0, 1, 2 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG2) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO | 0x100, // Block number 1 Instruction::GOTO | 0x100, // Block number 2 Instruction::RETURN_VOID); // Block number 3 const int dominators[] = { -1, 0, 1, 2, 3 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG3) { const uint16_t data1[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO | 0x200, // Block number 1 Instruction::RETURN_VOID, // Block number 2 Instruction::GOTO | 0xFF00); // Block number 3 const int dominators[] = { -1, 0, 3, 1, 2 }; TestCode(data1, dominators, sizeof(dominators) / sizeof(int)); const uint16_t data2[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO_16, 3, Instruction::RETURN_VOID, Instruction::GOTO_16, 0xFFFF); TestCode(data2, dominators, sizeof(dominators) / sizeof(int)); const uint16_t data3[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO_32, 4, 0, Instruction::RETURN_VOID, Instruction::GOTO_32, 0xFFFF, 0xFFFF); TestCode(data3, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG4) { const uint16_t data1[] = ZERO_REGISTER_CODE_ITEM( Instruction::NOP, Instruction::GOTO | 0xFF00); const int dominators[] = { -1, 0, -1 }; TestCode(data1, dominators, sizeof(dominators) / sizeof(int)); const uint16_t data2[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO_32, 0, 0); TestCode(data2, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG5) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::RETURN_VOID, // Block number 1 Instruction::GOTO | 0x100, // Dead block Instruction::GOTO | 0xFE00); // Block number 2 const int dominators[] = { -1, 0, -1, 1 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG6) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, Instruction::GOTO | 0x100, Instruction::RETURN_VOID); const int dominators[] = { -1, 0, 1, 1, 3 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG7) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, // Block number 1 Instruction::GOTO | 0x100, // Block number 2 Instruction::GOTO | 0xFF00); // Block number 3 const int dominators[] = { -1, 0, 1, 1, -1 // exit block is not dominated by any block due to the spin loop. }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG8) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, // Block number 1 Instruction::GOTO | 0x200, // Block number 2 Instruction::GOTO | 0x100, // Block number 3 Instruction::GOTO | 0xFF00); // Block number 4 const int dominators[] = { -1, 0, 1, 1, 1, -1 // exit block is not dominated by any block due to the spin loop. }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG9) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, // Block number 1 Instruction::GOTO | 0x200, // Block number 2 Instruction::GOTO | 0x100, // Block number 3 Instruction::GOTO | 0xFE00); // Block number 4 const int dominators[] = { -1, 0, 1, 1, 1, -1 // exit block is not dominated by any block due to the spin loop. }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG10) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 6, // Block number 1 Instruction::IF_EQ, 3, // Block number 2 Instruction::GOTO | 0x100, // Block number 3 Instruction::GOTO | 0x100, // Block number 4 Instruction::RETURN_VOID); // Block number 5 const int dominators[] = { -1, 0, 1, 2, 2, 1, 5 // Block number 5 dominates exit block }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } } // namespace art <commit_msg>Fix lint errors.<commit_after>/* * Copyright (C) 2014 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 "builder.h" #include "dex_instruction.h" #include "nodes.h" #include "optimizing_unit_test.h" #include "utils/arena_allocator.h" #include "gtest/gtest.h" namespace art { static void TestCode(const uint16_t* data, const int* blocks, size_t blocks_length) { ArenaPool pool; ArenaAllocator allocator(&pool); HGraphBuilder builder(&allocator); const DexFile::CodeItem* item = reinterpret_cast<const DexFile::CodeItem*>(data); HGraph* graph = builder.BuildGraph(*item); ASSERT_NE(graph, nullptr); graph->BuildDominatorTree(); ASSERT_EQ(graph->blocks()->Size(), blocks_length); for (size_t i = 0; i < blocks_length; i++) { if (blocks[i] == -1) { ASSERT_EQ(nullptr, graph->blocks()->Get(i)->dominator()); } else { ASSERT_NE(nullptr, graph->blocks()->Get(i)->dominator()); ASSERT_EQ(blocks[i], graph->blocks()->Get(i)->dominator()->block_id()); } } } TEST(OptimizerTest, ReturnVoid) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::RETURN_VOID); // Block number 1 const int dominators[] = { -1, 0, 1 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG1) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO | 0x100, // Block number 1 Instruction::RETURN_VOID); // Block number 2 const int dominators[] = { -1, 0, 1, 2 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG2) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO | 0x100, // Block number 1 Instruction::GOTO | 0x100, // Block number 2 Instruction::RETURN_VOID); // Block number 3 const int dominators[] = { -1, 0, 1, 2, 3 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG3) { const uint16_t data1[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO | 0x200, // Block number 1 Instruction::RETURN_VOID, // Block number 2 Instruction::GOTO | 0xFF00); // Block number 3 const int dominators[] = { -1, 0, 3, 1, 2 }; TestCode(data1, dominators, sizeof(dominators) / sizeof(int)); const uint16_t data2[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO_16, 3, Instruction::RETURN_VOID, Instruction::GOTO_16, 0xFFFF); TestCode(data2, dominators, sizeof(dominators) / sizeof(int)); const uint16_t data3[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO_32, 4, 0, Instruction::RETURN_VOID, Instruction::GOTO_32, 0xFFFF, 0xFFFF); TestCode(data3, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG4) { const uint16_t data1[] = ZERO_REGISTER_CODE_ITEM( Instruction::NOP, Instruction::GOTO | 0xFF00); const int dominators[] = { -1, 0, -1 }; TestCode(data1, dominators, sizeof(dominators) / sizeof(int)); const uint16_t data2[] = ZERO_REGISTER_CODE_ITEM( Instruction::GOTO_32, 0, 0); TestCode(data2, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG5) { const uint16_t data[] = ZERO_REGISTER_CODE_ITEM( Instruction::RETURN_VOID, // Block number 1 Instruction::GOTO | 0x100, // Dead block Instruction::GOTO | 0xFE00); // Block number 2 const int dominators[] = { -1, 0, -1, 1 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG6) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, Instruction::GOTO | 0x100, Instruction::RETURN_VOID); const int dominators[] = { -1, 0, 1, 1, 3 }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG7) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, // Block number 1 Instruction::GOTO | 0x100, // Block number 2 Instruction::GOTO | 0xFF00); // Block number 3 const int dominators[] = { -1, 0, 1, 1, -1 // exit block is not dominated by any block due to the spin loop. }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG8) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, // Block number 1 Instruction::GOTO | 0x200, // Block number 2 Instruction::GOTO | 0x100, // Block number 3 Instruction::GOTO | 0xFF00); // Block number 4 const int dominators[] = { -1, 0, 1, 1, 1, -1 // exit block is not dominated by any block due to the spin loop. }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG9) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 3, // Block number 1 Instruction::GOTO | 0x200, // Block number 2 Instruction::GOTO | 0x100, // Block number 3 Instruction::GOTO | 0xFE00); // Block number 4 const int dominators[] = { -1, 0, 1, 1, 1, -1 // exit block is not dominated by any block due to the spin loop. }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } TEST(OptimizerTest, CFG10) { const uint16_t data[] = ONE_REGISTER_CODE_ITEM( Instruction::CONST_4 | 0 | 0, Instruction::IF_EQ, 6, // Block number 1 Instruction::IF_EQ, 3, // Block number 2 Instruction::GOTO | 0x100, // Block number 3 Instruction::GOTO | 0x100, // Block number 4 Instruction::RETURN_VOID); // Block number 5 const int dominators[] = { -1, 0, 1, 2, 2, 1, 5 // Block number 5 dominates exit block }; TestCode(data, dominators, sizeof(dominators) / sizeof(int)); } } // namespace art <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: localstratumbase.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-01-07 10:10:14 $ * * 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 CONFIGMGR_LOCALBE_LOCALSTRATUMBASE_HXX_ #define CONFIGMGR_LOCALBE_LOCALSTRATUMBASE_HXX_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDENTITIES_HPP_ #include <com/sun/star/configuration/backend/XBackendEntities.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XUPDATABLELAYER_HPP_ #include <com/sun/star/configuration/backend/XUpdatableLayer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_ #include <com/sun/star/configuration/InvalidBootstrapFileException.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CANNOTCONNECTEXCEPTION_HPP_ #include <com/sun/star/configuration/backend/CannotConnectException.hpp> #endif #ifndef _CPPUHELPER_COMPBASE3_HXX_ #include <cppuhelper/compbase3.hxx> #endif namespace configmgr { struct ServiceImplementationInfo; namespace localbe { //------------------------------------------------------------------------------ namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace backend = css::configuration::backend ; //------------------------------------------------------------------------------ typedef cppu::WeakComponentImplHelper3<lang::XInitialization, backend::XBackendEntities, lang::XServiceInfo> LocalStratumImplBase ; struct LocalStratumMutexHolder { osl::Mutex mMutex; }; //------------------------------------------------------------------------------ static const char kLocalDataSuffix[] = ".xcu"; //------------------------------------------------------------------------------ /** Helper for implementing the [Single|Multi]LayerStratum service for local file access. */ class LocalStratumBase : protected LocalStratumMutexHolder, public LocalStratumImplBase { protected : /** Service constructor from a service factory. @param xContext component context */ LocalStratumBase(const uno::Reference<uno::XComponentContext>& xContext) ; /** Destructor */ ~LocalStratumBase() ; public: // XInitialize virtual void SAL_CALL initialize( const uno::Sequence<uno::Any>& aParameters) throw (uno::RuntimeException, uno::Exception, css::configuration::InvalidBootstrapFileException, backend::CannotConnectException, backend::BackendSetupException); // XBackendEntities virtual rtl::OUString SAL_CALL getOwnerEntity( ) throw (uno::RuntimeException); virtual rtl::OUString SAL_CALL getAdminEntity( ) throw (uno::RuntimeException); virtual sal_Bool SAL_CALL supportsEntity( const rtl::OUString& aEntity ) throw (backend::BackendAccessException, uno::RuntimeException); virtual sal_Bool SAL_CALL isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity ) throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName( ) throw (uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& aServiceName ) throw (uno::RuntimeException) ; virtual uno::Sequence<rtl::OUString> SAL_CALL getSupportedServiceNames( ) throw (uno::RuntimeException) ; protected: rtl::OUString const & getBaseUrl() const { return mStrataDataUrl; } static rtl::OUString getDataSuffix() { return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(kLocalDataSuffix)); } //------------------------------------------------------------------------------ /// raise a NoSupportException for an attempt to update this layer void failReadonly(); // helper for implementing the stratum getLayer[s] function[s] uno::Reference<backend::XLayer> SAL_CALL getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp ) throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException); /** Builds a LocalFileLayer object given a subpath Since the LocalFileLayer implements the various interfaces a layer can be accessed as, a few methods need one. @param aSubpath Subpath @return local file layer @throws com::sun::star::lang::IllegalArgumentException if the subpath is invalid. */ uno::Reference<backend::XLayer> createReadonlyFileLayer(const rtl::OUString& aSubpath) throw (lang::IllegalArgumentException) ; /** Builds a LocalFileLayer object given a subpath. Since the LocalFileLayer implements the various interfaces a layer can be accessed as, a few methods need one. @param aSubpath subpath @return local file layer @throws com::sun::star::lang::IllegalArgumentException if the subpath is invalid. */ uno::Reference<backend::XUpdatableLayer> createUpdatableFileLayer(const rtl::OUString& aSubpath) throw (lang::IllegalArgumentException) ; /** Tells if a file is more recent than a given date. The date is formatted YYYYMMDDhhmmssZ. @param aSubpath relative URL of the component to check @param aTimestamp timestamp to check against @return sal_True if the file is more recent, sal_False otherwise */ sal_Bool isMoreRecent(const rtl::OUString& aSubpath, const rtl::OUString& aTimestamp) ; protected: /// Parses and adjusts the passed base URL virtual void adjustBaseURL(rtl::OUString& aBaseURL); private: /** Retrieves the appropriate layer and sublayers base directories. @param aLayerUrl layer base URL, filled on return @param aSubLayerUrl sublayer base URL, filled on return */ virtual void getLayerDirectories(rtl::OUString& aLayerUrl, rtl::OUString& aSubLayerUrl) const = 0; virtual const ServiceImplementationInfo * getServiceInfoData() const = 0; private : /** Service factory */ uno::Reference<lang::XMultiServiceFactory> mFactory ; /** Base of the strata data. */ rtl::OUString mStrataDataUrl ; } ; } } // configmgr.localbe #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.46); FILE MERGED 2005/09/05 17:04:52 rt 1.2.46.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: localstratumbase.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:07:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_LOCALBE_LOCALSTRATUMBASE_HXX_ #define CONFIGMGR_LOCALBE_LOCALSTRATUMBASE_HXX_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDENTITIES_HPP_ #include <com/sun/star/configuration/backend/XBackendEntities.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XUPDATABLELAYER_HPP_ #include <com/sun/star/configuration/backend/XUpdatableLayer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_ #include <com/sun/star/configuration/InvalidBootstrapFileException.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CANNOTCONNECTEXCEPTION_HPP_ #include <com/sun/star/configuration/backend/CannotConnectException.hpp> #endif #ifndef _CPPUHELPER_COMPBASE3_HXX_ #include <cppuhelper/compbase3.hxx> #endif namespace configmgr { struct ServiceImplementationInfo; namespace localbe { //------------------------------------------------------------------------------ namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace backend = css::configuration::backend ; //------------------------------------------------------------------------------ typedef cppu::WeakComponentImplHelper3<lang::XInitialization, backend::XBackendEntities, lang::XServiceInfo> LocalStratumImplBase ; struct LocalStratumMutexHolder { osl::Mutex mMutex; }; //------------------------------------------------------------------------------ static const char kLocalDataSuffix[] = ".xcu"; //------------------------------------------------------------------------------ /** Helper for implementing the [Single|Multi]LayerStratum service for local file access. */ class LocalStratumBase : protected LocalStratumMutexHolder, public LocalStratumImplBase { protected : /** Service constructor from a service factory. @param xContext component context */ LocalStratumBase(const uno::Reference<uno::XComponentContext>& xContext) ; /** Destructor */ ~LocalStratumBase() ; public: // XInitialize virtual void SAL_CALL initialize( const uno::Sequence<uno::Any>& aParameters) throw (uno::RuntimeException, uno::Exception, css::configuration::InvalidBootstrapFileException, backend::CannotConnectException, backend::BackendSetupException); // XBackendEntities virtual rtl::OUString SAL_CALL getOwnerEntity( ) throw (uno::RuntimeException); virtual rtl::OUString SAL_CALL getAdminEntity( ) throw (uno::RuntimeException); virtual sal_Bool SAL_CALL supportsEntity( const rtl::OUString& aEntity ) throw (backend::BackendAccessException, uno::RuntimeException); virtual sal_Bool SAL_CALL isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity ) throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName( ) throw (uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& aServiceName ) throw (uno::RuntimeException) ; virtual uno::Sequence<rtl::OUString> SAL_CALL getSupportedServiceNames( ) throw (uno::RuntimeException) ; protected: rtl::OUString const & getBaseUrl() const { return mStrataDataUrl; } static rtl::OUString getDataSuffix() { return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(kLocalDataSuffix)); } //------------------------------------------------------------------------------ /// raise a NoSupportException for an attempt to update this layer void failReadonly(); // helper for implementing the stratum getLayer[s] function[s] uno::Reference<backend::XLayer> SAL_CALL getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp ) throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException); /** Builds a LocalFileLayer object given a subpath Since the LocalFileLayer implements the various interfaces a layer can be accessed as, a few methods need one. @param aSubpath Subpath @return local file layer @throws com::sun::star::lang::IllegalArgumentException if the subpath is invalid. */ uno::Reference<backend::XLayer> createReadonlyFileLayer(const rtl::OUString& aSubpath) throw (lang::IllegalArgumentException) ; /** Builds a LocalFileLayer object given a subpath. Since the LocalFileLayer implements the various interfaces a layer can be accessed as, a few methods need one. @param aSubpath subpath @return local file layer @throws com::sun::star::lang::IllegalArgumentException if the subpath is invalid. */ uno::Reference<backend::XUpdatableLayer> createUpdatableFileLayer(const rtl::OUString& aSubpath) throw (lang::IllegalArgumentException) ; /** Tells if a file is more recent than a given date. The date is formatted YYYYMMDDhhmmssZ. @param aSubpath relative URL of the component to check @param aTimestamp timestamp to check against @return sal_True if the file is more recent, sal_False otherwise */ sal_Bool isMoreRecent(const rtl::OUString& aSubpath, const rtl::OUString& aTimestamp) ; protected: /// Parses and adjusts the passed base URL virtual void adjustBaseURL(rtl::OUString& aBaseURL); private: /** Retrieves the appropriate layer and sublayers base directories. @param aLayerUrl layer base URL, filled on return @param aSubLayerUrl sublayer base URL, filled on return */ virtual void getLayerDirectories(rtl::OUString& aLayerUrl, rtl::OUString& aSubLayerUrl) const = 0; virtual const ServiceImplementationInfo * getServiceInfoData() const = 0; private : /** Service factory */ uno::Reference<lang::XMultiServiceFactory> mFactory ; /** Base of the strata data. */ rtl::OUString mStrataDataUrl ; } ; } } // configmgr.localbe #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: invalidatetree.cxx,v $ * * $Revision: 1.20 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:25:09 $ * * 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 "cachecontroller.hxx" #ifndef CONFIGMGR_CHANGE_HXX #include "change.hxx" #endif #ifndef _CONFIGMGR_TREE_VALUENODE_HXX #include "valuenode.hxx" #endif #ifndef CONFIGMGR_UPDATEHELPER_HXX #include "updatehelper.hxx" #endif #ifndef _CONFIGMGR_TREEACTIONS_HXX_ #include "treeactions.hxx" #endif #ifndef CONFIGMGR_TREEACCESSOR_HXX #include "treeaccessor.hxx" #endif #ifndef CONFIGMGR_UPDATEACCESSOR_HXX #include "updateaccessor.hxx" #endif #ifndef _CONFIGMGR_TRACER_HXX_ #include "tracer.hxx" #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_ #include <com/sun/star/container/NoSuchElementException.hpp> #endif #ifndef _VOS_THREAD_HXX_ #include <vos/thread.hxx> #endif #ifndef INCLUDED_ALGORITHM #include <algorithm> #define INCLUDED_ALGORITHM #endif namespace configmgr { using namespace com::sun::star::uno; using namespace configuration; namespace container = com::sun::star::container; // ----------------------------------------------------------------------------- // ------------------------------- invalidateTree ------------------------------- // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- std::auto_ptr<SubtreeChange> createDiffs(data::NodeAccessRef const& _aCachedNode, ISubtree const * _pLoadedSubtree, AbsolutePath const& _aAbsoluteSubtreePath) { OSL_PRECOND(_aCachedNode.isValid(), "Need an existing node to create a diff"); OSL_PRECOND(_pLoadedSubtree != 0, "Need a result node to create a diff"); // Create a TreeChangeList with the right name, parentname and ConfigurationProperties std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(), node::Attributes()) ); if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree)) aNewChange.reset(); return aNewChange; } // ----------------------------------------------------------------------------- #if 0 std::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath, const vos::ORef < OOptions >& _xOptions, sal_Int16 _nMinLevels) CFG_UNO_THROW_ALL() { TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true /*create TreeInfo*/); CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node"); rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get()); OSL_ENSURE(xLoader.is(), "Did not receive a loader for retrieving the node"); CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node"); if (!xLoader.is()) throw container::NoSuchElementException((::rtl::OUString::createFromAscii("Error while retrieving the node")), NULL); // now block for reading std::auto_ptr<ISubtree> pResponse; try { pResponse = xLoader->waitToResponse(); } catch (uno::Exception& e) { pInfo->releaseLoader(xLoader); throw; } pInfo->releaseLoader(xLoader); return pResponse; } #endif // ----------------------------------------------------------------------------- class OInvalidateTreeThread: public vos::OThread { typedef backend::ICachedDataProvider CacheManager; typedef rtl::Reference< CacheManager > CacheManagerRef; CacheManagerRef m_rTreeManager; Name m_aComponentName; RequestOptions m_aOptions; public: OInvalidateTreeThread(CacheManager* _rTreeManager, Name const & _aComponentName, const RequestOptions& _aOptions) : m_rTreeManager(_rTreeManager) , m_aComponentName(_aComponentName) , m_aOptions(_aOptions) {} ~OInvalidateTreeThread() {} private: virtual void SAL_CALL onTerminated() { delete this; } virtual void SAL_CALL run(); }; // ----------------------------------------------------------------------------- void CacheController::invalidateComponent(ComponentRequest const & _aComponent) CFG_UNO_THROW_ALL( ) { if (!this->m_bDisposing) { // start the InvalidateTreeThread only, if we are not at disposemode if (OInvalidateTreeThread *pThread = new OInvalidateTreeThread(this, _aComponent.getComponentName(), _aComponent.getOptions())) { pThread->create(); } else OSL_ENSURE(false, "Could not create refresher thread"); } } // ----------------------------------------------------------------------------- CacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL() { if (m_bDisposing) return CacheLocation(); CacheRef aCache = this->getCacheAlways(_aRequest.getOptions()); if (!aCache.is()) return CacheLocation(); osl::MutexGuard aCacheLineGuard(aCache->mutex()); // load the Node direct from the session, without using the cache ComponentRequest aForcedRequest(_aRequest); aForcedRequest.forceReload(); ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false); AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate()); NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ; NodeResult aLoadedNodeInstance(aNodeInstance) ; CacheLocation aResult; if (aLoadedNodeInstance.is()) { Name aModuleName = aLoadedNodeInstance->root().getModuleName(); memory::UpdateAccessor aChangingAccessor( aCache->getDataSegment(aModuleName) ); OSL_ENSURE(aChangingAccessor.is(), "No existing cache line for tree being refreshed"); data::TreeAddress aCachedTreeAddress = aCache->acquireModule(aModuleName); aResult.segment = aCache->getDataSegmentAddress(aModuleName); aResult.address = aCachedTreeAddress.addressValue(); if (aCachedTreeAddress.is()) try { std::auto_ptr<SubtreeChange> aTreeChanges; data::NodeAddress aRootAddress; { data::TreeAccessor aTreeAccess(aChangingAccessor.accessor(),aCachedTreeAddress); data::NodeAccessRef aRootNode = aTreeAccess.getRootNode(); aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location()); aRootAddress = aRootNode.address(); } if (aTreeChanges.get() != NULL) { // change all Values... found in the Subtree in the CacheTree applyUpdateWithAdjustmentToTree(*aTreeChanges, aChangingAccessor, aRootAddress); data::Accessor aNotifyLock = aChangingAccessor.downgrade(); // keep a read lock during notification UpdateRequest anUpdateReq( aTreeChanges.get(), aLoadedNodeInstance->root().location(), _aRequest.getOptions() ); m_aNotifier.notifyChanged(anUpdateReq); } aCache->releaseModule(aModuleName); } catch (...) { aCache->releaseModule(aModuleName); throw; } } return aResult; } // ----------------------------------------------------------------------------- void OInvalidateTreeThread::run() { try { ComponentRequest aRequest(m_aComponentName, m_aOptions); m_rTreeManager->refreshComponent(aRequest); } catch(uno::Exception&) { // do nothing, only thread safe exception absorb CFG_TRACE_ERROR_NI("OInvalidateTreeThread::run: refreshing failed - ignoring the exception"); } } // ----------------------------------------------------------------------------- } // namespace backend // ----------------------------------------------------------------------------- } // namespace configmgr <commit_msg>INTEGRATION: CWS pchfix02 (1.20.60); FILE MERGED 2006/09/01 17:20:46 kaib 1.20.60.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: invalidatetree.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: obo $ $Date: 2006-09-16 15:26:33 $ * * 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_configmgr.hxx" #include "cachecontroller.hxx" #ifndef CONFIGMGR_CHANGE_HXX #include "change.hxx" #endif #ifndef _CONFIGMGR_TREE_VALUENODE_HXX #include "valuenode.hxx" #endif #ifndef CONFIGMGR_UPDATEHELPER_HXX #include "updatehelper.hxx" #endif #ifndef _CONFIGMGR_TREEACTIONS_HXX_ #include "treeactions.hxx" #endif #ifndef CONFIGMGR_TREEACCESSOR_HXX #include "treeaccessor.hxx" #endif #ifndef CONFIGMGR_UPDATEACCESSOR_HXX #include "updateaccessor.hxx" #endif #ifndef _CONFIGMGR_TRACER_HXX_ #include "tracer.hxx" #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_ #include <com/sun/star/container/NoSuchElementException.hpp> #endif #ifndef _VOS_THREAD_HXX_ #include <vos/thread.hxx> #endif #ifndef INCLUDED_ALGORITHM #include <algorithm> #define INCLUDED_ALGORITHM #endif namespace configmgr { using namespace com::sun::star::uno; using namespace configuration; namespace container = com::sun::star::container; // ----------------------------------------------------------------------------- // ------------------------------- invalidateTree ------------------------------- // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- std::auto_ptr<SubtreeChange> createDiffs(data::NodeAccessRef const& _aCachedNode, ISubtree const * _pLoadedSubtree, AbsolutePath const& _aAbsoluteSubtreePath) { OSL_PRECOND(_aCachedNode.isValid(), "Need an existing node to create a diff"); OSL_PRECOND(_pLoadedSubtree != 0, "Need a result node to create a diff"); // Create a TreeChangeList with the right name, parentname and ConfigurationProperties std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(), node::Attributes()) ); if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree)) aNewChange.reset(); return aNewChange; } // ----------------------------------------------------------------------------- #if 0 std::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath, const vos::ORef < OOptions >& _xOptions, sal_Int16 _nMinLevels) CFG_UNO_THROW_ALL() { TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true /*create TreeInfo*/); CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node"); rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get()); OSL_ENSURE(xLoader.is(), "Did not receive a loader for retrieving the node"); CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node"); if (!xLoader.is()) throw container::NoSuchElementException((::rtl::OUString::createFromAscii("Error while retrieving the node")), NULL); // now block for reading std::auto_ptr<ISubtree> pResponse; try { pResponse = xLoader->waitToResponse(); } catch (uno::Exception& e) { pInfo->releaseLoader(xLoader); throw; } pInfo->releaseLoader(xLoader); return pResponse; } #endif // ----------------------------------------------------------------------------- class OInvalidateTreeThread: public vos::OThread { typedef backend::ICachedDataProvider CacheManager; typedef rtl::Reference< CacheManager > CacheManagerRef; CacheManagerRef m_rTreeManager; Name m_aComponentName; RequestOptions m_aOptions; public: OInvalidateTreeThread(CacheManager* _rTreeManager, Name const & _aComponentName, const RequestOptions& _aOptions) : m_rTreeManager(_rTreeManager) , m_aComponentName(_aComponentName) , m_aOptions(_aOptions) {} ~OInvalidateTreeThread() {} private: virtual void SAL_CALL onTerminated() { delete this; } virtual void SAL_CALL run(); }; // ----------------------------------------------------------------------------- void CacheController::invalidateComponent(ComponentRequest const & _aComponent) CFG_UNO_THROW_ALL( ) { if (!this->m_bDisposing) { // start the InvalidateTreeThread only, if we are not at disposemode if (OInvalidateTreeThread *pThread = new OInvalidateTreeThread(this, _aComponent.getComponentName(), _aComponent.getOptions())) { pThread->create(); } else OSL_ENSURE(false, "Could not create refresher thread"); } } // ----------------------------------------------------------------------------- CacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL() { if (m_bDisposing) return CacheLocation(); CacheRef aCache = this->getCacheAlways(_aRequest.getOptions()); if (!aCache.is()) return CacheLocation(); osl::MutexGuard aCacheLineGuard(aCache->mutex()); // load the Node direct from the session, without using the cache ComponentRequest aForcedRequest(_aRequest); aForcedRequest.forceReload(); ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false); AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate()); NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ; NodeResult aLoadedNodeInstance(aNodeInstance) ; CacheLocation aResult; if (aLoadedNodeInstance.is()) { Name aModuleName = aLoadedNodeInstance->root().getModuleName(); memory::UpdateAccessor aChangingAccessor( aCache->getDataSegment(aModuleName) ); OSL_ENSURE(aChangingAccessor.is(), "No existing cache line for tree being refreshed"); data::TreeAddress aCachedTreeAddress = aCache->acquireModule(aModuleName); aResult.segment = aCache->getDataSegmentAddress(aModuleName); aResult.address = aCachedTreeAddress.addressValue(); if (aCachedTreeAddress.is()) try { std::auto_ptr<SubtreeChange> aTreeChanges; data::NodeAddress aRootAddress; { data::TreeAccessor aTreeAccess(aChangingAccessor.accessor(),aCachedTreeAddress); data::NodeAccessRef aRootNode = aTreeAccess.getRootNode(); aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location()); aRootAddress = aRootNode.address(); } if (aTreeChanges.get() != NULL) { // change all Values... found in the Subtree in the CacheTree applyUpdateWithAdjustmentToTree(*aTreeChanges, aChangingAccessor, aRootAddress); data::Accessor aNotifyLock = aChangingAccessor.downgrade(); // keep a read lock during notification UpdateRequest anUpdateReq( aTreeChanges.get(), aLoadedNodeInstance->root().location(), _aRequest.getOptions() ); m_aNotifier.notifyChanged(anUpdateReq); } aCache->releaseModule(aModuleName); } catch (...) { aCache->releaseModule(aModuleName); throw; } } return aResult; } // ----------------------------------------------------------------------------- void OInvalidateTreeThread::run() { try { ComponentRequest aRequest(m_aComponentName, m_aOptions); m_rTreeManager->refreshComponent(aRequest); } catch(uno::Exception&) { // do nothing, only thread safe exception absorb CFG_TRACE_ERROR_NI("OInvalidateTreeThread::run: refreshing failed - ignoring the exception"); } } // ----------------------------------------------------------------------------- } // namespace backend // ----------------------------------------------------------------------------- } // namespace configmgr <|endoftext|>
<commit_before>#include <stdexcept> #include <functional> #include <list> #include "containers/iterators.hpp" #include "unittest/gtest.hpp" namespace unittest { struct test_iterator : one_way_iterator_t<int> { typedef std::list<std::list<int> > data_blocks_t; explicit test_iterator(data_blocks_t& _data_blocks) : prefetches_count(0), blocked_without_prefetch(0), data_blocks(_data_blocks) { // remove empty blocks data_blocks.remove_if(std::mem_fun_ref(&data_blocks_t::value_type::empty)); // add first empty block (so that we could check prefetch of the first block data_blocks.push_front(std::list<int>()); } boost::optional<int> next() { if (data_blocks.empty()) return boost::none; if (data_blocks.front().empty()) { blocked_without_prefetch++; data_blocks.pop_front(); } if (data_blocks.empty()) return boost::none; int result = data_blocks.front().front(); data_blocks.front().pop_front(); return boost::optional<int>(result); } void prefetch() { prefetches_count++; if (!data_blocks.empty() && data_blocks.front().empty()) { data_blocks.pop_front(); } } size_t prefetches_count; size_t blocked_without_prefetch; private: data_blocks_t data_blocks; }; struct delete_check_iterator : test_iterator { delete_check_iterator(data_blocks_t& data_blocks, bool *_deleted) : test_iterator(data_blocks), deleted(_deleted) { *deleted = false; } virtual ~delete_check_iterator() { *deleted = true; } private: bool *deleted; }; // Helper functions std::list<int> parse_list_of_ints(const std::string &_l) { std::string l = _l; l += " "; std::list<int> result; std::string w; for (int i = 0, e = l.size(); i < e; ++i) { if (l[i] != ' ') { w.push_back(l[i]); } else if (!w.empty()) { int v = atoi(w.c_str()); rassert(v != 0); result.push_back(v); w.clear(); } } rassert(w.empty(), "we put a space at the end of l for a reason!"); return result; } // parse the string "1 2 3 | 42 56 | 13" into a list of lists of integers, using '|' as a list separator test_iterator::data_blocks_t parse_data_blocks(const std::string &_db) { std::string db = _db; db += " "; test_iterator::data_blocks_t result; std::string w; std::list<int> current_list; // oh god for (int i = 0, e = db.size(); i < e; ++i) { if (db[i] != ' ') { w.push_back(db[i]); } else if (!w.empty()) { if (w == "|") { result.push_back(current_list); current_list.clear(); } else { int v = atoi(w.c_str()); rassert(v != 0); current_list.push_back(v); } w.clear(); } } rassert(w.empty(), "we put a space at the end of db for a reason!"); if (!current_list.empty()) { result.push_back(current_list); } return result; } std::list<int> data_blocks_to_list_of_ints(test_iterator::data_blocks_t& db) { std::list<int> result; for (test_iterator::data_blocks_t::iterator it = db.begin(); it != db.end(); ++it) { for (std::list<int>::iterator i = (*it).begin(); i != (*it).end(); ++i) { result.push_back(*i); } //std::copy((*it).begin(), (*it).end(), result.end()); } return result; } // Tests TEST(MergeIteratorsTest, merge_empty) { test_iterator::data_blocks_t empty_blocks; test_iterator *a = new test_iterator(empty_blocks); test_iterator *b = new test_iterator(empty_blocks); test_iterator *c = new test_iterator(empty_blocks); merge_ordered_data_iterator_t<int> merged; merged.add_mergee(a); merged.add_mergee(b); merged.add_mergee(c); ASSERT_FALSE(merged.next()); } TEST(MergeIteratorsTest, parse_data_blocks) { test_iterator::data_blocks_t db = parse_data_blocks("1 2 3 | 42 56 | 93"); ASSERT_EQ(db.size(), 3); ASSERT_EQ(db.front().size(), 3); ASSERT_EQ(db.back().size(), 1); } TEST(MergeIteratorsTest, three_way_merge) { test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10"); test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16"); test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16"); test_iterator *a = new test_iterator(a_db); test_iterator *b = new test_iterator(b_db); test_iterator *c = new test_iterator(c_db); merge_ordered_data_iterator_t<int> merge_iterator; merge_iterator.add_mergee(a); merge_iterator.add_mergee(b); merge_iterator.add_mergee(c); std::list<int> merged; boost::optional<int> next; while ((next = merge_iterator.next())) { merged.push_back(next.get()); } std::list<int> a_db_flat = data_blocks_to_list_of_ints(a_db); std::list<int> b_db_flat = data_blocks_to_list_of_ints(b_db); std::list<int> c_db_flat = data_blocks_to_list_of_ints(c_db); std::list<int> merged_expected; merged_expected.merge(a_db_flat); merged_expected.merge(b_db_flat); merged_expected.merge(c_db_flat); ASSERT_TRUE(std::equal(merged_expected.begin(), merged_expected.end(), merged.begin())); } TEST(MergeIteratorsTest, iterators_get_deleted) { test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10"); test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16"); test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16"); test_iterator::data_blocks_t d_db = parse_data_blocks(""); bool a_deleted = false, b_deleted = false, c_deleted = false, d_deleted = false; test_iterator *a = new delete_check_iterator(a_db, &a_deleted); test_iterator *b = new delete_check_iterator(b_db, &b_deleted); test_iterator *c = new delete_check_iterator(c_db, &c_deleted); test_iterator *d = new delete_check_iterator(d_db, &d_deleted); merge_ordered_data_iterator_t<int> merge_iterator; merge_iterator.add_mergee(a); merge_iterator.add_mergee(b); merge_iterator.add_mergee(c); merge_iterator.add_mergee(d); (void) merge_iterator.next(); EXPECT_TRUE(d_deleted); boost::optional<int> next; bool expect_a_deleted = false; while ((next = merge_iterator.next())) { if (expect_a_deleted) { EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted"; } if (next.get() == 10) { expect_a_deleted = true; // when the next element is fetched, merge iterator will recognize that // 'a' iterator has exhausted, so it can delete it } } EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should have deleted the 'a' iterator long ago"; EXPECT_TRUE(b_deleted && c_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted"; a_deleted = false; b_deleted = false; { test_iterator *a = new delete_check_iterator(a_db, &a_deleted); test_iterator *b = new delete_check_iterator(b_db, &b_deleted); merge_ordered_data_iterator_t<int> merge_iterator; merge_iterator.add_mergee(a); merge_iterator.add_mergee(b); // get some data from the merge iterator, but don't exhaust the iterators (void) merge_iterator.next(); (void) merge_iterator.next(); (void) merge_iterator.next(); } EXPECT_TRUE(a_deleted && b_deleted) << "merge_ordered_data_iterator_t should delete the iterators on destruction, even when they have not been exhausted"; } } // namespace unittest <commit_msg>Reintroduce checks for non-blocking in merge iterator test.<commit_after>#include <stdexcept> #include <functional> #include <list> #include "containers/iterators.hpp" #include "unittest/gtest.hpp" namespace unittest { struct test_iterator : one_way_iterator_t<int> { typedef std::list<std::list<int> > data_blocks_t; test_iterator(data_blocks_t& _data_blocks, size_t& _blocked_without_prefetch) : prefetches_count(0), blocked_without_prefetch(_blocked_without_prefetch), data_blocks(_data_blocks) { blocked_without_prefetch = 0; // remove empty blocks data_blocks.remove_if(std::mem_fun_ref(&data_blocks_t::value_type::empty)); // add first empty block (so that we could check prefetch of the first block data_blocks.push_front(std::list<int>()); } boost::optional<int> next() { if (data_blocks.empty()) return boost::none; if (data_blocks.front().empty()) { blocked_without_prefetch++; data_blocks.pop_front(); } if (data_blocks.empty()) return boost::none; int result = data_blocks.front().front(); data_blocks.front().pop_front(); return boost::optional<int>(result); } void prefetch() { prefetches_count++; if (!data_blocks.empty() && data_blocks.front().empty()) { data_blocks.pop_front(); } } size_t prefetches_count; size_t& blocked_without_prefetch; private: data_blocks_t data_blocks; }; struct delete_check_iterator : test_iterator { delete_check_iterator(data_blocks_t& data_blocks, size_t& blocked_without_prefetch, bool *_deleted) : test_iterator(data_blocks, blocked_without_prefetch), deleted(_deleted) { *deleted = false; } virtual ~delete_check_iterator() { *deleted = true; } private: bool *deleted; }; // Helper functions std::list<int> parse_list_of_ints(const std::string &_l) { std::string l = _l; l += " "; std::list<int> result; std::string w; for (int i = 0, e = l.size(); i < e; ++i) { if (l[i] != ' ') { w.push_back(l[i]); } else if (!w.empty()) { int v = atoi(w.c_str()); rassert(v != 0); result.push_back(v); w.clear(); } } rassert(w.empty(), "we put a space at the end of l for a reason!"); return result; } // parse the string "1 2 3 | 42 56 | 13" into a list of lists of integers, using '|' as a list separator test_iterator::data_blocks_t parse_data_blocks(const std::string &_db) { std::string db = _db; db += " "; test_iterator::data_blocks_t result; std::string w; std::list<int> current_list; // oh god for (int i = 0, e = db.size(); i < e; ++i) { if (db[i] != ' ') { w.push_back(db[i]); } else if (!w.empty()) { if (w == "|") { result.push_back(current_list); current_list.clear(); } else { int v = atoi(w.c_str()); rassert(v != 0); current_list.push_back(v); } w.clear(); } } rassert(w.empty(), "we put a space at the end of db for a reason!"); if (!current_list.empty()) { result.push_back(current_list); } return result; } std::list<int> data_blocks_to_list_of_ints(test_iterator::data_blocks_t& db) { std::list<int> result; for (test_iterator::data_blocks_t::iterator it = db.begin(); it != db.end(); ++it) { for (std::list<int>::iterator i = (*it).begin(); i != (*it).end(); ++i) { result.push_back(*i); } //std::copy((*it).begin(), (*it).end(), result.end()); } return result; } // Tests TEST(MergeIteratorsTest, merge_empty) { test_iterator::data_blocks_t empty_blocks; size_t blocked_without_prefetch_a, blocked_without_prefetch_b, blocked_without_prefetch_c; test_iterator *a = new test_iterator(empty_blocks, blocked_without_prefetch_a); test_iterator *b = new test_iterator(empty_blocks, blocked_without_prefetch_b); test_iterator *c = new test_iterator(empty_blocks, blocked_without_prefetch_c); merge_ordered_data_iterator_t<int> merged; merged.add_mergee(a); merged.add_mergee(b); merged.add_mergee(c); ASSERT_FALSE(merged.next()); ASSERT_EQ(blocked_without_prefetch_a, 0); ASSERT_EQ(blocked_without_prefetch_b, 0); ASSERT_EQ(blocked_without_prefetch_c, 0); } TEST(MergeIteratorsTest, parse_data_blocks) { test_iterator::data_blocks_t db = parse_data_blocks("1 2 3 | 42 56 | 93"); ASSERT_EQ(db.size(), 3); ASSERT_EQ(db.front().size(), 3); ASSERT_EQ(db.back().size(), 1); } TEST(MergeIteratorsTest, three_way_merge) { test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10"); test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16"); test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16"); size_t blocked_without_prefetch_a, blocked_without_prefetch_b, blocked_without_prefetch_c; test_iterator *a = new test_iterator(a_db, blocked_without_prefetch_a); test_iterator *b = new test_iterator(b_db, blocked_without_prefetch_b); test_iterator *c = new test_iterator(c_db, blocked_without_prefetch_c); merge_ordered_data_iterator_t<int> merge_iterator; merge_iterator.add_mergee(a); merge_iterator.add_mergee(b); merge_iterator.add_mergee(c); std::list<int> merged; boost::optional<int> next; while ((next = merge_iterator.next())) { merged.push_back(next.get()); } std::list<int> a_db_flat = data_blocks_to_list_of_ints(a_db); std::list<int> b_db_flat = data_blocks_to_list_of_ints(b_db); std::list<int> c_db_flat = data_blocks_to_list_of_ints(c_db); std::list<int> merged_expected; merged_expected.merge(a_db_flat); merged_expected.merge(b_db_flat); merged_expected.merge(c_db_flat); ASSERT_TRUE(std::equal(merged_expected.begin(), merged_expected.end(), merged.begin())); ASSERT_EQ(blocked_without_prefetch_a, 0); ASSERT_EQ(blocked_without_prefetch_b, 0); ASSERT_EQ(blocked_without_prefetch_c, 0); } TEST(MergeIteratorsTest, iterators_get_deleted) { test_iterator::data_blocks_t a_db = parse_data_blocks("1 2 3 | 7 | 10"); test_iterator::data_blocks_t b_db = parse_data_blocks("4 | 6 8 9 | 11 13 16"); test_iterator::data_blocks_t c_db = parse_data_blocks("5 8 | 9 | 12 15 16"); test_iterator::data_blocks_t d_db = parse_data_blocks(""); size_t blocked_without_prefetch_a, blocked_without_prefetch_b, blocked_without_prefetch_c, blocked_without_prefetch_d; bool a_deleted = false, b_deleted = false, c_deleted = false, d_deleted = false; test_iterator *a = new delete_check_iterator(a_db, blocked_without_prefetch_a, &a_deleted); test_iterator *b = new delete_check_iterator(b_db, blocked_without_prefetch_b, &b_deleted); test_iterator *c = new delete_check_iterator(c_db, blocked_without_prefetch_c, &c_deleted); test_iterator *d = new delete_check_iterator(d_db, blocked_without_prefetch_d, &d_deleted); merge_ordered_data_iterator_t<int> merge_iterator; merge_iterator.add_mergee(a); merge_iterator.add_mergee(b); merge_iterator.add_mergee(c); merge_iterator.add_mergee(d); (void) merge_iterator.next(); EXPECT_TRUE(d_deleted); boost::optional<int> next; bool expect_a_deleted = false; while ((next = merge_iterator.next())) { if (expect_a_deleted) { EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted"; } if (next.get() == 10) { expect_a_deleted = true; // when the next element is fetched, merge iterator will recognize that // 'a' iterator has exhausted, so it can delete it } } EXPECT_TRUE(a_deleted) << "merge_ordered_data_iterator_t should have deleted the 'a' iterator long ago"; EXPECT_TRUE(b_deleted && c_deleted) << "merge_ordered_data_iterator_t should delete the iterator after it has exhausted"; ASSERT_EQ(blocked_without_prefetch_a, 0); ASSERT_EQ(blocked_without_prefetch_b, 0); ASSERT_EQ(blocked_without_prefetch_c, 0); ASSERT_EQ(blocked_without_prefetch_d, 0); a_deleted = false; b_deleted = false; { test_iterator *a = new delete_check_iterator(a_db, blocked_without_prefetch_a, &a_deleted); test_iterator *b = new delete_check_iterator(b_db, blocked_without_prefetch_b, &b_deleted); merge_ordered_data_iterator_t<int> merge_iterator; merge_iterator.add_mergee(a); merge_iterator.add_mergee(b); // get some data from the merge iterator, but don't exhaust the iterators (void) merge_iterator.next(); (void) merge_iterator.next(); (void) merge_iterator.next(); } EXPECT_TRUE(a_deleted && b_deleted) << "merge_ordered_data_iterator_t should delete the iterators on destruction, even when they have not been exhausted"; ASSERT_EQ(blocked_without_prefetch_a, 0); ASSERT_EQ(blocked_without_prefetch_b, 0); } } // namespace unittest <|endoftext|>
<commit_before>#pragma once #include "math_helpers.hpp" #include <array> #include <cassert> #include <tuple> namespace cu { /// An N-dimensional point whose coordinate type is @c T. /// /// The coordinates can be accessed via the @c operator[](). /// The constructor takes the same arguments as an @c std::array<T,N>. template <typename T, std::size_t N> class Point { public: template <typename ...Us, typename = decltype(std::array<T,N>{std::declval<Us>()...})> Point( Us && ...args ) : x_{ std::forward<Us>(args)... } {} T &operator[]( std::size_t idx ) { return x_[idx]; } const T & operator[]( std::size_t idx ) const { return x_[idx]; } bool operator==( const Point & other ) { return x_ == other.x_; } private: std::array<T,N> x_; }; /// An @c N-dimensional rectangle whose coordinate type is @c T. /// /// The rectangle is determined by two points @c A and @c B, where no /// coordinate of @c A may be larger than the corresponding coordinate /// of @c B. This ensures, that the edges of the rectangle all have /// non-negative lenghts. template <typename T, std::size_t N> class Rect { using Point = Point<T,N>; public: Rect() {} Rect( Point A, Point B ) : A_(A) , B_(B) { checkInvariants(); } constexpr Point A() const { return A_; } constexpr Point B() const { return B_; } void setA( const Point & P ) { A_ = P; checkInvariants(); } void setB( const Point & P ) { B_ = P; checkInvariants(); } private: void checkInvariants() const { for ( std::size_t i = 0; i != N; ++i ) assert( A_[i] <= B_[i] ); } Point A_; Point B_; }; namespace detail { template <typename T> std::pair<T,T> intersect_interval( const T & a1, const T & b1, const T & a2, const T & b2 ) { if ( b1 < a2 || a1 > b2 ) return { {}, {} }; return { std::max( a1, a2 ), std::min(b1, b2) }; } template <typename T, std::size_t N, std::size_t ...indices> Rect<T,N> intersect_impl( const Rect<T,N> & lhs, const Rect<T,N> & rhs, std::index_sequence<indices...> ) { Point<T,N> A; Point<T,N> B; for ( std::size_t i = 0; i != N; ++i ) { std::tie( A[i], B[i] ) = intersect_interval( lhs.A()[i], lhs.B()[i], rhs.A()[i], rhs.B()[i] ); } return { A, B }; } } /// Calculates the intersection of two rectangles. /// /// If the intersection is empty, then the resulting rectangle will have /// volume @c 0. template <typename T, std::size_t N> Rect<T,N> operator &( const Rect<T,N> & lhs, const Rect<T,N> & rhs ) { return detail::intersect_impl( lhs, rhs, std::make_index_sequence<N>() ); } template <typename T, std::size_t N> bool operator==( const Rect<T,N> & lhs, const Rect<T,N> & rhs ) { return lhs.A() == rhs.A() && lhs.B() == rhs.B(); } } // namespace cu <commit_msg>Compile bug fix. Added namespace to cu::Point.<commit_after>#pragma once #include "math_helpers.hpp" #include <array> #include <cassert> #include <tuple> namespace cu { /// An N-dimensional point whose coordinate type is @c T. /// /// The coordinates can be accessed via the @c operator[](). /// The constructor takes the same arguments as an @c std::array<T,N>. template <typename T, std::size_t N> class Point { public: template <typename ...Us, typename = decltype(std::array<T,N>{std::declval<Us>()...})> Point( Us && ...args ) : x_{ std::forward<Us>(args)... } {} T &operator[]( std::size_t idx ) { return x_[idx]; } const T & operator[]( std::size_t idx ) const { return x_[idx]; } bool operator==( const Point & other ) { return x_ == other.x_; } private: std::array<T,N> x_; }; /// An @c N-dimensional rectangle whose coordinate type is @c T. /// /// The rectangle is determined by two points @c A and @c B, where no /// coordinate of @c A may be larger than the corresponding coordinate /// of @c B. This ensures, that the edges of the rectangle all have /// non-negative lenghts. template <typename T, std::size_t N> class Rect { using Point = cu::Point<T,N>; public: Rect() {} Rect( Point A, Point B ) : A_(A) , B_(B) { checkInvariants(); } constexpr Point A() const { return A_; } constexpr Point B() const { return B_; } void setA( const Point & P ) { A_ = P; checkInvariants(); } void setB( const Point & P ) { B_ = P; checkInvariants(); } private: void checkInvariants() const { for ( std::size_t i = 0; i != N; ++i ) assert( A_[i] <= B_[i] ); } Point A_; Point B_; }; namespace detail { template <typename T> std::pair<T,T> intersect_interval( const T & a1, const T & b1, const T & a2, const T & b2 ) { if ( b1 < a2 || a1 > b2 ) return { {}, {} }; return { std::max( a1, a2 ), std::min(b1, b2) }; } template <typename T, std::size_t N, std::size_t ...indices> Rect<T,N> intersect_impl( const Rect<T,N> & lhs, const Rect<T,N> & rhs, std::index_sequence<indices...> ) { Point<T,N> A; Point<T,N> B; for ( std::size_t i = 0; i != N; ++i ) { std::tie( A[i], B[i] ) = intersect_interval( lhs.A()[i], lhs.B()[i], rhs.A()[i], rhs.B()[i] ); } return { A, B }; } } /// Calculates the intersection of two rectangles. /// /// If the intersection is empty, then the resulting rectangle will have /// volume @c 0. template <typename T, std::size_t N> Rect<T,N> operator &( const Rect<T,N> & lhs, const Rect<T,N> & rhs ) { return detail::intersect_impl( lhs, rhs, std::make_index_sequence<N>() ); } template <typename T, std::size_t N> bool operator==( const Rect<T,N> & lhs, const Rect<T,N> & rhs ) { return lhs.A() == rhs.A() && lhs.B() == rhs.B(); } } // namespace cu <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #define _CONNECTIVITY_COMMONTOOLS_HXX_ #include <rtl/ustring.hxx> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/uno/Any.hxx> #ifndef _VECTOR_ #include <vector> #endif #include <cppuhelper/weakref.hxx> #include <comphelper/stl_types.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #include <osl/interlck.h> #include <jvmaccess/virtualmachine.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include "connectivity/dbtoolsdllapi.hxx" namespace com { namespace sun { namespace star { namespace util { struct Date; struct DateTime; struct Time; } }}} namespace connectivity { //------------------------------------------------------------------------------ OOO_DLLPUBLIC_DBTOOLS sal_Bool match(const sal_Unicode* pWild, const sal_Unicode* pStr, const sal_Unicode cEscape); //------------------------------------------------------------------------------ OOO_DLLPUBLIC_DBTOOLS rtl::OUString toString(const ::com::sun::star::uno::Any& rValue); OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateString(const ::com::sun::star::util::Date& rDate); OOO_DLLPUBLIC_DBTOOLS rtl::OUString toTimeString(const ::com::sun::star::util::Time& rTime); OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateTimeString(const ::com::sun::star::util::DateTime& rDateTime); // typedefs typedef std::vector< ::com::sun::star::uno::WeakReferenceHelper > OWeakRefArray; typedef ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> OSQLTable; DECLARE_STL_MAP(::rtl::OUString,OSQLTable,comphelper::UStringMixLess, OSQLTables); // ------------------------------------------------------------------------- // class ORefVector allows reference counting on a std::vector // ------------------------------------------------------------------------- template< class VectorVal > class ORefVector { std::vector< VectorVal > m_vector; oslInterlockedCount m_refCount; protected: virtual ~ORefVector(){} public: typedef std::vector< VectorVal > Vector; ORefVector() : m_refCount(0) {} ORefVector(size_t _st) : m_vector(_st) , m_refCount(0) {} ORefVector(const ORefVector& _rRH) : m_vector(_rRH.m_vector),m_refCount(0) { } ORefVector& operator=(const ORefVector& _rRH) { if ( &_rRH != this ) { m_vector = _rRH.m_vector; } return *this; } std::vector< VectorVal > & get() { return m_vector; } std::vector< VectorVal > const & get() const { return m_vector; } inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW( () ) { return ::rtl_allocateMemory( nSize ); } inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW( () ) { ::rtl_freeMemory( pMem ); } inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW( () ) { return pMem; } inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW( () ) {} void acquire() { osl_incrementInterlockedCount( &m_refCount ); } void release() { if (! osl_decrementInterlockedCount( &m_refCount )) delete this; } }; // ------------------------------------------------------------------------- // class ORowVector incudes refcounting and initialze himself // with at least one element. This first element is reserved for // the bookmark // ------------------------------------------------------------------------- template< class VectorVal > class ORowVector : public ORefVector< VectorVal > { public: ORowVector() : ORefVector< VectorVal >(1){} ORowVector(size_t _st) : ORefVector< VectorVal >(_st+1) {} }; typedef ORefVector< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > OSQLColumns; // ======================================================================================= // search from __first to __last the column with the name _rVal // when no such column exist __last is returned OOO_DLLPUBLIC_DBTOOLS OSQLColumns::Vector::const_iterator find( OSQLColumns::Vector::const_iterator __first, OSQLColumns::Vector::const_iterator __last, const ::rtl::OUString& _rVal, const ::comphelper::UStringMixEqual& _rCase); // ======================================================================================= // search from __first to __last the column with the realname _rVal // when no such column exist __last is returned OOO_DLLPUBLIC_DBTOOLS OSQLColumns::Vector::const_iterator findRealName( OSQLColumns::Vector::const_iterator __first, OSQLColumns::Vector::const_iterator __last, const ::rtl::OUString& _rVal, const ::comphelper::UStringMixEqual& _rCase); // ======================================================================================= // the first two find methods are much faster than the one below // ======================================================================================= // search from __first to __last the column with the property _rProp equals the value _rVal // when no such column exist __last is returned OOO_DLLPUBLIC_DBTOOLS OSQLColumns::Vector::const_iterator find( OSQLColumns::Vector::const_iterator __first, OSQLColumns::Vector::const_iterator __last, const ::rtl::OUString& _rProp, const ::rtl::OUString& _rVal, const ::comphelper::UStringMixEqual& _rCase); OOO_DLLPUBLIC_DBTOOLS void checkDisposed(sal_Bool _bThrow) throw ( ::com::sun::star::lang::DisposedException ); /** creates a java virtual machine @param _rxFactory The ORB. @return The JavaVM. */ OOO_DLLPUBLIC_DBTOOLS ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory); /** return <TRUE/> if the java class exists, otherwise <FALSE/>. @param _pJVM The JavaVM. @param _sClassName The class name to look for. */ OOO_DLLPUBLIC_DBTOOLS sal_Bool existsJavaClassByName( const ::rtl::Reference< jvmaccess::VirtualMachine >& _pJVM,const ::rtl::OUString& _sClassName ); } //================================================================================== #define DECLARE_SERVICE_INFO() \ virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); \ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); \ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) \ #define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname) \ ::rtl::OUString SAL_CALL classname::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) \ { \ return ::rtl::OUString::createFromAscii(implasciiname); \ } \ ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL classname::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) \ { \ ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1); \ aSupported[0] = ::rtl::OUString::createFromAscii(serviceasciiname); \ return aSupported; \ } \ sal_Bool SAL_CALL classname::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) \ { \ Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); \ const ::rtl::OUString* pSupported = aSupported.getConstArray(); \ const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); \ for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) \ ; \ \ return pSupported != pEnd; \ } \ //================================================================================== #endif // _CONNECTIVITY_COMMONTOOLS_HXX_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>overload match and avoid implicit cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #define _CONNECTIVITY_COMMONTOOLS_HXX_ #include <rtl/ustring.hxx> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/uno/Any.hxx> #ifndef _VECTOR_ #include <vector> #endif #include <cppuhelper/weakref.hxx> #include <comphelper/stl_types.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #include <osl/interlck.h> #include <jvmaccess/virtualmachine.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include "connectivity/dbtoolsdllapi.hxx" namespace com { namespace sun { namespace star { namespace util { struct Date; struct DateTime; struct Time; } }}} namespace connectivity { //------------------------------------------------------------------------------ OOO_DLLPUBLIC_DBTOOLS sal_Bool match(const sal_Unicode* pWild, const sal_Unicode* pStr, const sal_Unicode cEscape); inline sal_Bool match(const ::rtl::OUString &rWild, const ::rtl::OUString &rStr, const sal_Unicode cEscape) { return match(rWild.getStr(), rStr.getStr(), cEscape); } //------------------------------------------------------------------------------ OOO_DLLPUBLIC_DBTOOLS rtl::OUString toString(const ::com::sun::star::uno::Any& rValue); OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateString(const ::com::sun::star::util::Date& rDate); OOO_DLLPUBLIC_DBTOOLS rtl::OUString toTimeString(const ::com::sun::star::util::Time& rTime); OOO_DLLPUBLIC_DBTOOLS rtl::OUString toDateTimeString(const ::com::sun::star::util::DateTime& rDateTime); // typedefs typedef std::vector< ::com::sun::star::uno::WeakReferenceHelper > OWeakRefArray; typedef ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> OSQLTable; DECLARE_STL_MAP(::rtl::OUString,OSQLTable,comphelper::UStringMixLess, OSQLTables); // ------------------------------------------------------------------------- // class ORefVector allows reference counting on a std::vector // ------------------------------------------------------------------------- template< class VectorVal > class ORefVector { std::vector< VectorVal > m_vector; oslInterlockedCount m_refCount; protected: virtual ~ORefVector(){} public: typedef std::vector< VectorVal > Vector; ORefVector() : m_refCount(0) {} ORefVector(size_t _st) : m_vector(_st) , m_refCount(0) {} ORefVector(const ORefVector& _rRH) : m_vector(_rRH.m_vector),m_refCount(0) { } ORefVector& operator=(const ORefVector& _rRH) { if ( &_rRH != this ) { m_vector = _rRH.m_vector; } return *this; } std::vector< VectorVal > & get() { return m_vector; } std::vector< VectorVal > const & get() const { return m_vector; } inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW( () ) { return ::rtl_allocateMemory( nSize ); } inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW( () ) { ::rtl_freeMemory( pMem ); } inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW( () ) { return pMem; } inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW( () ) {} void acquire() { osl_incrementInterlockedCount( &m_refCount ); } void release() { if (! osl_decrementInterlockedCount( &m_refCount )) delete this; } }; // ------------------------------------------------------------------------- // class ORowVector incudes refcounting and initialze himself // with at least one element. This first element is reserved for // the bookmark // ------------------------------------------------------------------------- template< class VectorVal > class ORowVector : public ORefVector< VectorVal > { public: ORowVector() : ORefVector< VectorVal >(1){} ORowVector(size_t _st) : ORefVector< VectorVal >(_st+1) {} }; typedef ORefVector< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > OSQLColumns; // ======================================================================================= // search from __first to __last the column with the name _rVal // when no such column exist __last is returned OOO_DLLPUBLIC_DBTOOLS OSQLColumns::Vector::const_iterator find( OSQLColumns::Vector::const_iterator __first, OSQLColumns::Vector::const_iterator __last, const ::rtl::OUString& _rVal, const ::comphelper::UStringMixEqual& _rCase); // ======================================================================================= // search from __first to __last the column with the realname _rVal // when no such column exist __last is returned OOO_DLLPUBLIC_DBTOOLS OSQLColumns::Vector::const_iterator findRealName( OSQLColumns::Vector::const_iterator __first, OSQLColumns::Vector::const_iterator __last, const ::rtl::OUString& _rVal, const ::comphelper::UStringMixEqual& _rCase); // ======================================================================================= // the first two find methods are much faster than the one below // ======================================================================================= // search from __first to __last the column with the property _rProp equals the value _rVal // when no such column exist __last is returned OOO_DLLPUBLIC_DBTOOLS OSQLColumns::Vector::const_iterator find( OSQLColumns::Vector::const_iterator __first, OSQLColumns::Vector::const_iterator __last, const ::rtl::OUString& _rProp, const ::rtl::OUString& _rVal, const ::comphelper::UStringMixEqual& _rCase); OOO_DLLPUBLIC_DBTOOLS void checkDisposed(sal_Bool _bThrow) throw ( ::com::sun::star::lang::DisposedException ); /** creates a java virtual machine @param _rxFactory The ORB. @return The JavaVM. */ OOO_DLLPUBLIC_DBTOOLS ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory); /** return <TRUE/> if the java class exists, otherwise <FALSE/>. @param _pJVM The JavaVM. @param _sClassName The class name to look for. */ OOO_DLLPUBLIC_DBTOOLS sal_Bool existsJavaClassByName( const ::rtl::Reference< jvmaccess::VirtualMachine >& _pJVM,const ::rtl::OUString& _sClassName ); } //================================================================================== #define DECLARE_SERVICE_INFO() \ virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); \ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); \ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) \ #define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname) \ ::rtl::OUString SAL_CALL classname::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) \ { \ return ::rtl::OUString::createFromAscii(implasciiname); \ } \ ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL classname::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) \ { \ ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1); \ aSupported[0] = ::rtl::OUString::createFromAscii(serviceasciiname); \ return aSupported; \ } \ sal_Bool SAL_CALL classname::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) \ { \ Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); \ const ::rtl::OUString* pSupported = aSupported.getConstArray(); \ const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); \ for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) \ ; \ \ return pSupported != pEnd; \ } \ //================================================================================== #endif // _CONNECTIVITY_COMMONTOOLS_HXX_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|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 <sal/macros.h> #include "MDriver.hxx" #include "MConnection.hxx" #include "connectivity/dbexception.hxx" #include "resource/mozab_res.hrc" #include "resource/common_res.hrc" #include <tools/solar.h> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace connectivity::mozab; namespace connectivity { namespace mozab { //------------------------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ) { return *(new MozabDriver( _rxFactory )); } } } // -------------------------------------------------------------------------------- MozabDriver::MozabDriver( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) : ODriver_BASE(m_aMutex), m_xMSFactory( _rxFactory ) ,m_hModule(NULL) ,m_pCreationFunc(NULL) { } // ----------------------------------------------------------------------------- MozabDriver::~MozabDriver() { } // -------------------------------------------------------------------------------- void MozabDriver::disposing() { ::osl::MutexGuard aGuard(m_aMutex); // when driver will be destroied so all our connections have to be destroied as well for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i) { Reference< XComponent > xComp(i->get(), UNO_QUERY); if (xComp.is()) xComp->dispose(); } m_xConnections.clear(); connectivity::OWeakRefArray().swap(m_xConnections); // this really clears ODriver_BASE::disposing(); if(m_hModule) { m_pCreationFunc = NULL; osl_unloadModule(m_hModule); m_hModule = NULL; } } // static ServiceInfo //------------------------------------------------------------------------------ rtl::OUString MozabDriver::getImplementationName_Static( ) throw(RuntimeException) { return rtl::OUString(MOZAB_DRIVER_IMPL_NAME); // this name is referenced in the configuration and in the mozab.xml // Please take care when changing it. } //------------------------------------------------------------------------------ Sequence< ::rtl::OUString > MozabDriver::getSupportedServiceNames_Static( ) throw (RuntimeException) { // which service is supported // for more information @see com.sun.star.sdbc.Driver Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString( "com.sun.star.sdbc.Driver"); return aSNS; } //------------------------------------------------------------------ ::rtl::OUString SAL_CALL MozabDriver::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //------------------------------------------------------------------ sal_Bool SAL_CALL MozabDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } //------------------------------------------------------------------ Sequence< ::rtl::OUString > SAL_CALL MozabDriver::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } // -------------------------------------------------------------------------------- Reference< XConnection > SAL_CALL MozabDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { if ( !ensureInit() ) return NULL; if ( ! acceptsURL( url ) ) return NULL; // create a new connection with the given properties and append it to our vector Reference< XConnection > xCon; if (m_pCreationFunc) { ::osl::MutexGuard aGuard(m_aMutex); //We must make sure we create an com.sun.star.mozilla.MozillaBootstrap brfore call any mozilla codes Reference<XInterface> xInstance = m_xMSFactory->createInstance(::rtl::OUString( "com.sun.star.mozilla.MozillaBootstrap") ); OSL_ENSURE( xInstance.is(), "failed to create instance" ); OConnection* pCon = reinterpret_cast<OConnection*>((*m_pCreationFunc)(this)); xCon = pCon; // important here because otherwise the connection could be deleted inside (refcount goes -> 0) pCon->construct(url,info); // late constructor call which can throw exception and allows a correct dtor call when so m_xConnections.push_back(WeakReferenceHelper(*pCon)); } else { ::connectivity::SharedResources aResources; const ::rtl::OUString sError( aResources.getResourceStringWithSubstitution( STR_COULD_NOT_LOAD_LIB, "$libname$", ::rtl::OUString( SVLIBRARY( "mozabdrv" ) ) ) ); ::dbtools::throwGenericSQLException(sError,*this); } return xCon; } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL MozabDriver::acceptsURL( const ::rtl::OUString& url ) throw(SQLException, RuntimeException) { if ( !ensureInit() ) return sal_False; // here we have to look if we support this url format return impl_classifyURL(url) != Unknown; } // -------------------------------------------------------------------------------- Sequence< DriverPropertyInfo > SAL_CALL MozabDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException) { if ( !ensureInit() ) return Sequence< DriverPropertyInfo >(); if ( acceptsURL(url) ) { if ( impl_classifyURL(url) != LDAP ) return Sequence< DriverPropertyInfo >(); ::std::vector< DriverPropertyInfo > aDriverInfo; aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("BaseDN") ,::rtl::OUString("Base DN.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("MaxRowCount") ,::rtl::OUString("Records (max.)") ,sal_False ,::rtl::OUString("100") ,Sequence< ::rtl::OUString >()) ); return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size()); } ::connectivity::SharedResources aResources; const ::rtl::OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR); ::dbtools::throwGenericSQLException(sMessage ,*this); // if you have something special to say return it here :-) return Sequence< DriverPropertyInfo >(); } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL MozabDriver::getMajorVersion( ) throw(RuntimeException) { return 1; // depends on you } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL MozabDriver::getMinorVersion( ) throw(RuntimeException) { return 0; // depends on you } // -------------------------------------------------------------------------------- EDriverType MozabDriver::impl_classifyURL( const ::rtl::OUString& url ) { // Skip 'sdbc:mozab: part of URL // sal_Int32 nLen = url.indexOf(':'); nLen = url.indexOf(':',nLen+1); ::rtl::OUString aAddrbookURI(url.copy(nLen+1)); // Get Scheme nLen = aAddrbookURI.indexOf(':'); ::rtl::OUString aAddrbookScheme; if ( nLen == -1 ) { // There isn't any subschema: - but could be just subschema if ( !aAddrbookURI.isEmpty() ) aAddrbookScheme= aAddrbookURI; else if(url == ::rtl::OUString("sdbc:address:") ) return Unknown; // TODO check else return Unknown; } else aAddrbookScheme = aAddrbookURI.copy(0, nLen); struct __scheme_map { EDriverType eType; const sal_Char* pScheme; } aSchemeMap[] = { #if defined(WNT) { Outlook, "outlook" }, { OutlookExpress, "outlookexp" }, #endif { Mozilla, "mozilla" }, { ThunderBird, "thunderbird" }, { LDAP, "ldap" } }; for ( size_t i=0; i < sizeof( aSchemeMap ) / sizeof( aSchemeMap[0] ); ++i ) { if ( aAddrbookScheme.compareToAscii( aSchemeMap[i].pScheme ) == 0 ) return aSchemeMap[i].eType; } return Unknown; } // -------------------------------------------------------------------------------- namespace { template< typename FUNCTION > void lcl_getFunctionFromModuleOrUnload( oslModule& _rModule, const sal_Char* _pAsciiSymbolName, FUNCTION& _rFunction ) { _rFunction = NULL; if ( _rModule ) { const ::rtl::OUString sSymbolName = ::rtl::OUString::createFromAscii( _pAsciiSymbolName ); _rFunction = (FUNCTION)( osl_getFunctionSymbol( _rModule, sSymbolName.pData ) ); if ( !_rFunction ) { // did not find the symbol OSL_FAIL( ( ::rtl::OString( "lcl_getFunctionFromModuleOrUnload: could not find the symbol " ) + ::rtl::OString( _pAsciiSymbolName ) ).getStr() ); osl_unloadModule( _rModule ); _rModule = NULL; } } } } // ----------------------------------------------------------------------------- extern "C" { static void SAL_CALL thisModule() {} } bool MozabDriver::ensureInit() { if ( m_hModule ) return true; OSL_ENSURE(NULL == m_pCreationFunc, "MozabDriver::ensureInit: inconsistence: already have a factory function!"); const ::rtl::OUString sModuleName(SVLIBRARY( "mozabdrv" )); // load the mozabdrv library m_hModule = osl_loadModuleRelative(&thisModule, sModuleName.pData, 0); OSL_ENSURE(NULL != m_hModule, "MozabDriver::ensureInit: could not load the mozabdrv library!"); if ( !m_hModule ) return false; OSetMozabServiceFactory pSetFactoryFunc( NULL ); lcl_getFunctionFromModuleOrUnload( m_hModule, "setMozabServiceFactory", pSetFactoryFunc ); lcl_getFunctionFromModuleOrUnload( m_hModule, "OMozabConnection_CreateInstance", m_pCreationFunc ); if ( !m_hModule ) // one of the symbols did not exist return false; if ( m_xMSFactory.is() ) { // for purpose of transfer safety, the interface needs to be acuired once // (will be release by the callee) m_xMSFactory->acquire(); ( *pSetFactoryFunc )( m_xMSFactory.get() ); } return true; } // ----------------------------------------------------------------------------- /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix debug build<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 <sal/macros.h> #include "MDriver.hxx" #include "MConnection.hxx" #include "connectivity/dbexception.hxx" #include "resource/mozab_res.hrc" #include "resource/common_res.hrc" #include <tools/solar.h> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace connectivity::mozab; namespace connectivity { namespace mozab { //------------------------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL MozabDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ) { return *(new MozabDriver( _rxFactory )); } } } // -------------------------------------------------------------------------------- MozabDriver::MozabDriver( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) : ODriver_BASE(m_aMutex), m_xMSFactory( _rxFactory ) ,m_hModule(NULL) ,m_pCreationFunc(NULL) { } // ----------------------------------------------------------------------------- MozabDriver::~MozabDriver() { } // -------------------------------------------------------------------------------- void MozabDriver::disposing() { ::osl::MutexGuard aGuard(m_aMutex); // when driver will be destroied so all our connections have to be destroied as well for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i) { Reference< XComponent > xComp(i->get(), UNO_QUERY); if (xComp.is()) xComp->dispose(); } m_xConnections.clear(); connectivity::OWeakRefArray().swap(m_xConnections); // this really clears ODriver_BASE::disposing(); if(m_hModule) { m_pCreationFunc = NULL; osl_unloadModule(m_hModule); m_hModule = NULL; } } // static ServiceInfo //------------------------------------------------------------------------------ rtl::OUString MozabDriver::getImplementationName_Static( ) throw(RuntimeException) { return rtl::OUString(MOZAB_DRIVER_IMPL_NAME); // this name is referenced in the configuration and in the mozab.xml // Please take care when changing it. } //------------------------------------------------------------------------------ Sequence< ::rtl::OUString > MozabDriver::getSupportedServiceNames_Static( ) throw (RuntimeException) { // which service is supported // for more information @see com.sun.star.sdbc.Driver Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString( "com.sun.star.sdbc.Driver"); return aSNS; } //------------------------------------------------------------------ ::rtl::OUString SAL_CALL MozabDriver::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //------------------------------------------------------------------ sal_Bool SAL_CALL MozabDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } //------------------------------------------------------------------ Sequence< ::rtl::OUString > SAL_CALL MozabDriver::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } // -------------------------------------------------------------------------------- Reference< XConnection > SAL_CALL MozabDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { if ( !ensureInit() ) return NULL; if ( ! acceptsURL( url ) ) return NULL; // create a new connection with the given properties and append it to our vector Reference< XConnection > xCon; if (m_pCreationFunc) { ::osl::MutexGuard aGuard(m_aMutex); //We must make sure we create an com.sun.star.mozilla.MozillaBootstrap brfore call any mozilla codes Reference<XInterface> xInstance = m_xMSFactory->createInstance(::rtl::OUString( "com.sun.star.mozilla.MozillaBootstrap") ); OSL_ENSURE( xInstance.is(), "failed to create instance" ); OConnection* pCon = reinterpret_cast<OConnection*>((*m_pCreationFunc)(this)); xCon = pCon; // important here because otherwise the connection could be deleted inside (refcount goes -> 0) pCon->construct(url,info); // late constructor call which can throw exception and allows a correct dtor call when so m_xConnections.push_back(WeakReferenceHelper(*pCon)); } else { ::connectivity::SharedResources aResources; const ::rtl::OUString sError( aResources.getResourceStringWithSubstitution( STR_COULD_NOT_LOAD_LIB, "$libname$", ::rtl::OUString( SVLIBRARY( "mozabdrv" ) ) ) ); ::dbtools::throwGenericSQLException(sError,*this); } return xCon; } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL MozabDriver::acceptsURL( const ::rtl::OUString& url ) throw(SQLException, RuntimeException) { if ( !ensureInit() ) return sal_False; // here we have to look if we support this url format return impl_classifyURL(url) != Unknown; } // -------------------------------------------------------------------------------- Sequence< DriverPropertyInfo > SAL_CALL MozabDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException) { if ( !ensureInit() ) return Sequence< DriverPropertyInfo >(); if ( acceptsURL(url) ) { if ( impl_classifyURL(url) != LDAP ) return Sequence< DriverPropertyInfo >(); ::std::vector< DriverPropertyInfo > aDriverInfo; aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("BaseDN") ,::rtl::OUString("Base DN.") ,sal_False ,::rtl::OUString() ,Sequence< ::rtl::OUString >()) ); aDriverInfo.push_back(DriverPropertyInfo( ::rtl::OUString("MaxRowCount") ,::rtl::OUString("Records (max.)") ,sal_False ,::rtl::OUString("100") ,Sequence< ::rtl::OUString >()) ); return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size()); } ::connectivity::SharedResources aResources; const ::rtl::OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR); ::dbtools::throwGenericSQLException(sMessage ,*this); // if you have something special to say return it here :-) return Sequence< DriverPropertyInfo >(); } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL MozabDriver::getMajorVersion( ) throw(RuntimeException) { return 1; // depends on you } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL MozabDriver::getMinorVersion( ) throw(RuntimeException) { return 0; // depends on you } // -------------------------------------------------------------------------------- EDriverType MozabDriver::impl_classifyURL( const ::rtl::OUString& url ) { // Skip 'sdbc:mozab: part of URL // sal_Int32 nLen = url.indexOf(':'); nLen = url.indexOf(':',nLen+1); ::rtl::OUString aAddrbookURI(url.copy(nLen+1)); // Get Scheme nLen = aAddrbookURI.indexOf(':'); ::rtl::OUString aAddrbookScheme; if ( nLen == -1 ) { // There isn't any subschema: - but could be just subschema if ( !aAddrbookURI.isEmpty() ) aAddrbookScheme= aAddrbookURI; else if(url == ::rtl::OUString("sdbc:address:") ) return Unknown; // TODO check else return Unknown; } else aAddrbookScheme = aAddrbookURI.copy(0, nLen); struct __scheme_map { EDriverType eType; const sal_Char* pScheme; } aSchemeMap[] = { #if defined(WNT) { Outlook, "outlook" }, { OutlookExpress, "outlookexp" }, #endif { Mozilla, "mozilla" }, { ThunderBird, "thunderbird" }, { LDAP, "ldap" } }; for ( size_t i=0; i < sizeof( aSchemeMap ) / sizeof( aSchemeMap[0] ); ++i ) { if ( aAddrbookScheme.compareToAscii( aSchemeMap[i].pScheme ) == 0 ) return aSchemeMap[i].eType; } return Unknown; } // -------------------------------------------------------------------------------- namespace { template< typename FUNCTION > void lcl_getFunctionFromModuleOrUnload( oslModule& _rModule, const sal_Char* _pAsciiSymbolName, FUNCTION& _rFunction ) { _rFunction = NULL; if ( _rModule ) { const ::rtl::OUString sSymbolName = ::rtl::OUString::createFromAscii( _pAsciiSymbolName ); _rFunction = (FUNCTION)( osl_getFunctionSymbol( _rModule, sSymbolName.pData ) ); if ( !_rFunction ) { // did not find the symbol rtl::OUStringBuffer aBuf; aBuf.append( "lcl_getFunctionFromModuleOrUnload: could not find the symbol " ); aBuf.append( sSymbolName ); OSL_FAIL( aBuf.makeStringAndClear().getStr() ); osl_unloadModule( _rModule ); _rModule = NULL; } } } } // ----------------------------------------------------------------------------- extern "C" { static void SAL_CALL thisModule() {} } bool MozabDriver::ensureInit() { if ( m_hModule ) return true; OSL_ENSURE(NULL == m_pCreationFunc, "MozabDriver::ensureInit: inconsistence: already have a factory function!"); const ::rtl::OUString sModuleName(SVLIBRARY( "mozabdrv" )); // load the mozabdrv library m_hModule = osl_loadModuleRelative(&thisModule, sModuleName.pData, 0); OSL_ENSURE(NULL != m_hModule, "MozabDriver::ensureInit: could not load the mozabdrv library!"); if ( !m_hModule ) return false; OSetMozabServiceFactory pSetFactoryFunc( NULL ); lcl_getFunctionFromModuleOrUnload( m_hModule, "setMozabServiceFactory", pSetFactoryFunc ); lcl_getFunctionFromModuleOrUnload( m_hModule, "OMozabConnection_CreateInstance", m_pCreationFunc ); if ( !m_hModule ) // one of the symbols did not exist return false; if ( m_xMSFactory.is() ) { // for purpose of transfer safety, the interface needs to be acuired once // (will be release by the callee) m_xMSFactory->acquire(); ( *pSetFactoryFunc )( m_xMSFactory.get() ); } return true; } // ----------------------------------------------------------------------------- /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "code/ylikuutio/ontology/symbiosis.hpp" #include "code/ylikuutio/ontology/symbiont_species.hpp" #include "code/ylikuutio/ontology/symbiosis_struct.hpp" #include "code/ylikuutio/command_line/command_line_master.hpp" #include "code/ylikuutio/string/ylikuutio_string.hpp" #include "assimp/scene.h" #include "assimp/Exporter.hpp" #include "assimp/types.h" #define SDL_main main #include "SDL.h" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <algorithm> // std::transform #include <cstddef> // std::size_t #include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS #include <iostream> // std::cout, std::cin, std::cerr #include <limits> // std::numeric_limits #include <string> // std::string #include <vector> // std::vector // `yli_convert` is a command-line tool to load and export 3D data between different formats. // // parameters: // required: // `--in=foo` load 3D data from file `foo`. // `--in foo` load 3D data from file `foo`. // `--out=bar` export 3D data into file `bar`. // `--out bar` export 3D data into file `bar`. // // optional: // `--informat=baz` assume file format `baz` (if `--informat` is left out, file format is deduced from the filename extension). // `--informat baz` assume file format `baz` (if `--informat` is left out, file format is deduced from the filename extension). // `--outformat=qux` export 3D data into file `qux` (if `--outformat` is left out, file format is deduced from the filename extension). // `--outformat qux` export 3D data into file `qux` (if `--outformat` is left out, file format is deduced from the filename extension). // `--intexture=quux` use texture data into file `quux` as the material for all meshes (eg. `.obj` input file). // `--intexture quux` use texture data into file `quux` as the material for all meshes (eg. `.obj` input file). namespace yli { namespace ontology { class Universe; } } int main(const int argc, const char* argv[]) { yli::command_line::CommandLineMaster command_line_master(argc, argv); command_line_master.print_keys_and_values(); if (!command_line_master.is_key("in")) { std::cerr << "ERROR: --in parameter is required!\n\nexample:\n\nyli_convert --in=foo --out=bar\n"; exit(EXIT_FAILURE); } if (!command_line_master.is_key("out")) { std::cerr << "ERROR: --out parameter is required!\n\nexample:\n\nyli_convert --in=foo --out=bar\n"; exit(EXIT_FAILURE); } const std::string in_file = command_line_master.get_value("in"); const std::string out_file = command_line_master.get_value("out"); std::string in_file_format = ""; // dummy value. if (command_line_master.is_key("informat")) { in_file_format = command_line_master.get_value("informat"); } else { const char separator = '.'; yli::string::extract_last_part_of_string(in_file, in_file_format, separator); } if (in_file_format.empty()) { std::cerr << "ERROR: --informat is empty!\n"; exit(EXIT_FAILURE); } std::cout << "in file format is " << in_file_format << "\n"; std::string out_file_format = ""; // dummy value. if (command_line_master.is_key("outformat")) { out_file_format = command_line_master.get_value("outformat"); } else { const char separator = '.'; yli::string::extract_last_part_of_string(out_file, out_file_format, separator); } if (out_file_format.empty()) { std::cerr << "ERROR: --outformat is empty!\n"; exit(EXIT_FAILURE); } std::cout << "out file format is " << out_file_format << "\n"; // OK, all required input is given in the correct format. // convert in file format & out file format into lowercase. std::transform(in_file_format.begin(), in_file_format.end(), in_file_format.begin(), ::tolower); std::transform(out_file_format.begin(), out_file_format.end(), out_file_format.begin(), ::tolower); if (in_file_format != "obj" && in_file_format != "fbx") { std::cerr << "ERROR: unsupported in file format: " << in_file_format << "\n"; exit(EXIT_FAILURE); } // Always load the 3D object into a `yli::ontology::Symbiosis`. SymbiosisStruct symbiosis_struct; symbiosis_struct.model_filename = in_file; symbiosis_struct.model_file_format = in_file_format; symbiosis_struct.triangulation_type = "bilinear_interpolation"; symbiosis_struct.parent = nullptr; // no parent. symbiosis_struct.vram_buffer_in_use = false; // do not use VRAM buffer. yli::ontology::Universe* const universe = nullptr; const yli::ontology::Symbiosis symbiosis = yli::ontology::Symbiosis(universe, symbiosis_struct); // Assimp usage example: // https://github.com/assimp/assimp/issues/203 aiScene ai_scene; ai_scene.mRootNode = new aiNode(); ai_scene.mNumMaterials = symbiosis.get_number_of_symbiont_materials(); ai_scene.mMaterials = new aiMaterial*[ai_scene.mNumMaterials]; ai_scene.mNumAnimations = 0; // yli_convert does not yet support animations. ai_scene.mAnimations = nullptr; // yli_convert does not yet support animations. ai_scene.mNumTextures = symbiosis.get_number_of_symbiont_materials(); ai_scene.mTextures = new aiTexture*[ai_scene.mNumMaterials]; ai_scene.mNumLights = 0; // yli_convert does not yet support lights. ai_scene.mLights = nullptr; // yli_convert does not yet support lights. ai_scene.mNumCameras = 0; // yli_convert does not yet support cameras. ai_scene.mCameras = nullptr; // yli_convert does not yet support cameras. ai_scene.mMetaData = nullptr; // yli_convert does not yet support metadata. ai_scene.mNumMeshes = symbiosis.get_number_of_symbiont_species(); ai_scene.mMeshes = new aiMesh*[ai_scene.mNumMeshes]; ai_scene.mRootNode->mNumMeshes = symbiosis.get_number_of_symbiont_species(); ai_scene.mRootNode->mMeshes = new unsigned int[symbiosis.get_number_of_symbiont_species()]; std::cout << "Number of `SymbiontMaterial`s: " << symbiosis.get_number_of_symbiont_materials() << "\n"; for (std::size_t symbiont_material_i = 0; symbiont_material_i < symbiosis.get_number_of_symbiont_materials(); symbiont_material_i++) { std::cout << "Processing `SymbiontMaterial` " << symbiont_material_i << "\n"; const yli::ontology::SymbiontMaterial* const symbiont_material = symbiosis.get_symbiont_material(symbiont_material_i); ai_scene.mMaterials[symbiont_material_i] = new aiMaterial(); ai_scene.mTextures[symbiont_material_i] = new aiTexture(); if (symbiont_material == nullptr) { std::cerr << "ERROR: `yli_convert`: `symbiont_material` is `nullptr`!\n"; continue; } ai_scene.mTextures[symbiont_material_i]->mWidth = static_cast<unsigned int>(symbiont_material->get_image_width()); ai_scene.mTextures[symbiont_material_i]->mHeight = static_cast<unsigned int>(symbiont_material->get_image_height()); if (symbiont_material->get_childID() == std::numeric_limits<std::size_t>::max()) { // childID is the default (invalid) value, not a real childID! std::cerr << "ERROR: `yli_convert`: `childID` is `std::numeric_limits<std::size_t>::max()`!\n"; continue; } } for (std::size_t symbiont_species_i = 0; symbiont_species_i < symbiosis.get_number_of_symbiont_species(); symbiont_species_i++) { ai_scene.mRootNode->mMeshes[symbiont_species_i] = symbiont_species_i; ai_scene.mMeshes[symbiont_species_i] = new aiMesh(); const yli::ontology::SymbiontSpecies* const symbiont_species = symbiosis.get_symbiont_species(symbiont_species_i); if (symbiont_species == nullptr) { std::cerr << "ERROR: `yli_convert`: `symbiont_species` is `nullptr`!\n"; continue; } const yli::ontology::SymbiontMaterial* const symbiont_material = static_cast<yli::ontology::SymbiontMaterial*>(symbiont_species->get_parent()); if (symbiont_material == nullptr) { std::cerr << "ERROR: `yli_convert`: `symbiont_material` is `nullptr`!\n"; continue; } ai_scene.mMeshes[symbiont_species_i]->mMaterialIndex = symbiont_material->get_childID(); const std::vector<glm::vec3>& vertices = symbiont_species->get_vertices(); const std::vector<glm::vec3>& normals = symbiont_species->get_normals(); const std::vector<glm::vec2>& uvs = symbiont_species->get_uvs(); const std::size_t number_of_vertices = vertices.size(); ai_scene.mMeshes[symbiont_species_i]->mNumVertices = number_of_vertices; ai_scene.mMeshes[symbiont_species_i]->mVertices = new aiVector3D[number_of_vertices]; ai_scene.mMeshes[symbiont_species_i]->mNormals = new aiVector3D[number_of_vertices]; ai_scene.mMeshes[symbiont_species_i]->mTextureCoords[0] = new aiVector3D[number_of_vertices]; ai_scene.mMeshes[symbiont_species_i]->mNumUVComponents[0] = number_of_vertices; for (std::size_t vertex_i = 0; vertex_i < number_of_vertices; vertex_i++) { ai_scene.mMeshes[symbiont_species_i]->mVertices[vertex_i] = aiVector3D(vertices[vertex_i].x, vertices[vertex_i].y, vertices[vertex_i].z); ai_scene.mMeshes[symbiont_species_i]->mNormals[vertex_i] = aiVector3D(normals[vertex_i].x, normals[vertex_i].y, normals[vertex_i].z); ai_scene.mMeshes[symbiont_species_i]->mTextureCoords[0][vertex_i] = aiVector3D(uvs[vertex_i].x, uvs[vertex_i].y, 0); } const std::size_t number_of_faces = number_of_vertices / 3; std::cout << "Number of faces: " << number_of_faces << "\n"; ai_scene.mMeshes[symbiont_species_i]->mFaces = new aiFace[number_of_faces]; ai_scene.mMeshes[symbiont_species_i]->mNumFaces = number_of_faces; for (std::size_t face_i = 0; face_i < number_of_faces; face_i++) { ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices = new unsigned int[3]; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mNumIndices = 3; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices[0] = 3 * face_i; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices[1] = 3 * face_i + 1; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices[2] = 3 * face_i + 2; } } std::cout << "Creating Assimp::Exporter ...\n"; Assimp::Exporter assimp_exporter = Assimp::Exporter(); std::cout << "Exporting to " << out_file << " ...\n"; const aiReturn export_ai_return = assimp_exporter.Export(&ai_scene, out_file_format, out_file); if (export_ai_return == aiReturn_SUCCESS) { std::cout << "Export to " << out_file << " successful.\n"; } else if (export_ai_return == aiReturn_FAILURE) { std::cerr << "ERROR: Export to " << out_file << " failed.\n"; } else if (export_ai_return == aiReturn_OUTOFMEMORY) { std::cerr << "ERROR: Export to " << out_file << " failed: out of memory.\n"; } else if (export_ai_return == _AI_ENFORCE_ENUM_SIZE) { std::cerr << "ERROR: Export to " << out_file << " failed: _AI_ENFORCE_ENUM_SIZE.\n"; } else { std::cerr << "ERROR: Export to " << out_file << " failed: unknown error.\n"; } } <commit_msg>`yli_convert`: cleaning up code.<commit_after>#include "code/ylikuutio/ontology/symbiosis.hpp" #include "code/ylikuutio/ontology/symbiont_species.hpp" #include "code/ylikuutio/ontology/symbiosis_struct.hpp" #include "code/ylikuutio/command_line/command_line_master.hpp" #include "code/ylikuutio/string/ylikuutio_string.hpp" #include "assimp/scene.h" #include "assimp/Exporter.hpp" #include "assimp/types.h" #define SDL_main main #include "SDL.h" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <algorithm> // std::transform #include <cstddef> // std::size_t #include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS #include <iostream> // std::cout, std::cin, std::cerr #include <limits> // std::numeric_limits #include <string> // std::string #include <vector> // std::vector // `yli_convert` is a command-line tool to load and export 3D data between different formats. // // parameters: // required: // `--in=foo` load 3D data from file `foo`. // `--in foo` load 3D data from file `foo`. // `--out=bar` export 3D data into file `bar`. // `--out bar` export 3D data into file `bar`. // // optional: // `--informat=baz` assume file format `baz` (if `--informat` is left out, file format is deduced from the filename extension). // `--informat baz` assume file format `baz` (if `--informat` is left out, file format is deduced from the filename extension). // `--outformat=qux` export 3D data into file `qux` (if `--outformat` is left out, file format is deduced from the filename extension). // `--outformat qux` export 3D data into file `qux` (if `--outformat` is left out, file format is deduced from the filename extension). // `--intexture=quux` use texture data into file `quux` as the material for all meshes (eg. `.obj` input file). // `--intexture quux` use texture data into file `quux` as the material for all meshes (eg. `.obj` input file). namespace yli { namespace ontology { class Universe; } } int main(const int argc, const char* argv[]) { yli::command_line::CommandLineMaster command_line_master(argc, argv); command_line_master.print_keys_and_values(); if (!command_line_master.is_key("in")) { std::cerr << "ERROR: --in parameter is required!\n\nexample:\n\nyli_convert --in=foo --out=bar\n"; exit(EXIT_FAILURE); } if (!command_line_master.is_key("out")) { std::cerr << "ERROR: --out parameter is required!\n\nexample:\n\nyli_convert --in=foo --out=bar\n"; exit(EXIT_FAILURE); } const std::string& in_file = command_line_master.get_value("in"); const std::string& out_file = command_line_master.get_value("out"); std::string in_file_format = ""; // dummy value. if (command_line_master.is_key("informat")) { in_file_format = command_line_master.get_value("informat"); } else { const char separator = '.'; yli::string::extract_last_part_of_string(in_file, in_file_format, separator); } if (in_file_format.empty()) { std::cerr << "ERROR: --informat is empty!\n"; exit(EXIT_FAILURE); } std::cout << "in file format is " << in_file_format << "\n"; std::string out_file_format = ""; // dummy value. if (command_line_master.is_key("outformat")) { out_file_format = command_line_master.get_value("outformat"); } else { const char separator = '.'; yli::string::extract_last_part_of_string(out_file, out_file_format, separator); } if (out_file_format.empty()) { std::cerr << "ERROR: --outformat is empty!\n"; exit(EXIT_FAILURE); } std::cout << "out file format is " << out_file_format << "\n"; // OK, all required input is given in the correct format. // convert in file format & out file format into lowercase. std::transform(in_file_format.begin(), in_file_format.end(), in_file_format.begin(), ::tolower); std::transform(out_file_format.begin(), out_file_format.end(), out_file_format.begin(), ::tolower); if (in_file_format != "obj" && in_file_format != "fbx") { std::cerr << "ERROR: unsupported in file format: " << in_file_format << "\n"; exit(EXIT_FAILURE); } // Always load the 3D object into a `yli::ontology::Symbiosis`. SymbiosisStruct symbiosis_struct; symbiosis_struct.model_filename = in_file; symbiosis_struct.model_file_format = in_file_format; symbiosis_struct.triangulation_type = "bilinear_interpolation"; symbiosis_struct.parent = nullptr; // no parent. symbiosis_struct.vram_buffer_in_use = false; // do not use VRAM buffer. yli::ontology::Universe* const universe = nullptr; const yli::ontology::Symbiosis symbiosis = yli::ontology::Symbiosis(universe, symbiosis_struct); // Assimp usage example: // https://github.com/assimp/assimp/issues/203 aiScene ai_scene; ai_scene.mRootNode = new aiNode(); ai_scene.mNumMaterials = symbiosis.get_number_of_symbiont_materials(); ai_scene.mMaterials = new aiMaterial*[ai_scene.mNumMaterials]; ai_scene.mNumAnimations = 0; // yli_convert does not yet support animations. ai_scene.mAnimations = nullptr; // yli_convert does not yet support animations. ai_scene.mNumTextures = symbiosis.get_number_of_symbiont_materials(); ai_scene.mTextures = new aiTexture*[ai_scene.mNumMaterials]; ai_scene.mNumLights = 0; // yli_convert does not yet support lights. ai_scene.mLights = nullptr; // yli_convert does not yet support lights. ai_scene.mNumCameras = 0; // yli_convert does not yet support cameras. ai_scene.mCameras = nullptr; // yli_convert does not yet support cameras. ai_scene.mMetaData = nullptr; // yli_convert does not yet support metadata. ai_scene.mNumMeshes = symbiosis.get_number_of_symbiont_species(); ai_scene.mMeshes = new aiMesh*[ai_scene.mNumMeshes]; ai_scene.mRootNode->mNumMeshes = symbiosis.get_number_of_symbiont_species(); ai_scene.mRootNode->mMeshes = new unsigned int[symbiosis.get_number_of_symbiont_species()]; std::cout << "Number of `SymbiontMaterial`s: " << symbiosis.get_number_of_symbiont_materials() << "\n"; for (std::size_t symbiont_material_i = 0; symbiont_material_i < symbiosis.get_number_of_symbiont_materials(); symbiont_material_i++) { std::cout << "Processing `SymbiontMaterial` " << symbiont_material_i << "\n"; const yli::ontology::SymbiontMaterial* const symbiont_material = symbiosis.get_symbiont_material(symbiont_material_i); ai_scene.mMaterials[symbiont_material_i] = new aiMaterial(); ai_scene.mTextures[symbiont_material_i] = new aiTexture(); if (symbiont_material == nullptr) { std::cerr << "ERROR: `yli_convert`: `symbiont_material` is `nullptr`!\n"; continue; } ai_scene.mTextures[symbiont_material_i]->mWidth = static_cast<unsigned int>(symbiont_material->get_image_width()); ai_scene.mTextures[symbiont_material_i]->mHeight = static_cast<unsigned int>(symbiont_material->get_image_height()); if (symbiont_material->get_childID() == std::numeric_limits<std::size_t>::max()) { // childID is the default (invalid) value, not a real childID! std::cerr << "ERROR: `yli_convert`: `childID` is `std::numeric_limits<std::size_t>::max()`!\n"; continue; } } for (std::size_t symbiont_species_i = 0; symbiont_species_i < symbiosis.get_number_of_symbiont_species(); symbiont_species_i++) { ai_scene.mRootNode->mMeshes[symbiont_species_i] = symbiont_species_i; ai_scene.mMeshes[symbiont_species_i] = new aiMesh(); const yli::ontology::SymbiontSpecies* const symbiont_species = symbiosis.get_symbiont_species(symbiont_species_i); if (symbiont_species == nullptr) { std::cerr << "ERROR: `yli_convert`: `symbiont_species` is `nullptr`!\n"; continue; } const yli::ontology::SymbiontMaterial* const symbiont_material = static_cast<yli::ontology::SymbiontMaterial*>(symbiont_species->get_parent()); if (symbiont_material == nullptr) { std::cerr << "ERROR: `yli_convert`: `symbiont_material` is `nullptr`!\n"; continue; } ai_scene.mMeshes[symbiont_species_i]->mMaterialIndex = symbiont_material->get_childID(); const std::vector<glm::vec3>& vertices = symbiont_species->get_vertices(); const std::vector<glm::vec3>& normals = symbiont_species->get_normals(); const std::vector<glm::vec2>& uvs = symbiont_species->get_uvs(); const std::size_t number_of_vertices = vertices.size(); ai_scene.mMeshes[symbiont_species_i]->mNumVertices = number_of_vertices; ai_scene.mMeshes[symbiont_species_i]->mVertices = new aiVector3D[number_of_vertices]; ai_scene.mMeshes[symbiont_species_i]->mNormals = new aiVector3D[number_of_vertices]; ai_scene.mMeshes[symbiont_species_i]->mTextureCoords[0] = new aiVector3D[number_of_vertices]; ai_scene.mMeshes[symbiont_species_i]->mNumUVComponents[0] = number_of_vertices; for (std::size_t vertex_i = 0; vertex_i < number_of_vertices; vertex_i++) { ai_scene.mMeshes[symbiont_species_i]->mVertices[vertex_i] = aiVector3D(vertices[vertex_i].x, vertices[vertex_i].y, vertices[vertex_i].z); ai_scene.mMeshes[symbiont_species_i]->mNormals[vertex_i] = aiVector3D(normals[vertex_i].x, normals[vertex_i].y, normals[vertex_i].z); ai_scene.mMeshes[symbiont_species_i]->mTextureCoords[0][vertex_i] = aiVector3D(uvs[vertex_i].x, uvs[vertex_i].y, 0); } const std::size_t number_of_faces = number_of_vertices / 3; std::cout << "Number of faces: " << number_of_faces << "\n"; ai_scene.mMeshes[symbiont_species_i]->mFaces = new aiFace[number_of_faces]; ai_scene.mMeshes[symbiont_species_i]->mNumFaces = number_of_faces; for (std::size_t face_i = 0; face_i < number_of_faces; face_i++) { ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices = new unsigned int[3]; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mNumIndices = 3; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices[0] = 3 * face_i; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices[1] = 3 * face_i + 1; ai_scene.mMeshes[symbiont_species_i]->mFaces[face_i].mIndices[2] = 3 * face_i + 2; } } std::cout << "Creating Assimp::Exporter ...\n"; Assimp::Exporter assimp_exporter = Assimp::Exporter(); std::cout << "Exporting to " << out_file << " ...\n"; const aiReturn export_ai_return = assimp_exporter.Export(&ai_scene, out_file_format, out_file); if (export_ai_return == aiReturn_SUCCESS) { std::cout << "Export to " << out_file << " successful.\n"; } else if (export_ai_return == aiReturn_FAILURE) { std::cerr << "ERROR: Export to " << out_file << " failed.\n"; } else if (export_ai_return == aiReturn_OUTOFMEMORY) { std::cerr << "ERROR: Export to " << out_file << " failed: out of memory.\n"; } else if (export_ai_return == _AI_ENFORCE_ENUM_SIZE) { std::cerr << "ERROR: Export to " << out_file << " failed: _AI_ENFORCE_ENUM_SIZE.\n"; } else { std::cerr << "ERROR: Export to " << out_file << " failed: unknown error.\n"; } } <|endoftext|>
<commit_before>#ifndef _w32_mt_hpp__ #define _w32_mt_hpp__ // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "__configure__.hpp" namespace w32 { namespace mt {} } /*! * @defgroup w32-mt Multi-threading services. * * This group contains services for implementation of programs based on * multi-threading for efficient use of multi-processor architectures. It * contains facilities for starting and controlling threads, as well as * synchronization primitives. */ #include <w32.mt/AutoResetEvent.hpp> #include <w32.mt/CriticalSection.hpp> #include <w32.mt/ManualResetEvent.hpp> #include <w32.mt/Mutex.hpp> #include <w32.mt/Semaphore.hpp> #include <w32.mt/Thread.hpp> #include <w32.mt/ThreadLocalPointer.hpp> #if (_WIN32_WINNT >= 0x600) # include <w32.mt/ConditionVariable.hpp> # include <w32.mt/ReadWriteLock.hpp> #endif #include <w32.mt/increment.hpp> #include <w32.mt/decrement.hpp> #endif /* _w32_mt_hpp__ */ <commit_msg>Exports all w32::mt symbols.<commit_after>#ifndef _w32_mt_hpp__ #define _w32_mt_hpp__ // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "__configure__.hpp" namespace w32 { namespace mt {} } /*! * @defgroup w32-mt Multi-threading services. * * This group contains services for implementation of programs based on * multi-threading for efficient use of multi-processor architectures. It * contains facilities for starting and controlling threads, as well as * synchronization primitives. */ #include <w32.mt/AutoResetEvent.hpp> #include <w32.mt/CriticalSection.hpp> #include <w32.mt/ManualResetEvent.hpp> #include <w32.mt/Mutex.hpp> #include <w32.mt/Semaphore.hpp> #include <w32.mt/Timer.hpp> #include <w32.mt/Thread.hpp> #include <w32.mt/ThreadLocalPointer.hpp> #if (_WIN32_WINNT >= 0x600) # include <w32.mt/ConditionVariable.hpp> # include <w32.mt/ReadWriteLock.hpp> #endif #include <w32.mt/and.hpp> #include <w32.mt/atomic.hpp> #include <w32.mt/barrier.hpp> #include <w32.mt/compare-exchange.hpp> #include <w32.mt/decrement.hpp> #include <w32.mt/exchange.hpp> #include <w32.mt/increment.hpp> #include <w32.mt/or.hpp> #include <w32.mt/xor.hpp> #endif /* _w32_mt_hpp__ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2015, University Corporation for Atmospheric Research * 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. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdio> #include <cstdlib> #include <vector> #include <map> #include <set> #include <iostream> #include <fstream> #include <cstring> #include <cstring> #include <stdint.h> #include <sys/types.h> #include <sys/dir.h> #include <sys/stat.h> #include <fcntl.h> #include <sstream> #include <signal.h> #include <syslog.h> #include <sys/time.h> #include <sys/resource.h> #include <errno.h> #include <libcgroup.h> #include <cgroup_context.h> #include <log.h> typedef uint64_t memory_t; void enumerate_tasks(char* cgpath, uid_t victim, std::vector<pid_t>& cached_task_list); uid_t get_uid(pid_t pid) { char* status_path; asprintf(&status_path, "/proc/%d/status", pid); std::ifstream pid_status(status_path); std::string line; uid_t uid; char found = 0; while(pid_status.good()) { std::getline(pid_status, line); size_t pos = line.find("Uid:",0); std::string token; if(pos != std::string::npos) { std::stringstream ls(line,std::ios_base::in); ls >> token; //header ls >> uid; found = 1; break; } } if(!found) { slog(LOG_ERR,"Error mapping UID for PID %d\n", pid); } pid_status.close(); free(status_path); return(uid); } memory_t get_rss(pid_t pid) { char* status_path; asprintf(&status_path, "/proc/%d/status", pid); std::ifstream pid_status(status_path); std::string line; uint64_t rss; char found = 0; while(pid_status.good()) { std::getline(pid_status, line); size_t pos = line.find("VmRSS:",0); std::string token; if(pos != std::string::npos) { std::stringstream ls(line,std::ios_base::in); ls >> token; //header ls >> rss; //FIXME assumes always kB, which is currently correct //but could change found = 1; break; } } //if(!found) //ignore this case for now - due to races, it's fairly common //{ // //note: this can happen for kthreads // slog(LOG_WARNING,"Error finding RSS for PID %d\n", pid); //} pid_status.close(); free(status_path); return(rss); } extern "C" { char is_oom(struct cgroup_context* cgc) { char* path; asprintf(&path, "/%s/%s/memory.oom_control", cgc->cgroup_path, cgc->cgroup_name); std::ifstream oc(path, std::ifstream::in); char isoom = -1; while(oc.good()) { std::string token; oc >> token; if(token == "under_oom") { oc >> isoom; } } oc.close(); free(path); if(isoom == -1) abort(); if(isoom) return(1); return(0); } } void get_cgroup_from_pid(pid_t pid, std::string& result) { char* path; asprintf(&path, "/proc/%d/cgroup", pid); std::ifstream gcl(path, std::ifstream::in); while(gcl.good()) { std::string token; gcl >> token; size_t delim = 0; delim = token.find_first_of(':'); token.erase(0, delim); if(token.find("memory:/") != std::string::npos) { delim = token.find_first_of(':'); if((delim+1) > token.length()) { result.append("/;"); } else { result.append(token.substr(delim+1)); result.append(";"); } } } gcl.close(); free(path); } void sigkill_victim(pid_t pid) { uid_t victim_uid; std::string cgroups; char* log_msg; victim_uid = get_uid(pid); get_cgroup_from_pid(pid, cgroups); asprintf(&log_msg, "killing UID:%u PID %d; cgroups: %s\n", victim_uid, pid, cgroups.c_str() ); slog(LOG_ALERT, log_msg); free(log_msg); kill(pid, SIGKILL); } void kill_victim(struct cgroup_context* cgc, uid_t victim_uid) { std::vector<pid_t> cached_task_list; //get PID list char* cgpath; asprintf(&cgpath, "/%s/%s/", cgc->cgroup_path, cgc->cgroup_name); enumerate_tasks(cgpath, victim_uid, cached_task_list); free(cgpath); struct rlimit core_limit; core_limit.rlim_cur = 0; core_limit.rlim_max = 0; //Freeze all of user's processes for(std::vector<pid_t>::iterator i = cached_task_list.begin(); i!= cached_task_list.end(); i++) { cgroup_attach_task_pid(cgc->purgatory, *i); } char* root_freezer_path; char* root_memory_path; asprintf(&root_freezer_path, "/%s/tasks", cgc->freezer_path); asprintf(&root_memory_path, "/%s/tasks", cgc->cgroup_path); for(std::vector<pid_t>::iterator i = cached_task_list.begin(); i!= cached_task_list.end(); i++) { FILE* root_freezer = fopen(root_freezer_path,"w"); FILE* root_memory = fopen(root_memory_path, "w"); sigkill_victim(*i); fprintf(root_memory, "%d", *i); fclose(root_memory); fprintf(root_freezer, "%d", *i); fclose(root_freezer); } free(root_memory_path); free(root_freezer_path); } void enumerate_tasks(char* cgpath, uid_t victim_uid, std::vector<pid_t>& cached_task_list) { pid_t pid; char* task_path; asprintf(&task_path, "/%s/tasks", cgpath); std::ifstream task_list(task_path,std::ifstream::in); while(task_list.good()) { task_list >> pid; if(!(task_list.good())) //last read seems to be garbage { break; } uid_t uid = get_uid(pid); if(uid == victim_uid) { cached_task_list.push_back(pid); } } task_list.close(); free(task_path); DIR* cgd = opendir(cgpath); if(cgd == NULL) slog(LOG_ALERT, "Error opening cgroup directory: %s\n", cgpath); struct dirent* de; struct stat stat_buf; int r; while((de=readdir(cgd))!=NULL) { char* tmp_path; asprintf(&tmp_path, "%s/%s/", cgpath, de->d_name); r = stat(tmp_path, &stat_buf); if(r!=0) { if(errno != ENOTDIR) { slog(LOG_ALERT, "enumerate_tasks(): stat() error code: %s on \"%s\"", strerror(errno), tmp_path); } } else { if(S_ISDIR(stat_buf.st_mode) && de->d_name[0]!='.') { enumerate_tasks(tmp_path, victim_uid, cached_task_list); } } free(tmp_path); } closedir(cgd); } void enumerate_users(char* cgpath, std::map<uid_t, memory_t>& user_list) { char* task_path; asprintf(&task_path, "/%s/tasks", cgpath); std::ifstream task_list(task_path,std::ifstream::in); pid_t pid; while(task_list.good()) { task_list >> pid; if(!(task_list.good())) //last read seems to be garbage { break; } uid_t uid = get_uid(pid); memory_t rss = get_rss(pid); if(user_list.find(uid)==user_list.end()) { user_list[uid] = rss; } else { user_list[uid] = user_list[uid] + rss; } } task_list.close(); free(task_path); DIR* cgd = opendir(cgpath); if(cgd == NULL) slog(LOG_ALERT, "Error opening cgroup directory: %s\n", cgpath); struct dirent* de; struct stat stat_buf; int r; while((de=readdir(cgd))!=NULL) { char* tmp_path; asprintf(&tmp_path, "%s/%s/", cgpath, de->d_name); r = stat(tmp_path, &stat_buf); if(r!=0) { if(errno != ENOTDIR) { slog(LOG_ALERT, "enumerate_users(): stat() error code: %s on \"%s\"", strerror(errno), tmp_path); } } else { if(S_ISDIR(stat_buf.st_mode) && de->d_name[0]!='.') { enumerate_users(tmp_path, user_list); } } free(tmp_path); } closedir(cgd); } extern "C" { int find_victim(struct cgroup_context* cgc) { std::map<uid_t,memory_t> user_list; char* cgpath; asprintf(&cgpath, "/%s/%s/", cgc->cgroup_path, cgc->cgroup_name); enumerate_users(cgpath, user_list); free(cgpath); if(user_list.size() < 1) { return(-1); } memory_t max = (user_list.begin())->second; uid_t max_uid = (user_list.begin())->first; for(std::map<uid_t,memory_t>::iterator i = user_list.begin(); i!=user_list.end(); i++) { if(i->second > max) { max_uid = i->first; max = i->second; } } kill_victim(cgc, max_uid); return(0); } } <commit_msg>catch exception<commit_after>/* * Copyright (c) 2015, University Corporation for Atmospheric Research * 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. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdio> #include <cstdlib> #include <vector> #include <map> #include <set> #include <iostream> #include <fstream> #include <cstring> #include <cstring> #include <stdint.h> #include <sys/types.h> #include <sys/dir.h> #include <sys/stat.h> #include <fcntl.h> #include <sstream> #include <signal.h> #include <syslog.h> #include <sys/time.h> #include <sys/resource.h> #include <errno.h> #include <exception> #include <libcgroup.h> #include <cgroup_context.h> #include <log.h> typedef uint64_t memory_t; void enumerate_tasks(char* cgpath, uid_t victim, std::vector<pid_t>& cached_task_list); uid_t get_uid(pid_t pid) { char* status_path; asprintf(&status_path, "/proc/%d/status", pid); std::ifstream pid_status(status_path); std::string line; uid_t uid; char found = 0; while(pid_status.good()) { std::getline(pid_status, line); size_t pos = line.find("Uid:",0); std::string token; if(pos != std::string::npos) { std::stringstream ls(line,std::ios_base::in); ls >> token; //header ls >> uid; found = 1; break; } } if(!found) { slog(LOG_ERR,"Error mapping UID for PID %d\n", pid); } pid_status.close(); free(status_path); return(uid); } memory_t get_rss(pid_t pid) { char* status_path; asprintf(&status_path, "/proc/%d/status", pid); std::ifstream pid_status(status_path); std::string line; uint64_t rss; char found = 0; while(pid_status.good()) { std::getline(pid_status, line); size_t pos = line.find("VmRSS:",0); std::string token; if(pos != std::string::npos) { std::stringstream ls(line,std::ios_base::in); ls >> token; //header ls >> rss; //FIXME assumes always kB, which is currently correct //but could change found = 1; break; } } //if(!found) //ignore this case for now - due to races, it's fairly common //{ // //note: this can happen for kthreads // slog(LOG_WARNING,"Error finding RSS for PID %d\n", pid); //} pid_status.close(); free(status_path); return(rss); } extern "C" { char is_oom(struct cgroup_context* cgc) { char* path; asprintf(&path, "/%s/%s/memory.oom_control", cgc->cgroup_path, cgc->cgroup_name); std::ifstream oc(path, std::ifstream::in); char isoom = -1; while(oc.good()) { std::string token; oc >> token; if(token == "under_oom") { oc >> isoom; } } oc.close(); free(path); if(isoom == -1) abort(); if(isoom) return(1); return(0); } } void get_cgroup_from_pid(pid_t pid, std::string& result) { char* path; asprintf(&path, "/proc/%d/cgroup", pid); std::ifstream gcl(path, std::ifstream::in); try { while(gcl.good()) { std::string token; gcl >> token; size_t delim = 0; delim = token.find_first_of(':'); token.erase(0, delim); if(token.find("memory:/") != std::string::npos) { delim = token.find_first_of(':'); if((delim+1) > token.length()) { result.append("/;"); } else { result.append(token.substr(delim+1)); result.append(";"); } } } gcl.close(); } catch (std::exception& e) { //This shouldn't really ever happen //see gcc bug 53984 slog(LOG_ALERT, "Unexpected Exception reading cgroup file\n"); result.append(e.what()); } free(path); } void sigkill_victim(pid_t pid) { uid_t victim_uid; std::string cgroups; char* log_msg; victim_uid = get_uid(pid); get_cgroup_from_pid(pid, cgroups); asprintf(&log_msg, "killing UID:%u PID %d; cgroups: %s\n", victim_uid, pid, cgroups.c_str() ); slog(LOG_ALERT, log_msg); free(log_msg); kill(pid, SIGKILL); } void kill_victim(struct cgroup_context* cgc, uid_t victim_uid) { std::vector<pid_t> cached_task_list; //get PID list char* cgpath; asprintf(&cgpath, "/%s/%s/", cgc->cgroup_path, cgc->cgroup_name); enumerate_tasks(cgpath, victim_uid, cached_task_list); free(cgpath); struct rlimit core_limit; core_limit.rlim_cur = 0; core_limit.rlim_max = 0; //Freeze all of user's processes for(std::vector<pid_t>::iterator i = cached_task_list.begin(); i!= cached_task_list.end(); i++) { cgroup_attach_task_pid(cgc->purgatory, *i); } char* root_freezer_path; char* root_memory_path; asprintf(&root_freezer_path, "/%s/tasks", cgc->freezer_path); asprintf(&root_memory_path, "/%s/tasks", cgc->cgroup_path); for(std::vector<pid_t>::iterator i = cached_task_list.begin(); i!= cached_task_list.end(); i++) { FILE* root_freezer = fopen(root_freezer_path,"w"); FILE* root_memory = fopen(root_memory_path, "w"); sigkill_victim(*i); fprintf(root_memory, "%d", *i); fclose(root_memory); fprintf(root_freezer, "%d", *i); fclose(root_freezer); } free(root_memory_path); free(root_freezer_path); } void enumerate_tasks(char* cgpath, uid_t victim_uid, std::vector<pid_t>& cached_task_list) { pid_t pid; char* task_path; asprintf(&task_path, "/%s/tasks", cgpath); std::ifstream task_list(task_path,std::ifstream::in); while(task_list.good()) { task_list >> pid; if(!(task_list.good())) //last read seems to be garbage { break; } uid_t uid = get_uid(pid); if(uid == victim_uid) { cached_task_list.push_back(pid); } } task_list.close(); free(task_path); DIR* cgd = opendir(cgpath); if(cgd == NULL) slog(LOG_ALERT, "Error opening cgroup directory: %s\n", cgpath); struct dirent* de; struct stat stat_buf; int r; while((de=readdir(cgd))!=NULL) { char* tmp_path; asprintf(&tmp_path, "%s/%s/", cgpath, de->d_name); r = stat(tmp_path, &stat_buf); if(r!=0) { if(errno != ENOTDIR) { slog(LOG_ALERT, "enumerate_tasks(): stat() error code: %s on \"%s\"", strerror(errno), tmp_path); } } else { if(S_ISDIR(stat_buf.st_mode) && de->d_name[0]!='.') { enumerate_tasks(tmp_path, victim_uid, cached_task_list); } } free(tmp_path); } closedir(cgd); } void enumerate_users(char* cgpath, std::map<uid_t, memory_t>& user_list) { char* task_path; asprintf(&task_path, "/%s/tasks", cgpath); std::ifstream task_list(task_path,std::ifstream::in); pid_t pid; while(task_list.good()) { task_list >> pid; if(!(task_list.good())) //last read seems to be garbage { break; } uid_t uid = get_uid(pid); memory_t rss = get_rss(pid); if(user_list.find(uid)==user_list.end()) { user_list[uid] = rss; } else { user_list[uid] = user_list[uid] + rss; } } task_list.close(); free(task_path); DIR* cgd = opendir(cgpath); if(cgd == NULL) slog(LOG_ALERT, "Error opening cgroup directory: %s\n", cgpath); struct dirent* de; struct stat stat_buf; int r; while((de=readdir(cgd))!=NULL) { char* tmp_path; asprintf(&tmp_path, "%s/%s/", cgpath, de->d_name); r = stat(tmp_path, &stat_buf); if(r!=0) { if(errno != ENOTDIR) { slog(LOG_ALERT, "enumerate_users(): stat() error code: %s on \"%s\"", strerror(errno), tmp_path); } } else { if(S_ISDIR(stat_buf.st_mode) && de->d_name[0]!='.') { enumerate_users(tmp_path, user_list); } } free(tmp_path); } closedir(cgd); } extern "C" { int find_victim(struct cgroup_context* cgc) { std::map<uid_t,memory_t> user_list; char* cgpath; asprintf(&cgpath, "/%s/%s/", cgc->cgroup_path, cgc->cgroup_name); enumerate_users(cgpath, user_list); free(cgpath); if(user_list.size() < 1) { return(-1); } memory_t max = (user_list.begin())->second; uid_t max_uid = (user_list.begin())->first; for(std::map<uid_t,memory_t>::iterator i = user_list.begin(); i!=user_list.end(); i++) { if(i->second > max) { max_uid = i->first; max = i->second; } } kill_victim(cgc, max_uid); return(0); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2018 Airbus Defence and Space and RISC Software GmbH * * 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 "CCPACSFrame.h" #include <gp_Pnt.hxx> #include <gp_Pln.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <ShapeExtend_WireData.hxx> #include <ShapeFix_Wire.hxx> #include <BRepAlgoAPI_Section.hxx> #include "tiglcommonfunctions.h" #include "CNamedShape.h" #include "CCPACSFuselageSegment.h" #include "CCPACSProfileBasedStructuralElement.h" #include "CCPACSFuselageStringerFramePosition.h" #include "CCPACSCrossBeamAssemblyPosition.h" #include "CCPACSCrossBeamStrutAssemblyPosition.h" #include "CCPACSFuselageStringer.h" namespace tigl { CCPACSFrame::CCPACSFrame(CCPACSFramesAssembly* parent, CTiglUIDManager* uidMgr) : generated::CPACSFrame(parent, uidMgr) { } void CCPACSFrame::Invalidate() { for (int i = 0; i < 2; ++i) { m_geomCache[i] = boost::none; } } TopoDS_Shape CCPACSFrame::GetGeometry(bool just1DElements, TiglCoordinateSystem cs) { if (!m_geomCache[just1DElements]) BuildGeometry(just1DElements); const TopoDS_Shape shape = m_geomCache[just1DElements].value(); if (cs == GLOBAL_COORDINATE_SYSTEM) { CTiglTransformation trafo = m_parent->GetParent()->GetParent()->GetTransformationMatrix(); return trafo.Transform(shape); } else return shape; } void CCPACSFrame::BuildGeometry(bool just1DElements) { if (m_framePositions.empty()) throw CTiglError("Cannot build frame geometry, no frame positions defined in XML", TIGL_XML_ERROR); // this function build the frame in 2 steps : // 1) path definition (projection on the fuselage) // 2) if not just 1D element, build and sweep the profile all along the path CCPACSFuselage& fuselage = *m_parent->GetParent()->GetParent(); const TopoDS_Shape fuselageLoft = fuselage.GetLoft()->Shape(); // initialize object needed for the frame build gp_Pln profilePlane; TopoDS_Wire path; if (m_framePositions.size() == 1) { // if there is 1 position ==> the path is around the fuselage, in an X normal orientated plane const CCPACSFuselageStringerFramePosition& fp = *m_framePositions[0]; TopoDS_Shape section = BRepAlgoAPI_Section(fuselageLoft, gp_Pln(fp.GetRefPoint(), gp_Dir(1, 0, 0))).Shape(); path = BuildWireFromEdges(section); if (!just1DElements) { // -1) place the point and the plane (X Axis as normal vector) const gp_Lin iAxe = fuselage.Intersection(fp); const gp_Ax1 xAxe(iAxe.Location(), gp_Dir(1, 0, 0)); // parallel to x Axis => used to rotate the profile plane profilePlane = gp_Pln(gp_Ax3(iAxe.Location(), iAxe.Rotated(xAxe, M_PI / 2.).Direction(), gp_Dir(1, 0, 0))); } } else { // if there is more than 1 position ==> the path is projected segment by segment on the fuselage // create a frame in the fuselage, following the path described by all the positions in frame/frameposition[] // place every point on the fuselage loft std::vector<gp_Lin> pointList; for (size_t i = 0; i < m_framePositions.size(); i++) pointList.push_back(fuselage.Intersection(*m_framePositions[i])); // with a ShapeExtend_WireData, the individual segment orientation is not crucial during the wire building Handle(ShapeExtend_WireData) wirePath = new ShapeExtend_WireData; for (size_t i = 0; i < pointList.size() - 1; i++) { const gp_Pnt intersection0 = pointList.at(i + 0).Location(); const gp_Pnt intersection1 = pointList.at(i + 1).Location(); const gp_Pnt refPoint0 = m_framePositions[i + 0]->GetRefPoint(); const gp_Pnt refPoint1 = m_framePositions[i + 1]->GetRefPoint(); const double refAngle0 = m_framePositions[i + 0]->GetReferenceAngle(); const double refAngle1 = m_framePositions[i + 1]->GetReferenceAngle(); // first, we cut the initial segment in 2 parts const gp_Pnt midIntersection = fuselage.Intersection((refPoint0.XYZ() + refPoint1.XYZ()) / 2, Radians((refAngle0 + refAngle1) / 2.)).Location(); const gp_Pnt midRefPoint0 = (refPoint0.XYZ() * 0.25 + refPoint1.XYZ() * 0.75); const gp_Pnt midRefPoint1 = (refPoint0.XYZ() * 0.75 + refPoint1.XYZ() * 0.25); // third, we project the sub-segment on the fuselage, according to the projections points, // and add it to the path add the current part in the path builder wirePath->Add(fuselage.projectConic(BRepBuilderAPI_MakeEdge(intersection0, midIntersection).Edge(), midRefPoint0)); wirePath->Add(fuselage.projectConic(BRepBuilderAPI_MakeEdge(midIntersection, intersection1).Edge(), midRefPoint1)); } // finally, we can create the path with all the projection obtained // TODO : throw exception if the frame's path creation fail // the ShapeFix_Wire classe will create a proper wire (direction, order) with all the data in the ShapeExtend_WireData ShapeFix_Wire fixWire; fixWire.Load(wirePath); fixWire.Perform(); fixWire.FixReorder(); fixWire.FixConnected(); path = fixWire.WireAPIMake(); path.Orientation(TopAbs_FORWARD); if (!just1DElements) { // creation of the profile plane // the plan axis system is defined by : the location, the normal vector, the x vector. It's a right-handed system // the rotation is necessary to have a normal vector tangent to the fuselage const gp_Ax1 xAxe(pointList.at(0).Location(), gp_Dir(1, 0, 0)); // parallel to x Axis => used to rotate the profile plane profilePlane = gp_Pln(gp_Ax3(pointList.at(0).Location(), pointList.at(0).Rotated(xAxe, M_PI / 2.).Direction(), gp_Dir(1, 0, 0))); } } if (just1DElements) { m_geomCache[true] = path; } else { const CCPACSProfileBasedStructuralElement& pbse = m_uidMgr->ResolveObject<CCPACSProfileBasedStructuralElement>( m_framePositions.front()->GetStructuralElementUID()); m_geomCache[false] = pbse.makeFromWire(path, profilePlane); } } } // namespace tigl <commit_msg>fixed coordinate system issue with single position frames<commit_after>/* * Copyright (c) 2018 Airbus Defence and Space and RISC Software GmbH * * 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 "CCPACSFrame.h" #include <gp_Pnt.hxx> #include <gp_Pln.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <ShapeExtend_WireData.hxx> #include <ShapeFix_Wire.hxx> #include <BRepAlgoAPI_Section.hxx> #include "tiglcommonfunctions.h" #include "CNamedShape.h" #include "CCPACSFuselageSegment.h" #include "CCPACSProfileBasedStructuralElement.h" #include "CCPACSFuselageStringerFramePosition.h" #include "CCPACSCrossBeamAssemblyPosition.h" #include "CCPACSCrossBeamStrutAssemblyPosition.h" #include "CCPACSFuselageStringer.h" namespace tigl { CCPACSFrame::CCPACSFrame(CCPACSFramesAssembly* parent, CTiglUIDManager* uidMgr) : generated::CPACSFrame(parent, uidMgr) { } void CCPACSFrame::Invalidate() { for (int i = 0; i < 2; ++i) { m_geomCache[i] = boost::none; } } TopoDS_Shape CCPACSFrame::GetGeometry(bool just1DElements, TiglCoordinateSystem cs) { if (!m_geomCache[just1DElements]) BuildGeometry(just1DElements); const TopoDS_Shape shape = m_geomCache[just1DElements].value(); if (cs == GLOBAL_COORDINATE_SYSTEM) { CTiglTransformation trafo = m_parent->GetParent()->GetParent()->GetTransformationMatrix(); return trafo.Transform(shape); } else return shape; } void CCPACSFrame::BuildGeometry(bool just1DElements) { if (m_framePositions.empty()) throw CTiglError("Cannot build frame geometry, no frame positions defined in XML", TIGL_XML_ERROR); // this function build the frame in 2 steps : // 1) path definition (projection on the fuselage) // 2) if not just 1D element, build and sweep the profile all along the path CCPACSFuselage& fuselage = *m_parent->GetParent()->GetParent(); // initialize object needed for the frame build gp_Pln profilePlane; TopoDS_Wire path; if (m_framePositions.size() == 1) { // if there is 1 position ==> the path is around the fuselage, in an X normal orientated plane const CCPACSFuselageStringerFramePosition& fp = *m_framePositions[0]; const TopoDS_Shape fuselageLoft = fuselage.GetLoft(FUSELAGE_COORDINATE_SYSTEM); const TopoDS_Shape section = BRepAlgoAPI_Section(fuselageLoft, gp_Pln(fp.GetRefPoint(), gp_Dir(1, 0, 0))).Shape(); path = BuildWireFromEdges(section); if (!just1DElements) { // -1) place the point and the plane (X Axis as normal vector) const gp_Lin iAxe = fuselage.Intersection(fp); const gp_Ax1 xAxe(iAxe.Location(), gp_Dir(1, 0, 0)); // parallel to x Axis => used to rotate the profile plane profilePlane = gp_Pln(gp_Ax3(iAxe.Location(), iAxe.Rotated(xAxe, M_PI / 2.).Direction(), gp_Dir(1, 0, 0))); } } else { // if there is more than 1 position ==> the path is projected segment by segment on the fuselage // create a frame in the fuselage, following the path described by all the positions in frame/frameposition[] // place every point on the fuselage loft std::vector<gp_Lin> pointList; for (size_t i = 0; i < m_framePositions.size(); i++) pointList.push_back(fuselage.Intersection(*m_framePositions[i])); // with a ShapeExtend_WireData, the individual segment orientation is not crucial during the wire building Handle(ShapeExtend_WireData) wirePath = new ShapeExtend_WireData; for (size_t i = 0; i < pointList.size() - 1; i++) { const gp_Pnt intersection0 = pointList.at(i + 0).Location(); const gp_Pnt intersection1 = pointList.at(i + 1).Location(); const gp_Pnt refPoint0 = m_framePositions[i + 0]->GetRefPoint(); const gp_Pnt refPoint1 = m_framePositions[i + 1]->GetRefPoint(); const double refAngle0 = m_framePositions[i + 0]->GetReferenceAngle(); const double refAngle1 = m_framePositions[i + 1]->GetReferenceAngle(); // first, we cut the initial segment in 2 parts const gp_Pnt midIntersection = fuselage.Intersection((refPoint0.XYZ() + refPoint1.XYZ()) / 2, Radians((refAngle0 + refAngle1) / 2.)).Location(); const gp_Pnt midRefPoint0 = (refPoint0.XYZ() * 0.25 + refPoint1.XYZ() * 0.75); const gp_Pnt midRefPoint1 = (refPoint0.XYZ() * 0.75 + refPoint1.XYZ() * 0.25); // third, we project the sub-segment on the fuselage, according to the projections points, // and add it to the path add the current part in the path builder wirePath->Add(fuselage.projectConic(BRepBuilderAPI_MakeEdge(intersection0, midIntersection).Edge(), midRefPoint0)); wirePath->Add(fuselage.projectConic(BRepBuilderAPI_MakeEdge(midIntersection, intersection1).Edge(), midRefPoint1)); } // finally, we can create the path with all the projection obtained // TODO : throw exception if the frame's path creation fail // the ShapeFix_Wire classe will create a proper wire (direction, order) with all the data in the ShapeExtend_WireData ShapeFix_Wire fixWire; fixWire.Load(wirePath); fixWire.Perform(); fixWire.FixReorder(); fixWire.FixConnected(); path = fixWire.WireAPIMake(); path.Orientation(TopAbs_FORWARD); if (!just1DElements) { // creation of the profile plane // the plan axis system is defined by : the location, the normal vector, the x vector. It's a right-handed system // the rotation is necessary to have a normal vector tangent to the fuselage const gp_Ax1 xAxe(pointList.at(0).Location(), gp_Dir(1, 0, 0)); // parallel to x Axis => used to rotate the profile plane profilePlane = gp_Pln(gp_Ax3(pointList.at(0).Location(), pointList.at(0).Rotated(xAxe, M_PI / 2.).Direction(), gp_Dir(1, 0, 0))); } } if (just1DElements) { m_geomCache[true] = path; } else { const CCPACSProfileBasedStructuralElement& pbse = m_uidMgr->ResolveObject<CCPACSProfileBasedStructuralElement>( m_framePositions.front()->GetStructuralElementUID()); m_geomCache[false] = pbse.makeFromWire(path, profilePlane); } } } // namespace tigl <|endoftext|>
<commit_before>#ifdef WIN32 #include <intrin.h> #include <windows.h> #endif #include "glresource.hpp" #include "event.hpp" namespace rs { namespace { bool g_bglfuncInit = false; } #define GLGETPROC(name) SDL_GL_GetProcAddress(BOOST_PP_STRINGIZE(name)) #if defined(_WIN32) namespace { using SetSwapInterval_t = bool APIENTRY (*)(int); SetSwapInterval_t g_setswapinterval = nullptr; } void LoadGLAux() { g_setswapinterval = (SetSwapInterval_t)GLGETPROC(wglSwapIntervalEXT); } #else namespace { using SetSwapInterval_t = void APIENTRY (*)(int); SetSwapInterval_t g_setswapinterval = nullptr; } void LoadGLAux() { // EXTかSGIのどちらかが存在する事を期待 try { g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalSGI); } catch(const std::runtime_error& e) { g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalEXT); } } #endif bool GLWrap::isGLFuncLoaded() { return g_bglfuncInit; } void IGL_Draw::setSwapInterval(int n) { g_setswapinterval(n); } void IGL_OtherSingle::setSwapInterval(int n) { GLW.getDrawHandler().postExec([=](){ IGL_Draw().setSwapInterval(n); }); } // OpenGL関数ロード // FuncNameで読み込めなければFuncNameARBとFuncNameEXTで試す #define GLDEFINE(...) #define DEF_GLMETHOD(ret_type, num, name, args, argnames) \ GLWrap::name = nullptr; \ GLWrap::name = (typename GLWrap::t_##name) GLGETPROC(name); \ if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,ARB)); \ if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,EXT)); \ Assert(Warn, GLWrap::name != nullptr, "could not load OpenGL function: %1%", #name) void GLWrap::loadGLFunc() { // 各種API関数 #ifndef ANDROID #ifdef ANDROID #include "android_gl.inc" #elif defined(WIN32) #include "mingw_gl.inc" #else #include "linux_gl.inc" #endif #endif // その他OS依存なAPI関数 LoadGLAux(); g_bglfuncInit = true; } #undef DEF_GLMETHOD #undef GLDEFINE // ---------------------- GLShader ---------------------- void GLShader::_initShader() { _idSh = GL.glCreateShader(_flag); std::string ss("#version 110\n"); ss.append(_source); const auto* pStr = ss.c_str(); GL.glShaderSource(_idSh, 1, &pStr, nullptr); GL.glCompileShader(_idSh); // エラーが無かったか確認 GLint compiled; GL.glGetShaderiv(_idSh, GL_COMPILE_STATUS, &compiled); AssertT(Trap, compiled==GL_TRUE, (GLE_ShaderError)(const std::string&)(GLuint), ss, _idSh) } GLShader::GLShader() {} GLShader::GLShader(GLuint flag, const std::string& src): _flag(flag), _source(src) { _initShader(); } GLShader::~GLShader() { onDeviceLost(); } bool GLShader::isEmpty() const { return _source.empty(); } int GLShader::getShaderID() const { return _idSh; } void GLShader::onDeviceLost() { if(_idSh!=0) { GL.glDeleteShader(_idSh); _idSh = 0; } } void GLShader::onDeviceReset() { if(!isEmpty() && _idSh==0) _initShader(); } // ---------------------- draw::Program ---------------------- namespace draw { Program::Program(HProg hProg): Token(hProg), _idProg(hProg.ref()->getProgramID()) {} Program::Program(Program&& p): Token(p), _idProg(p._idProg) {} void Program::exec() { GL.glUseProgram(_idProg); } } // ---------------------- GLProgram ---------------------- GLProgram::GLProgram(HSh vsh, HSh psh) { _shader[ShType::VERTEX] = vsh; _shader[ShType::PIXEL] = psh; _initProgram(); } GLProgram::GLProgram(HSh vsh, HSh gsh, HSh psh) { _shader[ShType::VERTEX] = vsh; _shader[ShType::PIXEL] = psh; _shader[ShType::GEOMETRY] = gsh; _initProgram(); } void GLProgram::_initProgram() { _idProg = GL.glCreateProgram(); for(int i=0 ; i<static_cast<int>(ShType::NUM_SHTYPE) ; i++) { auto& sh = _shader[i]; // Geometryシェーダー以外は必須 if(sh.valid()) { GL.glAttachShader(_idProg, sh.cref()->getShaderID()); GLEC_ChkP(Trap) } else { AssertT(Trap, i==ShType::GEOMETRY, (GLE_Error)(const char*), "missing shader elements (vertex or fragment)") } } GL.glLinkProgram(_idProg); // エラーが無いかチェック int ib; GL.glGetProgramiv(_idProg, GL_LINK_STATUS, &ib); AssertT(Trap, ib==GL_TRUE, (GLE_ProgramError)(GLuint), _idProg) } GLProgram::~GLProgram() { if(mgr_gl.isInDtor()) { for(auto& p : _shader) p.setNull(); } onDeviceLost(); } void GLProgram::onDeviceLost() { if(_idProg != 0) { // ShaderはProgramをDeleteすれば自動的にdetachされる GL.glDeleteProgram(_idProg); _idProg = 0; } } void GLProgram::onDeviceReset() { if(_idProg == 0) { // 先にshaderがresetされてないかもしれないので、ここでしておく for(auto& s : _shader) { if(s) s.cref()->onDeviceReset(); } _initProgram(); } } const HLSh& GLProgram::getShader(ShType type) const { return _shader[(int)type]; } int GLProgram::getUniformID(const std::string& name) const { GLint id = getUniformIDNc(name); AssertT(Trap, id>=0, (GLE_ParamNotFound)(const std::string&), name) return id; } int GLProgram::getUniformIDNc(const std::string& name) const { return GL.glGetUniformLocation(getProgramID(), name.c_str()); } int GLProgram::getAttribID(const std::string& name) const { GLint id = getAttribIDNc(name); AssertT(Trap, id>=0, (GLE_ParamNotFound)(const std::string&), name) return id; } GLuint GLProgram::getProgramID() const { return _idProg; } int GLProgram::getAttribIDNc(const std::string& name) const { return GL.glGetAttribLocation(getProgramID(), name.c_str()); } void GLProgram::use() const { GL.glUseProgram(getProgramID()); GLEC_ChkP(Trap) } } <commit_msg>androidでコンパイル時にAPIENTRYマクロの代わりにGL_APIENTRYを使用<commit_after>#ifdef WIN32 #include <intrin.h> #include <windows.h> #endif #include "glresource.hpp" #include "event.hpp" namespace rs { namespace { bool g_bglfuncInit = false; } #define GLGETPROC(name) SDL_GL_GetProcAddress(BOOST_PP_STRINGIZE(name)) #if defined(_WIN32) namespace { using SetSwapInterval_t = bool APIENTRY (*)(int); SetSwapInterval_t g_setswapinterval = nullptr; } void LoadGLAux() { g_setswapinterval = (SetSwapInterval_t)GLGETPROC(wglSwapIntervalEXT); } #else namespace { #ifdef __ANDROID__ using SetSwapInterval_t = void GL_APIENTRY (*)(int); #else using SetSwapInterval_t = void APIENTRY (*)(int); #endif SetSwapInterval_t g_setswapinterval = nullptr; } void LoadGLAux() { // EXTかSGIのどちらかが存在する事を期待 try { g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalSGI); } catch(const std::runtime_error& e) { g_setswapinterval = (SetSwapInterval_t)GLGETPROC(glXSwapIntervalEXT); } } #endif bool GLWrap::isGLFuncLoaded() { return g_bglfuncInit; } void IGL_Draw::setSwapInterval(int n) { g_setswapinterval(n); } void IGL_OtherSingle::setSwapInterval(int n) { GLW.getDrawHandler().postExec([=](){ IGL_Draw().setSwapInterval(n); }); } // OpenGL関数ロード // FuncNameで読み込めなければFuncNameARBとFuncNameEXTで試す #define GLDEFINE(...) #define DEF_GLMETHOD(ret_type, num, name, args, argnames) \ GLWrap::name = nullptr; \ GLWrap::name = (typename GLWrap::t_##name) GLGETPROC(name); \ if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,ARB)); \ if(GLWrap::name == nullptr) GLWrap::name = (typename GLWrap::t_##name)GLGETPROC(BOOST_PP_CAT(name,EXT)); \ Assert(Warn, GLWrap::name != nullptr, "could not load OpenGL function: %1%", #name) void GLWrap::loadGLFunc() { // 各種API関数 #ifndef ANDROID #ifdef ANDROID #include "android_gl.inc" #elif defined(WIN32) #include "mingw_gl.inc" #else #include "linux_gl.inc" #endif #endif // その他OS依存なAPI関数 LoadGLAux(); g_bglfuncInit = true; } #undef DEF_GLMETHOD #undef GLDEFINE // ---------------------- GLShader ---------------------- void GLShader::_initShader() { _idSh = GL.glCreateShader(_flag); std::string ss("#version 110\n"); ss.append(_source); const auto* pStr = ss.c_str(); GL.glShaderSource(_idSh, 1, &pStr, nullptr); GL.glCompileShader(_idSh); // エラーが無かったか確認 GLint compiled; GL.glGetShaderiv(_idSh, GL_COMPILE_STATUS, &compiled); AssertT(Trap, compiled==GL_TRUE, (GLE_ShaderError)(const std::string&)(GLuint), ss, _idSh) } GLShader::GLShader() {} GLShader::GLShader(GLuint flag, const std::string& src): _flag(flag), _source(src) { _initShader(); } GLShader::~GLShader() { onDeviceLost(); } bool GLShader::isEmpty() const { return _source.empty(); } int GLShader::getShaderID() const { return _idSh; } void GLShader::onDeviceLost() { if(_idSh!=0) { GL.glDeleteShader(_idSh); _idSh = 0; } } void GLShader::onDeviceReset() { if(!isEmpty() && _idSh==0) _initShader(); } // ---------------------- draw::Program ---------------------- namespace draw { Program::Program(HProg hProg): Token(hProg), _idProg(hProg.ref()->getProgramID()) {} Program::Program(Program&& p): Token(p), _idProg(p._idProg) {} void Program::exec() { GL.glUseProgram(_idProg); } } // ---------------------- GLProgram ---------------------- GLProgram::GLProgram(HSh vsh, HSh psh) { _shader[ShType::VERTEX] = vsh; _shader[ShType::PIXEL] = psh; _initProgram(); } GLProgram::GLProgram(HSh vsh, HSh gsh, HSh psh) { _shader[ShType::VERTEX] = vsh; _shader[ShType::PIXEL] = psh; _shader[ShType::GEOMETRY] = gsh; _initProgram(); } void GLProgram::_initProgram() { _idProg = GL.glCreateProgram(); for(int i=0 ; i<static_cast<int>(ShType::NUM_SHTYPE) ; i++) { auto& sh = _shader[i]; // Geometryシェーダー以外は必須 if(sh.valid()) { GL.glAttachShader(_idProg, sh.cref()->getShaderID()); GLEC_ChkP(Trap) } else { AssertT(Trap, i==ShType::GEOMETRY, (GLE_Error)(const char*), "missing shader elements (vertex or fragment)") } } GL.glLinkProgram(_idProg); // エラーが無いかチェック int ib; GL.glGetProgramiv(_idProg, GL_LINK_STATUS, &ib); AssertT(Trap, ib==GL_TRUE, (GLE_ProgramError)(GLuint), _idProg) } GLProgram::~GLProgram() { if(mgr_gl.isInDtor()) { for(auto& p : _shader) p.setNull(); } onDeviceLost(); } void GLProgram::onDeviceLost() { if(_idProg != 0) { // ShaderはProgramをDeleteすれば自動的にdetachされる GL.glDeleteProgram(_idProg); _idProg = 0; } } void GLProgram::onDeviceReset() { if(_idProg == 0) { // 先にshaderがresetされてないかもしれないので、ここでしておく for(auto& s : _shader) { if(s) s.cref()->onDeviceReset(); } _initProgram(); } } const HLSh& GLProgram::getShader(ShType type) const { return _shader[(int)type]; } int GLProgram::getUniformID(const std::string& name) const { GLint id = getUniformIDNc(name); AssertT(Trap, id>=0, (GLE_ParamNotFound)(const std::string&), name) return id; } int GLProgram::getUniformIDNc(const std::string& name) const { return GL.glGetUniformLocation(getProgramID(), name.c_str()); } int GLProgram::getAttribID(const std::string& name) const { GLint id = getAttribIDNc(name); AssertT(Trap, id>=0, (GLE_ParamNotFound)(const std::string&), name) return id; } GLuint GLProgram::getProgramID() const { return _idProg; } int GLProgram::getAttribIDNc(const std::string& name) const { return GL.glGetAttribLocation(getProgramID(), name.c_str()); } void GLProgram::use() const { GL.glUseProgram(getProgramID()); GLEC_ChkP(Trap) } } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the Campcaster project. http://campcaster.campware.org/ To report bugs, send an e-mail to bugs@campware.org Campcaster is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Campcaster 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 Campcaster; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author$ Version : $Revision$ Location : $URL$ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #define DEBUG_PREFIX "GstreamerPlayer" #include "LiveSupport/Core/Debug.h" #include "LiveSupport/Core/TimeConversion.h" #include "LiveSupport/GstreamerElements/autoplug.h" #include "GstreamerPlayer.h" using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::PlaylistExecutor; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /** * The name of the config element for this class */ const std::string GstreamerPlayer::configElementNameStr = "gstreamerPlayer"; /** * The name of the audio device attribute. */ static const std::string audioDeviceName = "audioDevice"; /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Configure the Audio Player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { DEBUG_FUNC_INFO if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } const xmlpp::Attribute * attribute = 0; if ((attribute = element.get_attribute(audioDeviceName))) { audioDevice = attribute->get_value(); } } /*------------------------------------------------------------------------------ * Initialize the Audio Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: initialize(void) throw (std::exception) { DEBUG_FUNC_INFO if (initialized) { return; } // initialize the gstreamer library if (!gst_init_check(0, 0)) { throw std::runtime_error("couldn't initialize the gstreamer library"); } // create the pipeline container (threaded) pipeline = gst_thread_new("audio-player"); filesrc = 0; decoder = 0; audioconvert = 0; audioscale = 0; g_signal_connect(pipeline, "error", G_CALLBACK(errorHandler), this); // TODO: read the caps from the config file sinkCaps = gst_caps_new_simple("audio/x-raw-int", "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, "endiannes", G_TYPE_INT, G_BYTE_ORDER, "channels", G_TYPE_INT, 2, "rate", G_TYPE_INT, 44100, NULL); setAudioDevice(audioDevice); // set up other variables initialized = true; } /*------------------------------------------------------------------------------ * Handler for gstreamer errors. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: errorHandler(GstElement * pipeline, GstElement * source, GError * error, gchar * debug, gpointer self) throw () { // TODO: handle error std::cerr << "gstreamer error: " << error->message << std::endl; } /*------------------------------------------------------------------------------ * De-initialize the Gstreamer Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: deInitialize(void) throw () { DEBUG_FUNC_INFO if (initialized) { gst_element_set_state(pipeline, GST_STATE_NULL); gst_bin_sync_children_state(GST_BIN(pipeline)); if (!gst_element_get_parent(audiosink)) { // delete manually, if audiosink wasn't added to the pipeline // for some reason gst_object_unref(GST_OBJECT(audiosink)); } gst_object_unref(GST_OBJECT(pipeline)); gst_caps_free(sinkCaps); audiosink = 0; initialized = false; } } /*------------------------------------------------------------------------------ * Attach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener) throw () { listeners.push_back(eventListener); } /*------------------------------------------------------------------------------ * Detach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener) throw (std::invalid_argument) { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { if (*it == eventListener) { listeners.erase(it); return; } ++it; } throw std::invalid_argument("supplied event listener not found"); } /*------------------------------------------------------------------------------ * Send the onStop event to all attached listeners. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: fireOnStopEvent(void) throw () { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { (*it)->onStop(); ++it; } } /*------------------------------------------------------------------------------ * An EOS event handler, that will put the pipeline to EOS as well. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: eosEventHandler(GstElement * element, gpointer self) throw () { GstreamerPlayer * player = (GstreamerPlayer*) self; gst_element_set_eos(player->pipeline); player->fireOnStopEvent(); } /*------------------------------------------------------------------------------ * Specify which file to play *----------------------------------------------------------------------------*/ void GstreamerPlayer :: open(const std::string fileUrl) throw (std::invalid_argument, std::runtime_error) { // GStreamer pipeline overview: // filesrc -> decoder -> audioconvert -> audioscale -> audiosink DEBUG_BLOCK std::string filePath; GstElement * pipe; GstElement * fakesink; gint64 position; if (isOpen()) { close(); } if (fileUrl.find("file://") == 0) { filePath = fileUrl.substr(7, fileUrl.size()); } else if (fileUrl.find("file:") == 0) { filePath = fileUrl.substr(5, fileUrl.size()); } else { throw std::invalid_argument("badly formed URL or unsupported protocol"); } filesrc = gst_element_factory_make("filesrc", "file-source"); gst_element_set(filesrc, "location", filePath.c_str(), NULL); decoder = ls_gst_autoplug_plug_source(filesrc, "decoder", sinkCaps); if (!decoder) { throw std::invalid_argument(std::string("can't open URL ") + fileUrl); } // connect the decoder unto a fakesink, and iterate on it until the // first bytes come out. this is to make sure that _really_ all // initialiation is done at opening pipe = gst_pipeline_new("pipe"); fakesink = gst_element_factory_make("fakesink", "fakesink"); gst_object_ref(GST_OBJECT(filesrc)); gst_object_ref(GST_OBJECT(decoder)); gst_element_link_many(decoder, fakesink, NULL); gst_bin_add_many(GST_BIN(pipe), filesrc, decoder, fakesink, NULL); gst_element_set_state(pipe, GST_STATE_PLAYING); position = 0LL; while (position == 0LL && gst_bin_iterate(GST_BIN(pipe))) { GstFormat format = GST_FORMAT_DEFAULT; gst_element_query(fakesink, GST_QUERY_POSITION, &format, &position); } gst_element_set_state(pipe, GST_STATE_PAUSED); gst_bin_remove_many(GST_BIN(pipe), filesrc, decoder, NULL); gst_element_unlink(decoder, fakesink); gst_object_unref(GST_OBJECT(pipe)); // converts between different audio formats (e.g. bitrate) audioconvert = gst_element_factory_make("audioconvert", NULL); // scale the sampling rate, if necessary audioscale = gst_element_factory_make("audioscale", NULL); gst_bin_add_many(GST_BIN(pipeline), filesrc, decoder, audioconvert, audioscale, NULL); gst_element_link_many(decoder, audioconvert, audioscale, audiosink, NULL); // connect the eos signal handler g_signal_connect(decoder, "eos", G_CALLBACK(eosEventHandler), this); if (gst_element_set_state(pipeline,GST_STATE_PAUSED) == GST_STATE_FAILURE) { close(); // the error is most probably caused by not being able to open // the audio device (as it might be blocked by an other process throw std::runtime_error("can't open audio device " + audioDevice); } gst_bin_sync_children_state(GST_BIN(pipeline)); } /*------------------------------------------------------------------------------ * Tell if we've been opened. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isOpen(void) throw () { return decoder != 0; } /*------------------------------------------------------------------------------ * Get the length of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPlaylength(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; GstFormat format = GST_FORMAT_TIME; if (!isOpen()) { throw std::logic_error("player not open"); } if (decoder && gst_element_query(decoder, GST_QUERY_TOTAL, &format, &ns) && format == GST_FORMAT_TIME) { // use microsec, as nanosec() is not found by the compiler (?) length.reset(new time_duration(microsec(ns / 1000LL))); } else { length.reset(new time_duration(microsec(0LL))); } return length; } /*------------------------------------------------------------------------------ * Get the current position of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPosition(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; if (!isOpen()) { throw std::logic_error("player not open"); } ns = ls_gst_autoplug_get_position(decoder); // this is necessary for boost version < 1.33.0 gint64 us = ns / 1000LL; long s = us / 1000000LL; long frac_s = us % 1000000LL; length.reset(new time_duration(seconds(s) + microseconds(frac_s))); // if we can be sure that boost >= 1.33.0, then we can write this instead: // length.reset(new time_duration(microseconds(ns / 1000LL))); return length; } /*------------------------------------------------------------------------------ * Start playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: start(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (!isPlaying()) { gst_element_set_state(pipeline, GST_STATE_PLAYING); } } /*------------------------------------------------------------------------------ * Pause the player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: pause(void) throw (std::logic_error) { if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_PAUSED); } } /*------------------------------------------------------------------------------ * Tell if we're playing *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isPlaying(void) throw () { return gst_element_get_state(pipeline) == GST_STATE_PLAYING; } /*------------------------------------------------------------------------------ * Stop playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: stop(void) throw (std::logic_error) { if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_READY); } } /*------------------------------------------------------------------------------ * Close the currently opened audio file. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: close(void) throw (std::logic_error) { DEBUG_FUNC_INFO if (isPlaying()) { stop(); } gst_element_set_state(pipeline, GST_STATE_NULL); // Unlink elements: if (filesrc && decoder) { gst_element_unlink(filesrc, decoder); } if (decoder && audioconvert) { gst_element_unlink(decoder, audioconvert); } if (audioconvert && audioscale ) { gst_element_unlink(audioconvert, audioscale); } if (audioscale && audiosink) { gst_element_unlink(audioscale, audiosink); } // Remove elements from pipeline: if (audioscale) { gst_bin_remove(GST_BIN(pipeline), audioscale); } if (audioconvert) { gst_bin_remove(GST_BIN(pipeline), audioconvert); } if (decoder) { gst_bin_remove(GST_BIN(pipeline), decoder); } if (filesrc) { gst_bin_remove(GST_BIN(pipeline), filesrc); } filesrc = 0; decoder = 0; audioconvert = 0; audioscale = 0; } /*------------------------------------------------------------------------------ * Get the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ unsigned int GstreamerPlayer :: getVolume(void) throw () { return 0; } /*------------------------------------------------------------------------------ * Set the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: setVolume(unsigned int volume) throw () {} /*------------------------------------------------------------------------------ * Set the audio device. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: setAudioDevice(const std::string &deviceName) throw () { DEBUG_BLOCK if (deviceName.size() == 0) { return false; } const bool oss = deviceName.find("/dev") == 0; if (audiosink) { debug() << "Destroying old sink." << endl; if (audioscale) { gst_element_unlink(audioscale, audiosink); } gst_bin_remove(GST_BIN(pipeline), audiosink); audiosink = 0; } if (!audiosink) { audiosink = (oss ? gst_element_factory_make("osssink", "osssink") : gst_element_factory_make("alsasink", "alsasink")); } if (!audiosink) { return false; } // it's the same property, "device" for both alsasink and osssink gst_element_set(audiosink, "device", deviceName.c_str(), NULL); if (audioscale) { gst_element_link_filtered(audioscale, audiosink, sinkCaps); } gst_bin_add(GST_BIN(pipeline), audiosink); gst_bin_sync_children_state(GST_BIN(pipeline)); return true; } <commit_msg>Output the current file URL to debug.<commit_after>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the Campcaster project. http://campcaster.campware.org/ To report bugs, send an e-mail to bugs@campware.org Campcaster is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Campcaster 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 Campcaster; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author$ Version : $Revision$ Location : $URL$ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #define DEBUG_PREFIX "GstreamerPlayer" #include "LiveSupport/Core/Debug.h" #include "LiveSupport/Core/TimeConversion.h" #include "LiveSupport/GstreamerElements/autoplug.h" #include "GstreamerPlayer.h" using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::PlaylistExecutor; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /** * The name of the config element for this class */ const std::string GstreamerPlayer::configElementNameStr = "gstreamerPlayer"; /** * The name of the audio device attribute. */ static const std::string audioDeviceName = "audioDevice"; /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Configure the Audio Player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { DEBUG_FUNC_INFO if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } const xmlpp::Attribute * attribute = 0; if ((attribute = element.get_attribute(audioDeviceName))) { audioDevice = attribute->get_value(); } } /*------------------------------------------------------------------------------ * Initialize the Audio Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: initialize(void) throw (std::exception) { DEBUG_FUNC_INFO if (initialized) { return; } // initialize the gstreamer library if (!gst_init_check(0, 0)) { throw std::runtime_error("couldn't initialize the gstreamer library"); } // create the pipeline container (threaded) pipeline = gst_thread_new("audio-player"); filesrc = 0; decoder = 0; audioconvert = 0; audioscale = 0; g_signal_connect(pipeline, "error", G_CALLBACK(errorHandler), this); // TODO: read the caps from the config file sinkCaps = gst_caps_new_simple("audio/x-raw-int", "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, "endiannes", G_TYPE_INT, G_BYTE_ORDER, "channels", G_TYPE_INT, 2, "rate", G_TYPE_INT, 44100, NULL); setAudioDevice(audioDevice); // set up other variables initialized = true; } /*------------------------------------------------------------------------------ * Handler for gstreamer errors. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: errorHandler(GstElement * pipeline, GstElement * source, GError * error, gchar * debug, gpointer self) throw () { // TODO: handle error std::cerr << "gstreamer error: " << error->message << std::endl; } /*------------------------------------------------------------------------------ * De-initialize the Gstreamer Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: deInitialize(void) throw () { DEBUG_FUNC_INFO if (initialized) { gst_element_set_state(pipeline, GST_STATE_NULL); gst_bin_sync_children_state(GST_BIN(pipeline)); if (!gst_element_get_parent(audiosink)) { // delete manually, if audiosink wasn't added to the pipeline // for some reason gst_object_unref(GST_OBJECT(audiosink)); } gst_object_unref(GST_OBJECT(pipeline)); gst_caps_free(sinkCaps); audiosink = 0; initialized = false; } } /*------------------------------------------------------------------------------ * Attach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener) throw () { listeners.push_back(eventListener); } /*------------------------------------------------------------------------------ * Detach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener) throw (std::invalid_argument) { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { if (*it == eventListener) { listeners.erase(it); return; } ++it; } throw std::invalid_argument("supplied event listener not found"); } /*------------------------------------------------------------------------------ * Send the onStop event to all attached listeners. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: fireOnStopEvent(void) throw () { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { (*it)->onStop(); ++it; } } /*------------------------------------------------------------------------------ * An EOS event handler, that will put the pipeline to EOS as well. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: eosEventHandler(GstElement * element, gpointer self) throw () { GstreamerPlayer * player = (GstreamerPlayer*) self; gst_element_set_eos(player->pipeline); player->fireOnStopEvent(); } /*------------------------------------------------------------------------------ * Specify which file to play *----------------------------------------------------------------------------*/ void GstreamerPlayer :: open(const std::string fileUrl) throw (std::invalid_argument, std::runtime_error) { // GStreamer pipeline overview: // filesrc -> decoder -> audioconvert -> audioscale -> audiosink DEBUG_BLOCK std::string filePath; GstElement * pipe; GstElement * fakesink; gint64 position; if (isOpen()) { close(); } debug() << "Opening URL: " << fileUrl << endl; if (fileUrl.find("file://") == 0) { filePath = fileUrl.substr(7, fileUrl.size()); } else if (fileUrl.find("file:") == 0) { filePath = fileUrl.substr(5, fileUrl.size()); } else { throw std::invalid_argument("badly formed URL or unsupported protocol"); } filesrc = gst_element_factory_make("filesrc", "file-source"); gst_element_set(filesrc, "location", filePath.c_str(), NULL); decoder = ls_gst_autoplug_plug_source(filesrc, "decoder", sinkCaps); if (!decoder) { throw std::invalid_argument(std::string("can't open URL ") + fileUrl); } // connect the decoder unto a fakesink, and iterate on it until the // first bytes come out. this is to make sure that _really_ all // initialiation is done at opening pipe = gst_pipeline_new("pipe"); fakesink = gst_element_factory_make("fakesink", "fakesink"); gst_object_ref(GST_OBJECT(filesrc)); gst_object_ref(GST_OBJECT(decoder)); gst_element_link_many(decoder, fakesink, NULL); gst_bin_add_many(GST_BIN(pipe), filesrc, decoder, fakesink, NULL); gst_element_set_state(pipe, GST_STATE_PLAYING); position = 0LL; while (position == 0LL && gst_bin_iterate(GST_BIN(pipe))) { GstFormat format = GST_FORMAT_DEFAULT; gst_element_query(fakesink, GST_QUERY_POSITION, &format, &position); } gst_element_set_state(pipe, GST_STATE_PAUSED); gst_bin_remove_many(GST_BIN(pipe), filesrc, decoder, NULL); gst_element_unlink(decoder, fakesink); gst_object_unref(GST_OBJECT(pipe)); // converts between different audio formats (e.g. bitrate) audioconvert = gst_element_factory_make("audioconvert", NULL); // scale the sampling rate, if necessary audioscale = gst_element_factory_make("audioscale", NULL); gst_bin_add_many(GST_BIN(pipeline), filesrc, decoder, audioconvert, audioscale, NULL); gst_element_link_many(decoder, audioconvert, audioscale, audiosink, NULL); // connect the eos signal handler g_signal_connect(decoder, "eos", G_CALLBACK(eosEventHandler), this); if (gst_element_set_state(pipeline,GST_STATE_PAUSED) == GST_STATE_FAILURE) { close(); // the error is most probably caused by not being able to open // the audio device (as it might be blocked by an other process throw std::runtime_error("can't open audio device " + audioDevice); } gst_bin_sync_children_state(GST_BIN(pipeline)); } /*------------------------------------------------------------------------------ * Tell if we've been opened. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isOpen(void) throw () { return decoder != 0; } /*------------------------------------------------------------------------------ * Get the length of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPlaylength(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; GstFormat format = GST_FORMAT_TIME; if (!isOpen()) { throw std::logic_error("player not open"); } if (decoder && gst_element_query(decoder, GST_QUERY_TOTAL, &format, &ns) && format == GST_FORMAT_TIME) { // use microsec, as nanosec() is not found by the compiler (?) length.reset(new time_duration(microsec(ns / 1000LL))); } else { length.reset(new time_duration(microsec(0LL))); } return length; } /*------------------------------------------------------------------------------ * Get the current position of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPosition(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; if (!isOpen()) { throw std::logic_error("player not open"); } ns = ls_gst_autoplug_get_position(decoder); // this is necessary for boost version < 1.33.0 gint64 us = ns / 1000LL; long s = us / 1000000LL; long frac_s = us % 1000000LL; length.reset(new time_duration(seconds(s) + microseconds(frac_s))); // if we can be sure that boost >= 1.33.0, then we can write this instead: // length.reset(new time_duration(microseconds(ns / 1000LL))); return length; } /*------------------------------------------------------------------------------ * Start playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: start(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (!isPlaying()) { gst_element_set_state(pipeline, GST_STATE_PLAYING); } } /*------------------------------------------------------------------------------ * Pause the player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: pause(void) throw (std::logic_error) { if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_PAUSED); } } /*------------------------------------------------------------------------------ * Tell if we're playing *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isPlaying(void) throw () { return gst_element_get_state(pipeline) == GST_STATE_PLAYING; } /*------------------------------------------------------------------------------ * Stop playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: stop(void) throw (std::logic_error) { if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_READY); } } /*------------------------------------------------------------------------------ * Close the currently opened audio file. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: close(void) throw (std::logic_error) { DEBUG_FUNC_INFO if (isPlaying()) { stop(); } gst_element_set_state(pipeline, GST_STATE_NULL); // Unlink elements: if (filesrc && decoder) { gst_element_unlink(filesrc, decoder); } if (decoder && audioconvert) { gst_element_unlink(decoder, audioconvert); } if (audioconvert && audioscale ) { gst_element_unlink(audioconvert, audioscale); } if (audioscale && audiosink) { gst_element_unlink(audioscale, audiosink); } // Remove elements from pipeline: if (audioscale) { gst_bin_remove(GST_BIN(pipeline), audioscale); } if (audioconvert) { gst_bin_remove(GST_BIN(pipeline), audioconvert); } if (decoder) { gst_bin_remove(GST_BIN(pipeline), decoder); } if (filesrc) { gst_bin_remove(GST_BIN(pipeline), filesrc); } filesrc = 0; decoder = 0; audioconvert = 0; audioscale = 0; } /*------------------------------------------------------------------------------ * Get the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ unsigned int GstreamerPlayer :: getVolume(void) throw () { return 0; } /*------------------------------------------------------------------------------ * Set the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: setVolume(unsigned int volume) throw () {} /*------------------------------------------------------------------------------ * Set the audio device. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: setAudioDevice(const std::string &deviceName) throw () { DEBUG_BLOCK if (deviceName.size() == 0) { return false; } const bool oss = deviceName.find("/dev") == 0; if (audiosink) { debug() << "Destroying old sink." << endl; if (audioscale) { gst_element_unlink(audioscale, audiosink); } gst_bin_remove(GST_BIN(pipeline), audiosink); audiosink = 0; } if (!audiosink) { audiosink = (oss ? gst_element_factory_make("osssink", "osssink") : gst_element_factory_make("alsasink", "alsasink")); } if (!audiosink) { return false; } // it's the same property, "device" for both alsasink and osssink gst_element_set(audiosink, "device", deviceName.c_str(), NULL); if (audioscale) { gst_element_link_filtered(audioscale, audiosink, sinkCaps); } gst_bin_add(GST_BIN(pipeline), audiosink); gst_bin_sync_children_state(GST_BIN(pipeline)); return true; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "glimports.hpp" #include "glws.hpp" namespace glws { class WglDrawable : public Drawable { public: DWORD dwExStyle; DWORD dwStyle; HWND hWnd; HDC hDC; PIXELFORMATDESCRIPTOR pfd; int iPixelFormat; WglDrawable(const Visual *vis) : Drawable(vis) { static bool first = TRUE; RECT rect; if (first) { WNDCLASS wc; memset(&wc, 0, sizeof wc); wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.lpfnWndProc = DefWindowProc; wc.lpszClassName = "glretrace"; wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; RegisterClass(&wc); first = FALSE; } dwExStyle = 0; dwStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE | WS_OVERLAPPEDWINDOW; int x = 0, y = 0, width = 256, height = 256; rect.left = x; rect.top = y; rect.right = rect.left + width; rect.bottom = rect.top + height; AdjustWindowRectEx(&rect, dwStyle, FALSE, dwExStyle); hWnd = CreateWindowEx(dwExStyle, "glretrace", /* wc.lpszClassName */ NULL, dwStyle, CW_USEDEFAULT, /* x */ CW_USEDEFAULT, /* y */ rect.right - rect.left, /* width */ rect.bottom - rect.top, /* height */ NULL, NULL, NULL, NULL); hDC = GetDC(hWnd); memset(&pfd, 0, sizeof pfd); pfd.cColorBits = 3; pfd.cRedBits = 1; pfd.cGreenBits = 1; pfd.cBlueBits = 1; pfd.cDepthBits = 1; pfd.cStencilBits = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; pfd.iLayerType = PFD_MAIN_PLANE; pfd.iPixelType = PFD_TYPE_RGBA; pfd.nSize = sizeof(pfd); pfd.nVersion = 1; if (visual->doubleBuffer) { pfd.dwFlags |= PFD_DOUBLEBUFFER; } iPixelFormat = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, iPixelFormat, &pfd); } ~WglDrawable() { ReleaseDC(hWnd, hDC); DestroyWindow(hWnd); } void resize(unsigned w, unsigned h) { Drawable::resize(w, h); RECT rClient, rWindow; GetClientRect(hWnd, &rClient); GetWindowRect(hWnd, &rWindow); w += (rWindow.right - rWindow.left) - rClient.right; h += (rWindow.bottom - rWindow.top) - rClient.bottom; MoveWindow(hWnd, rWindow.left, rWindow.top, w, h, TRUE); } void swapBuffers(void) { SwapBuffers(hDC); } }; class WglContext : public Context { public: HGLRC hglrc; WglContext(const Visual *vis) : Context(vis), hglrc(0) {} ~WglContext() { if (hglrc) { wglDeleteContext(hglrc); } } }; class WglWindowSystem : public WindowSystem { public: Visual * createVisual(bool doubleBuffer) { Visual *visual = new Visual(); visual->doubleBuffer = doubleBuffer; return visual; } Drawable * createDrawable(const Visual *visual) { return new WglDrawable(visual); } Context * createContext(const Visual *visual) { return new WglContext(visual); } bool makeCurrent(Drawable *drawable, Context *context) { if (!drawable || !context) { return wglMakeCurrent(NULL, NULL); } else { WglDrawable *wglDrawable = dynamic_cast<WglDrawable *>(drawable); WglContext *wglContext = dynamic_cast<WglContext *>(context); if (!wglContext->hglrc) { wglContext->hglrc = wglCreateContext(wglDrawable->hDC); if (!wglContext->hglrc) { return false; } } return wglMakeCurrent(wglDrawable->hDC, wglContext->hglrc); } } bool processEvents(void) { // TODO return true; } }; WindowSystem *createNativeWindowSystem(void) { return new WglWindowSystem(); } } /* namespace glretrace */ <commit_msg>Allow to resize the window to be larger than the desktop.<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "glimports.hpp" #include "glws.hpp" namespace glws { static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { MINMAXINFO *pMMI; switch (uMsg) { case WM_GETMINMAXINFO: // Allow to create a window bigger than the desktop pMMI = (MINMAXINFO *)lParam; pMMI->ptMaxSize.x = 60000; pMMI->ptMaxSize.y = 60000; pMMI->ptMaxTrackSize.x = 60000; pMMI->ptMaxTrackSize.y = 60000; break; default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } class WglDrawable : public Drawable { public: DWORD dwExStyle; DWORD dwStyle; HWND hWnd; HDC hDC; PIXELFORMATDESCRIPTOR pfd; int iPixelFormat; WglDrawable(const Visual *vis) : Drawable(vis) { static bool first = TRUE; RECT rect; if (first) { WNDCLASS wc; memset(&wc, 0, sizeof wc); wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.lpfnWndProc = WndProc; wc.lpszClassName = "glretrace"; wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; RegisterClass(&wc); first = FALSE; } dwExStyle = 0; dwStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE | WS_OVERLAPPEDWINDOW; int x = 0, y = 0, width = 256, height = 256; rect.left = x; rect.top = y; rect.right = rect.left + width; rect.bottom = rect.top + height; AdjustWindowRectEx(&rect, dwStyle, FALSE, dwExStyle); hWnd = CreateWindowEx(dwExStyle, "glretrace", /* wc.lpszClassName */ NULL, dwStyle, 0, /* x */ 0, /* y */ rect.right - rect.left, /* width */ rect.bottom - rect.top, /* height */ NULL, NULL, NULL, NULL); hDC = GetDC(hWnd); memset(&pfd, 0, sizeof pfd); pfd.cColorBits = 3; pfd.cRedBits = 1; pfd.cGreenBits = 1; pfd.cBlueBits = 1; pfd.cDepthBits = 1; pfd.cStencilBits = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; pfd.iLayerType = PFD_MAIN_PLANE; pfd.iPixelType = PFD_TYPE_RGBA; pfd.nSize = sizeof(pfd); pfd.nVersion = 1; if (visual->doubleBuffer) { pfd.dwFlags |= PFD_DOUBLEBUFFER; } iPixelFormat = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, iPixelFormat, &pfd); } ~WglDrawable() { ReleaseDC(hWnd, hDC); DestroyWindow(hWnd); } void resize(unsigned w, unsigned h) { Drawable::resize(w, h); RECT rClient, rWindow; GetClientRect(hWnd, &rClient); GetWindowRect(hWnd, &rWindow); w += (rWindow.right - rWindow.left) - rClient.right; h += (rWindow.bottom - rWindow.top) - rClient.bottom; SetWindowPos(hWnd, NULL, rWindow.left, rWindow.top, w, h, SWP_NOMOVE); } void swapBuffers(void) { SwapBuffers(hDC); } }; class WglContext : public Context { public: HGLRC hglrc; WglContext(const Visual *vis) : Context(vis), hglrc(0) {} ~WglContext() { if (hglrc) { wglDeleteContext(hglrc); } } }; class WglWindowSystem : public WindowSystem { public: Visual * createVisual(bool doubleBuffer) { Visual *visual = new Visual(); visual->doubleBuffer = doubleBuffer; return visual; } Drawable * createDrawable(const Visual *visual) { return new WglDrawable(visual); } Context * createContext(const Visual *visual) { return new WglContext(visual); } bool makeCurrent(Drawable *drawable, Context *context) { if (!drawable || !context) { return wglMakeCurrent(NULL, NULL); } else { WglDrawable *wglDrawable = dynamic_cast<WglDrawable *>(drawable); WglContext *wglContext = dynamic_cast<WglContext *>(context); if (!wglContext->hglrc) { wglContext->hglrc = wglCreateContext(wglDrawable->hDC); if (!wglContext->hglrc) { return false; } } return wglMakeCurrent(wglDrawable->hDC, wglContext->hglrc); } } bool processEvents(void) { // TODO return true; } }; WindowSystem *createNativeWindowSystem(void) { return new WglWindowSystem(); } } /* namespace glretrace */ <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkBlurMaskFilter.h" namespace skiagm { class BlursGM : public GM { public: BlursGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual SkString onShortName() { return SkString("blurs"); } virtual SkISize onISize() { return make_isize(700, 500); } virtual void onDraw(SkCanvas* canvas) { SkBlurMaskFilter::BlurStyle NONE = SkBlurMaskFilter::BlurStyle(-999); static const struct { SkBlurMaskFilter::BlurStyle fStyle; int fCx, fCy; } gRecs[] = { { NONE, 0, 0 }, { SkBlurMaskFilter::kInner_BlurStyle, -1, 0 }, { SkBlurMaskFilter::kNormal_BlurStyle, 0, 1 }, { SkBlurMaskFilter::kSolid_BlurStyle, 0, -1 }, { SkBlurMaskFilter::kOuter_BlurStyle, 1, 0 }, }; SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(25)); canvas->translate(SkIntToScalar(-40), SkIntToScalar(0)); SkBlurMaskFilter::BlurFlags flags = SkBlurMaskFilter::kNone_BlurFlag; for (int j = 0; j < 2; j++) { canvas->save(); paint.setColor(SK_ColorBLUE); for (size_t i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { if (gRecs[i].fStyle != NONE) { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(20), gRecs[i].fStyle, flags ); paint.setMaskFilter(mf)->unref(); } else { paint.setMaskFilter(NULL); } canvas->drawCircle(SkIntToScalar(200 + gRecs[i].fCx*100) , SkIntToScalar(200 + gRecs[i].fCy*100) , SkIntToScalar(50) , paint); } // draw text { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(4) , SkBlurMaskFilter::kNormal_BlurStyle , flags ); paint.setMaskFilter(mf)->unref(); SkScalar x = SkIntToScalar(70); SkScalar y = SkIntToScalar(400); paint.setColor(SK_ColorBLACK); canvas->drawText("Hamburgefons Style", 18, x, y, paint); canvas->drawText("Hamburgefons Style", 18 , x, y + SkIntToScalar(50), paint); paint.setMaskFilter(NULL); paint.setColor(SK_ColorWHITE); x -= SkIntToScalar(2); y -= SkIntToScalar(2); canvas->drawText("Hamburgefons Style", 18, x, y, paint); } canvas->restore(); flags = SkBlurMaskFilter::kHighQuality_BlurFlag; canvas->translate(SkIntToScalar(350), SkIntToScalar(0)); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BlursGM; } static GMRegistry reg(MyFactory); } <commit_msg>Turn off the blurs GM for Pipe playback.<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkBlurMaskFilter.h" namespace skiagm { class BlursGM : public GM { public: BlursGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual uint32_t onGetFlags() const SK_OVERRIDE { return this->INHERITED::onGetFlags() | GM::kSkipPipe_Flag; } virtual SkString onShortName() { return SkString("blurs"); } virtual SkISize onISize() { return make_isize(700, 500); } virtual void onDraw(SkCanvas* canvas) { SkBlurMaskFilter::BlurStyle NONE = SkBlurMaskFilter::BlurStyle(-999); static const struct { SkBlurMaskFilter::BlurStyle fStyle; int fCx, fCy; } gRecs[] = { { NONE, 0, 0 }, { SkBlurMaskFilter::kInner_BlurStyle, -1, 0 }, { SkBlurMaskFilter::kNormal_BlurStyle, 0, 1 }, { SkBlurMaskFilter::kSolid_BlurStyle, 0, -1 }, { SkBlurMaskFilter::kOuter_BlurStyle, 1, 0 }, }; SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(25)); canvas->translate(SkIntToScalar(-40), SkIntToScalar(0)); SkBlurMaskFilter::BlurFlags flags = SkBlurMaskFilter::kNone_BlurFlag; for (int j = 0; j < 2; j++) { canvas->save(); paint.setColor(SK_ColorBLUE); for (size_t i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { if (gRecs[i].fStyle != NONE) { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(20), gRecs[i].fStyle, flags ); paint.setMaskFilter(mf)->unref(); } else { paint.setMaskFilter(NULL); } canvas->drawCircle(SkIntToScalar(200 + gRecs[i].fCx*100) , SkIntToScalar(200 + gRecs[i].fCy*100) , SkIntToScalar(50) , paint); } // draw text { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(4) , SkBlurMaskFilter::kNormal_BlurStyle , flags ); paint.setMaskFilter(mf)->unref(); SkScalar x = SkIntToScalar(70); SkScalar y = SkIntToScalar(400); paint.setColor(SK_ColorBLACK); canvas->drawText("Hamburgefons Style", 18, x, y, paint); canvas->drawText("Hamburgefons Style", 18 , x, y + SkIntToScalar(50), paint); paint.setMaskFilter(NULL); paint.setColor(SK_ColorWHITE); x -= SkIntToScalar(2); y -= SkIntToScalar(2); canvas->drawText("Hamburgefons Style", 18, x, y, paint); } canvas->restore(); flags = SkBlurMaskFilter::kHighQuality_BlurFlag; canvas->translate(SkIntToScalar(350), SkIntToScalar(0)); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BlursGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>/************************************************************************/ /* XGPacket */ /* */ /* XGrid Packet */ /* */ /* XGPacket.cpp */ /* */ /* Alex Forencich <alex@alexforencich.com> */ /* */ /* Copyright (c) 2011 Alex Forencich */ /* */ /* 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 */ /* MEXGHANTABILITY, 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 "XGPacket.h" #include <sstream> #include <iomanip> XGPacket::XGPacket() { zero(); } XGPacket::~XGPacket() { // nothing } void XGPacket::zero() { source_id = 0; type = 0; seq = 0; flags = 0; radius = 0; data.clear(); } uint16_t XGPacket::get_length() { return data.size()+sizeof(xgrid_header_t); } std::vector<uint8_t> XGPacket::get_raw_packet() { std::vector<uint8_t> dataout; dataout.push_back(XGRID_IDENTIFIER); dataout.push_back(payload.size()); dataout.push_back(payload.size() >> 8); dataout.insert(dataout.end(), payload.begin(), payload.end()); return dataout; } bool XGPacket::read_packet(std::vector<char> bytes, size_t &bytes_read) { return read_packet((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet(std::vector<uint8_t> bytes, size_t &bytes_read) { return read_packet(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet(std::deque<char> bytes, size_t &bytes_read) { return read_packet((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet(std::deque<uint8_t> bytes, size_t &bytes_read) { return read_packet(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet(uint8_t *bytes, size_t count, size_t &bytes_read) { size_t n = 0; uint16_t size; uint8_t *ptr = bytes; uint8_t b; if (count == 0) return false; // find packet start byte while ((*(ptr++) != XGRID_IDENTIFIER) & (n++ < count)) { } // start of packet offset // to discard junk ahead of incomplete packet // (assuming packet is currently truncated) bytes_read = n-1; // return if out of buffer if (n > count) return false; // return if not enough bytes left if (count - n < sizeof(xgrid_header_t) + 2) return false; // get packet size size = (uint16_t)*(ptr++); size |= (uint16_t)*(ptr++) << 8; n += 2; // return if we don't have the whole packet if (count - n < size) return false; payload.clear(); // read payload for (int i = 0; i < size; i++) { b = *(ptr++); payload.push_back(b); n++; } bytes_read = n; return true; } bool XGPacket::read_packet_bare(std::vector<char> bytes, size_t &bytes_read) { return read_packet_bare((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(std::vector<uint8_t> bytes, size_t &bytes_read) { return read_packet_bare(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(std::deque<char> bytes, size_t &bytes_read) { return read_packet_bare((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(std::deque<uint8_t> bytes, size_t &bytes_read) { return read_packet_bare(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(uint8_t *bytes, size_t count, size_t &bytes_read) { size_t n = 0; uint8_t *ptr = bytes; uint8_t b; if (count < sizeof(xgrid_header_t)) return false; payload.clear(); // read payload for (int i = 0; i < count; i++) { b = *(ptr++); payload.push_back(b); } bytes_read = count; return true; } bool XGPacket::build_packet() { payload.clear(); payload.push_back(source_id); payload.push_back(source_id << 8); payload.push_back(type); payload.push_back(seq); payload.push_back(flags); payload.push_back(radius); for (int i = 0; i < data.size(); i++) { payload.push_back(data[i]); } return true; } bool XGPacket::decode_packet() { if (payload.size() < sizeof(xgrid_header_t)) return false; source_id = read_payload_uint16(0); type = payload[2]; seq = payload[3]; flags = payload[4]; radius = payload[5]; data.clear(); for (int i = sizeof(xgrid_header_t); i < payload.size(); i++) { data.push_back(payload[i]); } return true; } std::string XGPacket::get_desc() { std::stringstream desc; desc << "XGrid Packet" << std::endl; desc << " Length: " << std::dec << get_length() << std::endl; desc << " Source ID: 0x" << std::setfill('0') << std::setw(4) << std::hex << (int)source_id << std::endl; desc << " Type: 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)type << std::endl; desc << " Seq: " << std::dec << (int)seq << std::endl; desc << " Flags: 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)flags << std::endl; desc << " Radius: " << std::dec << (int)radius << std::endl; desc << " Data (hex):"; for (int i = 0; i < data.size(); i++) { if (i > 0 && i % 16 == 0) desc << std::endl << " "; desc << " " << std::setfill('0') << std::setw(2) << std::hex << (int)data[i]; } desc << std::endl; return desc.str(); } std::string XGPacket::get_hex_packet() { std::vector<uint8_t> pkt = get_raw_packet(); std::stringstream out; for (int i = 0; i < pkt.size(); i++) { if (i > 0) out << " "; out << std::setfill('0') << std::setw(2) << std::hex << (int)pkt[i]; } return out.str(); } // read and write payload data uint8_t XGPacket::read_payload_uint8(int offset) { if (offset < 0) return 0; return payload[offset]; } uint16_t XGPacket::read_payload_uint16(int offset) { if (offset < 0) return 0; uint16_t value; value = (uint16_t)payload[offset]; value |= (uint16_t)payload[offset+1] << 8; return value; } uint32_t XGPacket::read_payload_uint32(int offset) { if (offset < 0) return 0; uint32_t value; value = (uint32_t)payload[offset]; value |= (uint32_t)payload[offset+1] << 8; value |= (uint32_t)payload[offset+2] << 16; value |= (uint32_t)payload[offset+3] << 24; return value; } uint64_t XGPacket::read_payload_uint64(int offset) { if (offset < 0) return 0; uint64_t value; value = (uint64_t)payload[offset]; value |= (uint64_t)payload[offset+1] << 8; value |= (uint64_t)payload[offset+2] << 16; value |= (uint64_t)payload[offset+3] << 24; value |= (uint64_t)payload[offset+4] << 32; value |= (uint64_t)payload[offset+5] << 40; value |= (uint64_t)payload[offset+6] << 48; value |= (uint64_t)payload[offset+7] << 56; return value; } void XGPacket::write_payload_uint8(int offset, uint8_t value) { if (offset < 0) return; payload[offset] = value; } void XGPacket::write_payload_uint16(int offset, uint16_t value) { if (offset < 0) return; payload[offset] = value; payload[offset+1] = value >> 8; } void XGPacket::write_payload_uint32(int offset, uint32_t value) { if (offset < 0) return; payload[offset] = value; payload[offset+1] = value >> 8; payload[offset+2] = value >> 16; payload[offset+3] = value >> 24; } void XGPacket::write_payload_uint64(int offset, uint64_t value) { if (offset < 0) return; payload[offset] = value; payload[offset+1] = value >> 8; payload[offset+2] = value >> 16; payload[offset+3] = value >> 24; payload[offset+4] = value >> 32; payload[offset+5] = value >> 40; payload[offset+6] = value >> 48; payload[offset+7] = value >> 56; } <commit_msg>Fixed deque cast issue<commit_after>/************************************************************************/ /* XGPacket */ /* */ /* XGrid Packet */ /* */ /* XGPacket.cpp */ /* */ /* Alex Forencich <alex@alexforencich.com> */ /* */ /* Copyright (c) 2011 Alex Forencich */ /* */ /* 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 */ /* MEXGHANTABILITY, 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 "XGPacket.h" #include <sstream> #include <iomanip> XGPacket::XGPacket() { zero(); } XGPacket::~XGPacket() { // nothing } void XGPacket::zero() { source_id = 0; type = 0; seq = 0; flags = 0; radius = 0; data.clear(); } uint16_t XGPacket::get_length() { return data.size()+sizeof(xgrid_header_t); } std::vector<uint8_t> XGPacket::get_raw_packet() { std::vector<uint8_t> dataout; dataout.push_back(XGRID_IDENTIFIER); dataout.push_back(payload.size()); dataout.push_back(payload.size() >> 8); dataout.insert(dataout.end(), payload.begin(), payload.end()); return dataout; } bool XGPacket::read_packet(std::vector<char> bytes, size_t &bytes_read) { return read_packet((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet(std::vector<uint8_t> bytes, size_t &bytes_read) { return read_packet(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet(std::deque<char> bytes, size_t &bytes_read) { std::vector<char> v(bytes.begin(), bytes.end()); return read_packet(v, bytes_read); } bool XGPacket::read_packet(std::deque<uint8_t> bytes, size_t &bytes_read) { std::vector<uint8_t> v(bytes.begin(), bytes.end()); return read_packet(v, bytes_read); } bool XGPacket::read_packet(uint8_t *bytes, size_t count, size_t &bytes_read) { size_t n = 0; uint16_t size; uint8_t *ptr = bytes; uint8_t b; if (count == 0) return false; // find packet start byte while ((*(ptr++) != XGRID_IDENTIFIER) & (n++ < count)) { } // start of packet offset // to discard junk ahead of incomplete packet // (assuming packet is currently truncated) bytes_read = n-1; // return if out of buffer if (n > count) return false; // return if not enough bytes left if (count - n < sizeof(xgrid_header_t) + 2) return false; // get packet size size = (uint16_t)*(ptr++); size |= (uint16_t)*(ptr++) << 8; n += 2; // return if we don't have the whole packet if (count - n < size) return false; payload.clear(); // read payload for (int i = 0; i < size; i++) { b = *(ptr++); payload.push_back(b); n++; } bytes_read = n; return true; } bool XGPacket::read_packet_bare(std::vector<char> bytes, size_t &bytes_read) { return read_packet_bare((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(std::vector<uint8_t> bytes, size_t &bytes_read) { return read_packet_bare(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(std::deque<char> bytes, size_t &bytes_read) { return read_packet_bare((uint8_t *)&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(std::deque<uint8_t> bytes, size_t &bytes_read) { return read_packet_bare(&bytes[0], bytes.size(), bytes_read); } bool XGPacket::read_packet_bare(uint8_t *bytes, size_t count, size_t &bytes_read) { size_t n = 0; uint8_t *ptr = bytes; uint8_t b; if (count < sizeof(xgrid_header_t)) return false; payload.clear(); // read payload for (int i = 0; i < count; i++) { b = *(ptr++); payload.push_back(b); } bytes_read = count; return true; } bool XGPacket::build_packet() { payload.clear(); payload.push_back(source_id); payload.push_back(source_id << 8); payload.push_back(type); payload.push_back(seq); payload.push_back(flags); payload.push_back(radius); for (int i = 0; i < data.size(); i++) { payload.push_back(data[i]); } return true; } bool XGPacket::decode_packet() { if (payload.size() < sizeof(xgrid_header_t)) return false; source_id = read_payload_uint16(0); type = payload[2]; seq = payload[3]; flags = payload[4]; radius = payload[5]; data.clear(); for (int i = sizeof(xgrid_header_t); i < payload.size(); i++) { data.push_back(payload[i]); } return true; } std::string XGPacket::get_desc() { std::stringstream desc; desc << "XGrid Packet" << std::endl; desc << " Length: " << std::dec << get_length() << std::endl; desc << " Source ID: 0x" << std::setfill('0') << std::setw(4) << std::hex << (int)source_id << std::endl; desc << " Type: 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)type << std::endl; desc << " Seq: " << std::dec << (int)seq << std::endl; desc << " Flags: 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)flags << std::endl; desc << " Radius: " << std::dec << (int)radius << std::endl; desc << " Data (hex):"; for (int i = 0; i < data.size(); i++) { if (i > 0 && i % 16 == 0) desc << std::endl << " "; desc << " " << std::setfill('0') << std::setw(2) << std::hex << (int)data[i]; } desc << std::endl; return desc.str(); } std::string XGPacket::get_hex_packet() { std::vector<uint8_t> pkt = get_raw_packet(); std::stringstream out; for (int i = 0; i < pkt.size(); i++) { if (i > 0) out << " "; out << std::setfill('0') << std::setw(2) << std::hex << (int)pkt[i]; } return out.str(); } // read and write payload data uint8_t XGPacket::read_payload_uint8(int offset) { if (offset < 0) return 0; return payload[offset]; } uint16_t XGPacket::read_payload_uint16(int offset) { if (offset < 0) return 0; uint16_t value; value = (uint16_t)payload[offset]; value |= (uint16_t)payload[offset+1] << 8; return value; } uint32_t XGPacket::read_payload_uint32(int offset) { if (offset < 0) return 0; uint32_t value; value = (uint32_t)payload[offset]; value |= (uint32_t)payload[offset+1] << 8; value |= (uint32_t)payload[offset+2] << 16; value |= (uint32_t)payload[offset+3] << 24; return value; } uint64_t XGPacket::read_payload_uint64(int offset) { if (offset < 0) return 0; uint64_t value; value = (uint64_t)payload[offset]; value |= (uint64_t)payload[offset+1] << 8; value |= (uint64_t)payload[offset+2] << 16; value |= (uint64_t)payload[offset+3] << 24; value |= (uint64_t)payload[offset+4] << 32; value |= (uint64_t)payload[offset+5] << 40; value |= (uint64_t)payload[offset+6] << 48; value |= (uint64_t)payload[offset+7] << 56; return value; } void XGPacket::write_payload_uint8(int offset, uint8_t value) { if (offset < 0) return; payload[offset] = value; } void XGPacket::write_payload_uint16(int offset, uint16_t value) { if (offset < 0) return; payload[offset] = value; payload[offset+1] = value >> 8; } void XGPacket::write_payload_uint32(int offset, uint32_t value) { if (offset < 0) return; payload[offset] = value; payload[offset+1] = value >> 8; payload[offset+2] = value >> 16; payload[offset+3] = value >> 24; } void XGPacket::write_payload_uint64(int offset, uint64_t value) { if (offset < 0) return; payload[offset] = value; payload[offset+1] = value >> 8; payload[offset+2] = value >> 16; payload[offset+3] = value >> 24; payload[offset+4] = value >> 32; payload[offset+5] = value >> 40; payload[offset+6] = value >> 48; payload[offset+7] = value >> 56; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_Wizard_TitlesAndObjects.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:38:49 $ * * 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_chart2.hxx" #include "tp_Wizard_TitlesAndObjects.hxx" #include "tp_Wizard_TitlesAndObjects.hrc" #include "Strings.hrc" #include "res_Titles.hxx" #include "res_LegendPosition.hxx" #include "ResId.hxx" #include "HelpIds.hrc" #include "macros.hxx" #include "ChartModelHelper.hxx" #include "AxisHelper.hxx" #include "LegendHelper.hxx" #include "NoWarningThisInCTOR.hxx" #include "ControllerLockGuard.hxx" //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; TitlesAndObjectsTabPage::TitlesAndObjectsTabPage( svt::OWizardMachine* pParent , const uno::Reference< XChartDocument >& xChartModel , const uno::Reference< uno::XComponentContext >& xContext ) : OWizardPage( pParent, SchResId(TP_WIZARD_TITLEANDOBJECTS) ) , m_aFT_TitleDescription( this, SchResId( FT_TITLEDESCRIPTION ) ) , m_aFL_Vertical( this, SchResId( FL_VERTICAL ) ) , m_apTitleResources( new TitleResources(this) ) , m_apLegendPositionResources( new LegendPositionResources(this,xContext) ) , m_aFL_Grids( this, SchResId( FL_GRIDS ) ) , m_aCB_Grid_X( this, SchResId( CB_X_SECONDARY ) ) , m_aCB_Grid_Y( this, SchResId( CB_Y_SECONDARY ) ) , m_aCB_Grid_Z( this, SchResId( CB_Z_SECONDARY ) ) , m_xChartModel( xChartModel ) , m_xCC( xContext ) , m_bCommitToModel( true ) , m_aTimerTriggeredControllerLock( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY ) ) { FreeResource(); this->SetText( String( SchResId( STR_PAGE_CHART_ELEMENTS ) ) ); Font aFont( m_aFT_TitleDescription.GetControlFont() ); aFont.SetWeight( WEIGHT_BOLD ); m_aFT_TitleDescription.SetControlFont( aFont ); m_aCB_Grid_X.SetHelpId( HID_SCH_CB_XGRID ); m_aCB_Grid_Y.SetHelpId( HID_SCH_CB_YGRID ); m_aCB_Grid_Z.SetHelpId( HID_SCH_CB_ZGRID ); m_apTitleResources->SetUpdateDataHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_apLegendPositionResources->SetChangeHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_aCB_Grid_X.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_aCB_Grid_Y.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_aCB_Grid_Z.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); } TitlesAndObjectsTabPage::~TitlesAndObjectsTabPage() { } void TitlesAndObjectsTabPage::initializePage() { m_bCommitToModel = false; //init titles { TitleDialogData aTitleInput; aTitleInput.readFromModel( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) ); m_apTitleResources->writeToResources( aTitleInput ); } //init legend { m_apLegendPositionResources->writeToResources( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) ); } //init grid checkboxes { uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( m_xChartModel ); uno::Sequence< sal_Bool > aPossibilityList; uno::Sequence< sal_Bool > aExistenceList; AxisHelper::getAxisOrGridPossibilities( aPossibilityList, xDiagram, sal_False ); AxisHelper::getAxisOrGridExcistence( aExistenceList, xDiagram, sal_False ); m_aCB_Grid_X.Enable( aPossibilityList[0] ); m_aCB_Grid_Y.Enable( aPossibilityList[1] ); m_aCB_Grid_Z.Enable( aPossibilityList[2] ); m_aCB_Grid_X.Check( aExistenceList[0] ); m_aCB_Grid_Y.Check( aExistenceList[1] ); m_aCB_Grid_Z.Check( aExistenceList[2] ); } m_bCommitToModel = true; } sal_Bool TitlesAndObjectsTabPage::commitPage( COMMIT_REASON /*eReason*/ ) { if( m_apTitleResources->IsModified() ) //titles may have changed in the meanwhile commitToModel(); return sal_True;//return false if this page should not be left } void TitlesAndObjectsTabPage::commitToModel() { bool bChanged = false; m_aTimerTriggeredControllerLock.startTimer(); uno::Reference< frame::XModel > xModel( m_xChartModel, uno::UNO_QUERY); ControllerLockGuard aLockedControllers( xModel ); //commit title changes to model { TitleDialogData aTitleOutput; m_apTitleResources->readFromResources( aTitleOutput ); bChanged = bChanged || aTitleOutput.writeDifferenceToModel( xModel, m_xCC ); m_apTitleResources->ClearModifyFlag(); } //commit legend changes to model { bChanged = true; m_apLegendPositionResources->writeToModel( xModel ); } //commit grid changes to model { uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( xModel ); uno::Sequence< sal_Bool > aOldExistenceList; AxisHelper::getAxisOrGridExcistence( aOldExistenceList, xDiagram, sal_False ); uno::Sequence< sal_Bool > aNewExistenceList(aOldExistenceList); aNewExistenceList[0]=m_aCB_Grid_X.IsChecked(); aNewExistenceList[1]=m_aCB_Grid_Y.IsChecked(); aNewExistenceList[2]=m_aCB_Grid_Z.IsChecked(); AxisHelper::changeVisibilityOfGrids( xDiagram , aOldExistenceList, aNewExistenceList, m_xCC ); } } IMPL_LINK( TitlesAndObjectsTabPage, ChangeHdl, void *, EMPTYARG ) { if( m_bCommitToModel ) commitToModel(); return 0; } sal_Bool TitlesAndObjectsTabPage::determineNextButtonState() { return sal_False; } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS chart19 (1.3.44); FILE MERGED 2007/11/20 17:12:15 iha 1.3.44.1: #1163# title for secondary axes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_Wizard_TitlesAndObjects.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2008-02-18 15:52:59 $ * * 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_chart2.hxx" #include "tp_Wizard_TitlesAndObjects.hxx" #include "tp_Wizard_TitlesAndObjects.hrc" #include "Strings.hrc" #include "res_Titles.hxx" #include "res_LegendPosition.hxx" #include "ResId.hxx" #include "HelpIds.hrc" #include "macros.hxx" #include "ChartModelHelper.hxx" #include "AxisHelper.hxx" #include "LegendHelper.hxx" #include "NoWarningThisInCTOR.hxx" #include "ControllerLockGuard.hxx" //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; TitlesAndObjectsTabPage::TitlesAndObjectsTabPage( svt::OWizardMachine* pParent , const uno::Reference< XChartDocument >& xChartModel , const uno::Reference< uno::XComponentContext >& xContext ) : OWizardPage( pParent, SchResId(TP_WIZARD_TITLEANDOBJECTS) ) , m_aFT_TitleDescription( this, SchResId( FT_TITLEDESCRIPTION ) ) , m_aFL_Vertical( this, SchResId( FL_VERTICAL ) ) , m_apTitleResources( new TitleResources(this,false) ) , m_apLegendPositionResources( new LegendPositionResources(this,xContext) ) , m_aFL_Grids( this, SchResId( FL_GRIDS ) ) , m_aCB_Grid_X( this, SchResId( CB_X_SECONDARY ) ) , m_aCB_Grid_Y( this, SchResId( CB_Y_SECONDARY ) ) , m_aCB_Grid_Z( this, SchResId( CB_Z_SECONDARY ) ) , m_xChartModel( xChartModel ) , m_xCC( xContext ) , m_bCommitToModel( true ) , m_aTimerTriggeredControllerLock( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY ) ) { FreeResource(); this->SetText( String( SchResId( STR_PAGE_CHART_ELEMENTS ) ) ); Font aFont( m_aFT_TitleDescription.GetControlFont() ); aFont.SetWeight( WEIGHT_BOLD ); m_aFT_TitleDescription.SetControlFont( aFont ); m_aCB_Grid_X.SetHelpId( HID_SCH_CB_XGRID ); m_aCB_Grid_Y.SetHelpId( HID_SCH_CB_YGRID ); m_aCB_Grid_Z.SetHelpId( HID_SCH_CB_ZGRID ); m_apTitleResources->SetUpdateDataHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_apLegendPositionResources->SetChangeHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_aCB_Grid_X.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_aCB_Grid_Y.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); m_aCB_Grid_Z.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl )); } TitlesAndObjectsTabPage::~TitlesAndObjectsTabPage() { } void TitlesAndObjectsTabPage::initializePage() { m_bCommitToModel = false; //init titles { TitleDialogData aTitleInput; aTitleInput.readFromModel( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) ); m_apTitleResources->writeToResources( aTitleInput ); } //init legend { m_apLegendPositionResources->writeToResources( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) ); } //init grid checkboxes { uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( m_xChartModel ); uno::Sequence< sal_Bool > aPossibilityList; uno::Sequence< sal_Bool > aExistenceList; AxisHelper::getAxisOrGridPossibilities( aPossibilityList, xDiagram, sal_False ); AxisHelper::getAxisOrGridExcistence( aExistenceList, xDiagram, sal_False ); m_aCB_Grid_X.Enable( aPossibilityList[0] ); m_aCB_Grid_Y.Enable( aPossibilityList[1] ); m_aCB_Grid_Z.Enable( aPossibilityList[2] ); m_aCB_Grid_X.Check( aExistenceList[0] ); m_aCB_Grid_Y.Check( aExistenceList[1] ); m_aCB_Grid_Z.Check( aExistenceList[2] ); } m_bCommitToModel = true; } sal_Bool TitlesAndObjectsTabPage::commitPage( COMMIT_REASON /*eReason*/ ) { if( m_apTitleResources->IsModified() ) //titles may have changed in the meanwhile commitToModel(); return sal_True;//return false if this page should not be left } void TitlesAndObjectsTabPage::commitToModel() { bool bChanged = false; m_aTimerTriggeredControllerLock.startTimer(); uno::Reference< frame::XModel > xModel( m_xChartModel, uno::UNO_QUERY); ControllerLockGuard aLockedControllers( xModel ); //commit title changes to model { TitleDialogData aTitleOutput; m_apTitleResources->readFromResources( aTitleOutput ); bChanged = bChanged || aTitleOutput.writeDifferenceToModel( xModel, m_xCC ); m_apTitleResources->ClearModifyFlag(); } //commit legend changes to model { bChanged = true; m_apLegendPositionResources->writeToModel( xModel ); } //commit grid changes to model { uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( xModel ); uno::Sequence< sal_Bool > aOldExistenceList; AxisHelper::getAxisOrGridExcistence( aOldExistenceList, xDiagram, sal_False ); uno::Sequence< sal_Bool > aNewExistenceList(aOldExistenceList); aNewExistenceList[0]=m_aCB_Grid_X.IsChecked(); aNewExistenceList[1]=m_aCB_Grid_Y.IsChecked(); aNewExistenceList[2]=m_aCB_Grid_Z.IsChecked(); AxisHelper::changeVisibilityOfGrids( xDiagram , aOldExistenceList, aNewExistenceList, m_xCC ); } } IMPL_LINK( TitlesAndObjectsTabPage, ChangeHdl, void *, EMPTYARG ) { if( m_bCommitToModel ) commitToModel(); return 0; } sal_Bool TitlesAndObjectsTabPage::determineNextButtonState() { return sal_False; } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "content/common/notification_observer.h" #include "content/common/notification_registrar.h" #include "content/common/notification_service.h" #include "net/base/mock_host_resolver.h" // A base class for tests below. class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryURL, "http://www.example.com"); } void SetUpInProcessBrowserTestFixture() OVERRIDE { // Start up the test server and get us ready for calling the install // API functions. host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); BeginInstallWithManifestFunction::SetIgnoreUserGestureForTests(true); BeginInstallWithManifestFunction::SetAutoConfirmForTests(true); ExtensionInstallUI::DisableFailureUIForTests(); } protected: // Returns a test server URL, but with host 'www.example.com' so it matches // the web store app's extent that we set up via command line flags. GURL GetTestServerURL(const std::string& path) { GURL url = test_server()->GetURL( std::string("files/extensions/api_test/webstore_private/") + path); // Replace the host with 'www.example.com' so it matches the web store // app's extent. GURL::Replacements replace_host; std::string host_str("www.example.com"); replace_host.SetHostStr(host_str); return url.ReplaceComponents(replace_host); } // Navigates to |page| and runs the Extension API test there. bool RunInstallTest(const std::string& page) { GURL crx_url = GetTestServerURL("extension.crx"); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); GURL page_url = GetTestServerURL(page); return RunPageTest(page_url.spec()); } ExtensionService* service() { return browser()->profile()->GetExtensionService(); } }; // Test cases where the user accepts the install confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) { ASSERT_TRUE(RunInstallTest("accepted.html")); } // Now test the case where the user cancels the confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) { BeginInstallWithManifestFunction::SetAutoConfirmForTests(false); ASSERT_TRUE(RunInstallTest("cancelled.html")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallNoGesture) { BeginInstallFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) { ui_test_utils::WindowedNotificationObserver observer( NotificationType::EXTENSION_INSTALL_ERROR, NotificationService::AllSources()); ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html")); observer.Wait(); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) { ui_test_utils::WindowedNotificationObserver observer( NotificationType::EXTENSION_INSTALL_ERROR, NotificationService::AllSources()); ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html")); observer.Wait(); } <commit_msg>Mark ExtensionWebstorePrivateApiTest.InstallAccepted as FLAKY.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "content/common/notification_observer.h" #include "content/common/notification_registrar.h" #include "content/common/notification_service.h" #include "net/base/mock_host_resolver.h" // A base class for tests below. class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryURL, "http://www.example.com"); } void SetUpInProcessBrowserTestFixture() OVERRIDE { // Start up the test server and get us ready for calling the install // API functions. host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); BeginInstallWithManifestFunction::SetIgnoreUserGestureForTests(true); BeginInstallWithManifestFunction::SetAutoConfirmForTests(true); ExtensionInstallUI::DisableFailureUIForTests(); } protected: // Returns a test server URL, but with host 'www.example.com' so it matches // the web store app's extent that we set up via command line flags. GURL GetTestServerURL(const std::string& path) { GURL url = test_server()->GetURL( std::string("files/extensions/api_test/webstore_private/") + path); // Replace the host with 'www.example.com' so it matches the web store // app's extent. GURL::Replacements replace_host; std::string host_str("www.example.com"); replace_host.SetHostStr(host_str); return url.ReplaceComponents(replace_host); } // Navigates to |page| and runs the Extension API test there. bool RunInstallTest(const std::string& page) { GURL crx_url = GetTestServerURL("extension.crx"); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); GURL page_url = GetTestServerURL(page); return RunPageTest(page_url.spec()); } ExtensionService* service() { return browser()->profile()->GetExtensionService(); } }; // TODO(asargent) - flaky; see crbug.com/80606. // Test cases where the user accepts the install confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FLAKY_InstallAccepted) { ASSERT_TRUE(RunInstallTest("accepted.html")); } // Now test the case where the user cancels the confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) { BeginInstallWithManifestFunction::SetAutoConfirmForTests(false); ASSERT_TRUE(RunInstallTest("cancelled.html")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallNoGesture) { BeginInstallFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) { ui_test_utils::WindowedNotificationObserver observer( NotificationType::EXTENSION_INSTALL_ERROR, NotificationService::AllSources()); ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html")); observer.Wait(); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) { ui_test_utils::WindowedNotificationObserver observer( NotificationType::EXTENSION_INSTALL_ERROR, NotificationService::AllSources()); ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html")); observer.Wait(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_install_dialog.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/browser/extensions/webstore_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/test_launcher_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/gpu/gpu_blacklist.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "net/base/mock_host_resolver.h" #include "ui/gfx/gl/gl_switches.h" using namespace extension_function_test_utils; namespace { class WebstoreInstallListener : public WebstoreInstaller::Delegate { public: WebstoreInstallListener() : received_failure_(false), received_success_(false), waiting_(false) {} void OnExtensionInstallSuccess(const std::string& id) OVERRIDE; void OnExtensionInstallFailure(const std::string& id, const std::string& error) OVERRIDE; void Wait(); bool received_failure() const { return received_failure_; } bool received_success() const { return received_success_; } const std::string& id() const { return id_; } const std::string& error() const { return error_; } private: bool received_failure_; bool received_success_; bool waiting_; std::string id_; std::string error_; }; void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) { received_success_ = true; id_ = id; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::OnExtensionInstallFailure( const std::string& id, const std::string& error) { received_failure_ = true; id_ = id; error_ = error; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::Wait() { if (received_success_ || received_failure_) return; waiting_ = true; ui_test_utils::RunMessageLoop(); } } // namespace // A base class for tests below. class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII( switches::kAppsGalleryURL, "http://www.example.com"); command_line->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); } void SetUpInProcessBrowserTestFixture() OVERRIDE { // Start up the test server and get us ready for calling the install // API functions. host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ExtensionInstallUI::DisableFailureUIForTests(); } protected: // Returns a test server URL, but with host 'www.example.com' so it matches // the web store app's extent that we set up via command line flags. GURL GetTestServerURL(const std::string& path) { GURL url = test_server()->GetURL( std::string("files/extensions/api_test/webstore_private/") + path); // Replace the host with 'www.example.com' so it matches the web store // app's extent. GURL::Replacements replace_host; std::string host_str("www.example.com"); replace_host.SetHostStr(host_str); return url.ReplaceComponents(replace_host); } // Navigates to |page| and runs the Extension API test there. Any downloads // of extensions will return the contents of |crx_file|. bool RunInstallTest(const std::string& page, const std::string& crx_file) { GURL crx_url = GetTestServerURL(crx_file); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); GURL page_url = GetTestServerURL(page); return RunPageTest(page_url.spec()); } ExtensionService* service() { return browser()->profile()->GetExtensionService(); } }; class ExtensionWebstorePrivateBundleTest : public ExtensionWebstorePrivateApiTest { public: void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture(); // The test server needs to have already started, so setup the switch here // rather than in SetUpCommandLine. CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryDownloadURL, GetTestServerURL("bundle/%s.crx").spec()); PackCRX("begfmnajjkbjdgmffnjaojchoncnmngg"); PackCRX("bmfoocgfinpmkmlbjhcbofejhkhlbchk"); PackCRX("mpneghmdnmaolkljkipbhaienajcflfe"); } void TearDownInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture(); for (size_t i = 0; i < test_crx_.size(); ++i) ASSERT_TRUE(file_util::Delete(test_crx_[i], false)); } private: void PackCRX(const std::string& id) { FilePath data_path = test_data_dir_.AppendASCII("webstore_private/bundle"); FilePath dir_path = data_path.AppendASCII(id); FilePath pem_path = data_path.AppendASCII(id + ".pem"); FilePath crx_path = data_path.AppendASCII(id + ".crx"); FilePath destination = PackExtensionWithOptions( dir_path, crx_path, pem_path, FilePath()); ASSERT_FALSE(destination.empty()); ASSERT_EQ(destination, crx_path); test_crx_.push_back(destination); } std::vector<FilePath> test_crx_; }; class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // In linux, we need to launch GPU process to decide if WebGL is allowed. // Run it on top of osmesa to avoid bot driver issues. #if defined(OS_LINUX) CHECK(test_launcher_utils::OverrideGLImplementation( command_line, gfx::kGLImplementationOSMesaName)) << "kUseGL must not be set multiple times!"; #endif } protected: void RunTest(bool webgl_allowed) { static const char kEmptyArgs[] = "[]"; static const char kWebGLStatusAllowed[] = "webgl_allowed"; static const char kWebGLStatusBlocked[] = "webgl_blocked"; scoped_ptr<base::Value> result(RunFunctionAndReturnResult( new GetWebGLStatusFunction(), kEmptyArgs, browser())); EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); StringValue* value = static_cast<StringValue*>(result.get()); std::string webgl_status = ""; EXPECT_TRUE(value && value->GetAsString(&webgl_status)); EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked, webgl_status.c_str()); } }; // Test cases where the user accepts the install confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); } // Test having the default download directory missing. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) { // Set a non-existent directory as the download path. ScopedTempDir temp_dir; EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath missing_directory = temp_dir.Take(); EXPECT_TRUE(file_util::Delete(missing_directory, true)); WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory); // Now run the install test, which should succeed. ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); // Cleanup. if (file_util::DirectoryExists(missing_directory)) EXPECT_TRUE(file_util::Delete(missing_directory, true)); } // Tests passing a localized name. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallLocalized) { ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx")); } // Now test the case where the user cancels the confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) { CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "cancel"); ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx")); listener.Wait(); ASSERT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx")); listener.Wait(); EXPECT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } // Tests that we can request an app installed bubble (instead of the default // UI when an app is installed). IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, AppInstallBubble) { WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx")); listener.Wait(); ASSERT_TRUE(listener.received_success()); ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id()); } // Tests using the iconUrl parameter to the install function. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IconUrl) { ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx")); } // Tests using silentlyInstall to install extensions. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest, SilentlyInstall) { WebstorePrivateApi::SetTrustTestIDsForTesting(true); ASSERT_TRUE(RunPageTest(GetTestServerURL("silently_install.html").spec())); } // Tests getWebGLStatus function when WebGL is allowed. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) { bool webgl_allowed = true; RunTest(webgl_allowed); } // Tests getWebGLStatus function when WebGL is blacklisted. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) { static const std::string json_blacklist = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"1.0\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0")); GpuBlacklist* blacklist = new GpuBlacklist("1.0"); ASSERT_TRUE(blacklist->LoadGpuBlacklist( json_blacklist, GpuBlacklist::kAllOs)); GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist); GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags(); EXPECT_EQ( flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl)); bool webgl_allowed = false; RunTest(webgl_allowed); } <commit_msg>Mark - ExtensionWebstorePrivateApiTest.AppInstallBubble, - ExtensionWebstorePrivateApiTest.InstallLocalized, - ExtensionWebstorePrivateApiTest.SilentlyInstall as flaky.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_install_dialog.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/browser/extensions/webstore_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/test_launcher_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/gpu/gpu_blacklist.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "net/base/mock_host_resolver.h" #include "ui/gfx/gl/gl_switches.h" using namespace extension_function_test_utils; namespace { class WebstoreInstallListener : public WebstoreInstaller::Delegate { public: WebstoreInstallListener() : received_failure_(false), received_success_(false), waiting_(false) {} void OnExtensionInstallSuccess(const std::string& id) OVERRIDE; void OnExtensionInstallFailure(const std::string& id, const std::string& error) OVERRIDE; void Wait(); bool received_failure() const { return received_failure_; } bool received_success() const { return received_success_; } const std::string& id() const { return id_; } const std::string& error() const { return error_; } private: bool received_failure_; bool received_success_; bool waiting_; std::string id_; std::string error_; }; void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) { received_success_ = true; id_ = id; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::OnExtensionInstallFailure( const std::string& id, const std::string& error) { received_failure_ = true; id_ = id; error_ = error; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::Wait() { if (received_success_ || received_failure_) return; waiting_ = true; ui_test_utils::RunMessageLoop(); } } // namespace // A base class for tests below. class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII( switches::kAppsGalleryURL, "http://www.example.com"); command_line->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); } void SetUpInProcessBrowserTestFixture() OVERRIDE { // Start up the test server and get us ready for calling the install // API functions. host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ExtensionInstallUI::DisableFailureUIForTests(); } protected: // Returns a test server URL, but with host 'www.example.com' so it matches // the web store app's extent that we set up via command line flags. GURL GetTestServerURL(const std::string& path) { GURL url = test_server()->GetURL( std::string("files/extensions/api_test/webstore_private/") + path); // Replace the host with 'www.example.com' so it matches the web store // app's extent. GURL::Replacements replace_host; std::string host_str("www.example.com"); replace_host.SetHostStr(host_str); return url.ReplaceComponents(replace_host); } // Navigates to |page| and runs the Extension API test there. Any downloads // of extensions will return the contents of |crx_file|. bool RunInstallTest(const std::string& page, const std::string& crx_file) { GURL crx_url = GetTestServerURL(crx_file); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); GURL page_url = GetTestServerURL(page); return RunPageTest(page_url.spec()); } ExtensionService* service() { return browser()->profile()->GetExtensionService(); } }; class ExtensionWebstorePrivateBundleTest : public ExtensionWebstorePrivateApiTest { public: void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture(); // The test server needs to have already started, so setup the switch here // rather than in SetUpCommandLine. CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryDownloadURL, GetTestServerURL("bundle/%s.crx").spec()); PackCRX("begfmnajjkbjdgmffnjaojchoncnmngg"); PackCRX("bmfoocgfinpmkmlbjhcbofejhkhlbchk"); PackCRX("mpneghmdnmaolkljkipbhaienajcflfe"); } void TearDownInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture(); for (size_t i = 0; i < test_crx_.size(); ++i) ASSERT_TRUE(file_util::Delete(test_crx_[i], false)); } private: void PackCRX(const std::string& id) { FilePath data_path = test_data_dir_.AppendASCII("webstore_private/bundle"); FilePath dir_path = data_path.AppendASCII(id); FilePath pem_path = data_path.AppendASCII(id + ".pem"); FilePath crx_path = data_path.AppendASCII(id + ".crx"); FilePath destination = PackExtensionWithOptions( dir_path, crx_path, pem_path, FilePath()); ASSERT_FALSE(destination.empty()); ASSERT_EQ(destination, crx_path); test_crx_.push_back(destination); } std::vector<FilePath> test_crx_; }; class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // In linux, we need to launch GPU process to decide if WebGL is allowed. // Run it on top of osmesa to avoid bot driver issues. #if defined(OS_LINUX) CHECK(test_launcher_utils::OverrideGLImplementation( command_line, gfx::kGLImplementationOSMesaName)) << "kUseGL must not be set multiple times!"; #endif } protected: void RunTest(bool webgl_allowed) { static const char kEmptyArgs[] = "[]"; static const char kWebGLStatusAllowed[] = "webgl_allowed"; static const char kWebGLStatusBlocked[] = "webgl_blocked"; scoped_ptr<base::Value> result(RunFunctionAndReturnResult( new GetWebGLStatusFunction(), kEmptyArgs, browser())); EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); StringValue* value = static_cast<StringValue*>(result.get()); std::string webgl_status = ""; EXPECT_TRUE(value && value->GetAsString(&webgl_status)); EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked, webgl_status.c_str()); } }; // Test cases where the user accepts the install confirmation dialog. // // flaky: http://crbug.com/111308 IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FLAKY_InstallAccepted) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); } // Test having the default download directory missing. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) { // Set a non-existent directory as the download path. ScopedTempDir temp_dir; EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath missing_directory = temp_dir.Take(); EXPECT_TRUE(file_util::Delete(missing_directory, true)); WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory); // Now run the install test, which should succeed. ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); // Cleanup. if (file_util::DirectoryExists(missing_directory)) EXPECT_TRUE(file_util::Delete(missing_directory, true)); } // Tests passing a localized name. // // flaky: http://crbug.com/111308 IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FLAKY_InstallLocalized) { ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx")); } // Now test the case where the user cancels the confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) { CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "cancel"); ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx")); listener.Wait(); ASSERT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx")); listener.Wait(); EXPECT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } // Tests that we can request an app installed bubble (instead of the default // UI when an app is installed). // // flaky: http://crbug.com/111308 IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FLAKY_AppInstallBubble) { WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx")); listener.Wait(); ASSERT_TRUE(listener.received_success()); ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id()); } // Tests using the iconUrl parameter to the install function. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IconUrl) { ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx")); } // Tests using silentlyInstall to install extensions. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest, SilentlyInstall) { WebstorePrivateApi::SetTrustTestIDsForTesting(true); ASSERT_TRUE(RunPageTest(GetTestServerURL("silently_install.html").spec())); } // Tests getWebGLStatus function when WebGL is allowed. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) { bool webgl_allowed = true; RunTest(webgl_allowed); } // Tests getWebGLStatus function when WebGL is blacklisted. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) { static const std::string json_blacklist = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"1.0\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0")); GpuBlacklist* blacklist = new GpuBlacklist("1.0"); ASSERT_TRUE(blacklist->LoadGpuBlacklist( json_blacklist, GpuBlacklist::kAllOs)); GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist); GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags(); EXPECT_EQ( flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl)); bool webgl_allowed = false; RunTest(webgl_allowed); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/notifier/communicator/ssl_socket_adapter.h" #include "base/compiler_specific.h" #include "base/message_loop.h" #include "chrome/browser/net/url_request_context_getter.h" #include "chrome/browser/profile.h" #include "net/base/address_list.h" #include "net/base/net_errors.h" #include "net/base/ssl_config_service.h" #include "net/base/sys_addrinfo.h" #include "net/socket/client_socket_factory.h" #include "net/url_request/url_request_context.h" namespace notifier { namespace { // Convert values from <errno.h> to values from "net/base/net_errors.h" int MapPosixError(int err) { // There are numerous posix error codes, but these are the ones we thus far // find interesting. switch (err) { case EAGAIN: #if EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif return net::ERR_IO_PENDING; case ENETDOWN: return net::ERR_INTERNET_DISCONNECTED; case ETIMEDOUT: return net::ERR_TIMED_OUT; case ECONNRESET: case ENETRESET: // Related to keep-alive return net::ERR_CONNECTION_RESET; case ECONNABORTED: return net::ERR_CONNECTION_ABORTED; case ECONNREFUSED: return net::ERR_CONNECTION_REFUSED; case EHOSTUNREACH: case ENETUNREACH: return net::ERR_ADDRESS_UNREACHABLE; case EADDRNOTAVAIL: return net::ERR_ADDRESS_INVALID; case 0: return net::OK; default: LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED"; return net::ERR_FAILED; } } } // namespace SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) { return new SSLSocketAdapter(socket); } SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket) : SSLAdapter(socket), ignore_bad_cert_(false), ALLOW_THIS_IN_INITIALIZER_LIST( connected_callback_(this, &SSLSocketAdapter::OnConnected)), ALLOW_THIS_IN_INITIALIZER_LIST( io_callback_(this, &SSLSocketAdapter::OnIO)), ssl_connected_(false), state_(STATE_NONE) { transport_socket_ = new TransportSocket(socket, this); } int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) { DCHECK(!restartable); hostname_ = hostname; if (socket_->GetState() != Socket::CS_CONNECTED) { state_ = STATE_SSL_WAIT; return 0; } else { return BeginSSL(); } } int SSLSocketAdapter::BeginSSL() { if (!MessageLoop::current()) { // Certificate verification is done via the Chrome message loop. // Without this check, if we don't have a chrome message loop the // SSL connection just hangs silently. LOG(DFATAL) << "Chrome message loop (needed by SSL certificate " << "verification) does not exist"; return net::ERR_UNEXPECTED; } // SSLConfigService is not thread-safe, and the default values for SSLConfig // are correct for us, so we don't use the config service to initialize this // object. net::SSLConfig ssl_config; transport_socket_->set_addr(talk_base::SocketAddress(hostname_.c_str())); ssl_socket_.reset( net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( transport_socket_, hostname_.c_str(), ssl_config)); int result = ssl_socket_->Connect(&connected_callback_, NULL); if (result == net::ERR_IO_PENDING || result == net::OK) { return 0; } else { LOG(ERROR) << "Could not start SSL: " << net::ErrorToString(result); return result; } } int SSLSocketAdapter::Send(const void* buf, size_t len) { if (!ssl_connected_) { return AsyncSocketAdapter::Send(buf, len); } else { scoped_refptr<net::IOBuffer> transport_buf = new net::IOBuffer(len); memcpy(transport_buf->data(), buf, len); int result = ssl_socket_->Write(transport_buf, len, NULL); if (result == net::ERR_IO_PENDING) { SetError(EWOULDBLOCK); } transport_buf = NULL; return result; } } int SSLSocketAdapter::Recv(void* buf, size_t len) { if (!ssl_connected_) { return AsyncSocketAdapter::Recv(buf, len); } switch (state_) { case STATE_NONE: { transport_buf_ = new net::IOBuffer(len); int result = ssl_socket_->Read(transport_buf_, len, &io_callback_); if (result >= 0) { memcpy(buf, transport_buf_->data(), len); } if (result == net::ERR_IO_PENDING) { state_ = STATE_READ; SetError(EWOULDBLOCK); } else { if (result < 0) { SetError(result); LOG(INFO) << "Socket error " << result; } transport_buf_ = NULL; } return result; } case STATE_READ_COMPLETE: memcpy(buf, transport_buf_->data(), len); transport_buf_ = NULL; state_ = STATE_NONE; return data_transferred_; case STATE_READ: case STATE_WRITE: case STATE_WRITE_COMPLETE: case STATE_SSL_WAIT: SetError(EWOULDBLOCK); return -1; default: NOTREACHED(); break; } return -1; } void SSLSocketAdapter::OnConnected(int result) { if (result == net::OK) { ssl_connected_ = true; OnConnectEvent(this); } } void SSLSocketAdapter::OnIO(int result) { switch (state_) { case STATE_READ: state_ = STATE_READ_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnReadEvent(this); break; case STATE_WRITE: state_ = STATE_WRITE_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnWriteEvent(this); break; case STATE_NONE: case STATE_READ_COMPLETE: case STATE_WRITE_COMPLETE: case STATE_SSL_WAIT: default: NOTREACHED(); break; } } void SSLSocketAdapter::OnReadEvent(talk_base::AsyncSocket* socket) { if (!transport_socket_->OnReadEvent(socket)) AsyncSocketAdapter::OnReadEvent(socket); } void SSLSocketAdapter::OnWriteEvent(talk_base::AsyncSocket* socket) { if (!transport_socket_->OnWriteEvent(socket)) AsyncSocketAdapter::OnWriteEvent(socket); } void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) { if (state_ != STATE_SSL_WAIT) { AsyncSocketAdapter::OnConnectEvent(socket); } else { state_ = STATE_NONE; int result = BeginSSL(); if (0 != result) { // TODO(zork): Handle this case gracefully. LOG(WARNING) << "BeginSSL() failed with " << result; } } } TransportSocket::TransportSocket(talk_base::AsyncSocket* socket, SSLSocketAdapter *ssl_adapter) : connect_callback_(NULL), read_callback_(NULL), write_callback_(NULL), read_buffer_len_(0), write_buffer_len_(0), socket_(socket) { socket_->SignalConnectEvent.connect(this, &TransportSocket::OnConnectEvent); } int TransportSocket::Connect(net::CompletionCallback* callback, const net::BoundNetLog& /* net_log */) { connect_callback_ = callback; return socket_->Connect(addr_); } void TransportSocket::Disconnect() { socket_->Close(); } bool TransportSocket::IsConnected() const { return (socket_->GetState() == talk_base::Socket::CS_CONNECTED); } bool TransportSocket::IsConnectedAndIdle() const { // Not implemented. NOTREACHED(); return false; } int TransportSocket::GetPeerAddress(net::AddressList* address) const { talk_base::SocketAddress socket_address = socket_->GetRemoteAddress(); // libjingle supports only IPv4 addresses. sockaddr_in ipv4addr; socket_address.ToSockAddr(&ipv4addr); struct addrinfo ai; memset(&ai, 0, sizeof(ai)); ai.ai_family = ipv4addr.sin_family; ai.ai_socktype = SOCK_STREAM; ai.ai_protocol = IPPROTO_TCP; ai.ai_addr = reinterpret_cast<struct sockaddr*>(&ipv4addr); ai.ai_addrlen = sizeof(ipv4addr); address->Copy(&ai, false); return net::OK; } int TransportSocket::Read(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!read_callback_); DCHECK(!read_buffer_.get()); int result = socket_->Recv(buf->data(), buf_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buf; read_buffer_len_ = buf_len; } } return result; } int TransportSocket::Write(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!write_callback_); DCHECK(!write_buffer_.get()); int result = socket_->Send(buf->data(), buf_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buf; write_buffer_len_ = buf_len; } } return result; } bool TransportSocket::SetReceiveBufferSize(int32 size) { // Not implemented. return false; } bool TransportSocket::SetSendBufferSize(int32 size) { // Not implemented. return false; } void TransportSocket::OnConnectEvent(talk_base::AsyncSocket * socket) { if (connect_callback_) { net::CompletionCallback *callback = connect_callback_; connect_callback_ = NULL; callback->RunWithParams(Tuple1<int>(MapPosixError(socket_->GetError()))); } } bool TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) { if (read_callback_) { DCHECK(read_buffer_.get()); net::CompletionCallback* callback = read_callback_; scoped_refptr<net::IOBuffer> buffer = read_buffer_; int buffer_len = read_buffer_len_; read_callback_ = NULL; read_buffer_ = NULL; read_buffer_len_ = 0; int result = socket_->Recv(buffer->data(), buffer_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buffer; read_buffer_len_ = buffer_len; return true; } } callback->RunWithParams(Tuple1<int>(result)); return true; } else { return false; } } bool TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) { if (write_callback_) { DCHECK(write_buffer_.get()); net::CompletionCallback* callback = write_callback_; scoped_refptr<net::IOBuffer> buffer = write_buffer_; int buffer_len = write_buffer_len_; write_callback_ = NULL; write_buffer_ = NULL; write_buffer_len_ = 0; int result = socket_->Send(buffer->data(), buffer_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buffer; write_buffer_len_ = buffer_len; return true; } } callback->RunWithParams(Tuple1<int>(result)); return true; } else { return false; } } } // namespace notifier <commit_msg>Add logging statements to ssl_socket_adapter.cc to watch for unexpected conditions.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/notifier/communicator/ssl_socket_adapter.h" #include "base/compiler_specific.h" #include "base/message_loop.h" #include "chrome/browser/net/url_request_context_getter.h" #include "chrome/browser/profile.h" #include "net/base/address_list.h" #include "net/base/net_errors.h" #include "net/base/ssl_config_service.h" #include "net/base/sys_addrinfo.h" #include "net/socket/client_socket_factory.h" #include "net/url_request/url_request_context.h" namespace notifier { namespace { // Convert values from <errno.h> to values from "net/base/net_errors.h" int MapPosixError(int err) { // There are numerous posix error codes, but these are the ones we thus far // find interesting. switch (err) { case EAGAIN: #if EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif return net::ERR_IO_PENDING; case ENETDOWN: return net::ERR_INTERNET_DISCONNECTED; case ETIMEDOUT: return net::ERR_TIMED_OUT; case ECONNRESET: case ENETRESET: // Related to keep-alive return net::ERR_CONNECTION_RESET; case ECONNABORTED: return net::ERR_CONNECTION_ABORTED; case ECONNREFUSED: return net::ERR_CONNECTION_REFUSED; case EHOSTUNREACH: case ENETUNREACH: return net::ERR_ADDRESS_UNREACHABLE; case EADDRNOTAVAIL: return net::ERR_ADDRESS_INVALID; case 0: return net::OK; default: LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED"; return net::ERR_FAILED; } } } // namespace SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) { return new SSLSocketAdapter(socket); } SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket) : SSLAdapter(socket), ignore_bad_cert_(false), ALLOW_THIS_IN_INITIALIZER_LIST( connected_callback_(this, &SSLSocketAdapter::OnConnected)), ALLOW_THIS_IN_INITIALIZER_LIST( io_callback_(this, &SSLSocketAdapter::OnIO)), ssl_connected_(false), state_(STATE_NONE) { transport_socket_ = new TransportSocket(socket, this); } int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) { DCHECK(!restartable); hostname_ = hostname; if (socket_->GetState() != Socket::CS_CONNECTED) { state_ = STATE_SSL_WAIT; return 0; } else { return BeginSSL(); } } int SSLSocketAdapter::BeginSSL() { if (!MessageLoop::current()) { // Certificate verification is done via the Chrome message loop. // Without this check, if we don't have a chrome message loop the // SSL connection just hangs silently. LOG(DFATAL) << "Chrome message loop (needed by SSL certificate " << "verification) does not exist"; return net::ERR_UNEXPECTED; } // SSLConfigService is not thread-safe, and the default values for SSLConfig // are correct for us, so we don't use the config service to initialize this // object. net::SSLConfig ssl_config; transport_socket_->set_addr(talk_base::SocketAddress(hostname_.c_str())); ssl_socket_.reset( net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( transport_socket_, hostname_.c_str(), ssl_config)); int result = ssl_socket_->Connect(&connected_callback_, NULL); if (result == net::ERR_IO_PENDING || result == net::OK) { return 0; } else { LOG(ERROR) << "Could not start SSL: " << net::ErrorToString(result); return result; } } int SSLSocketAdapter::Send(const void* buf, size_t len) { if (!ssl_connected_) { return AsyncSocketAdapter::Send(buf, len); } else { scoped_refptr<net::IOBuffer> transport_buf = new net::IOBuffer(len); memcpy(transport_buf->data(), buf, len); int result = ssl_socket_->Write(transport_buf, len, NULL); if (result == net::ERR_IO_PENDING) { SetError(EWOULDBLOCK); } transport_buf = NULL; return result; } } int SSLSocketAdapter::Recv(void* buf, size_t len) { if (!ssl_connected_) { return AsyncSocketAdapter::Recv(buf, len); } switch (state_) { case STATE_NONE: { transport_buf_ = new net::IOBuffer(len); int result = ssl_socket_->Read(transport_buf_, len, &io_callback_); if (result >= 0) { memcpy(buf, transport_buf_->data(), len); } if (result == net::ERR_IO_PENDING) { state_ = STATE_READ; SetError(EWOULDBLOCK); } else { if (result < 0) { SetError(result); LOG(INFO) << "Socket error " << result; } transport_buf_ = NULL; } return result; } case STATE_READ_COMPLETE: memcpy(buf, transport_buf_->data(), len); transport_buf_ = NULL; state_ = STATE_NONE; return data_transferred_; case STATE_READ: case STATE_WRITE: case STATE_WRITE_COMPLETE: case STATE_SSL_WAIT: SetError(EWOULDBLOCK); return -1; default: NOTREACHED(); break; } return -1; } void SSLSocketAdapter::OnConnected(int result) { if (result == net::OK) { ssl_connected_ = true; OnConnectEvent(this); } else { LOG(WARNING) << "OnConnected failed with error " << result; } } void SSLSocketAdapter::OnIO(int result) { switch (state_) { case STATE_READ: state_ = STATE_READ_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnReadEvent(this); break; case STATE_WRITE: state_ = STATE_WRITE_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnWriteEvent(this); break; case STATE_NONE: case STATE_READ_COMPLETE: case STATE_WRITE_COMPLETE: case STATE_SSL_WAIT: default: NOTREACHED(); break; } } void SSLSocketAdapter::OnReadEvent(talk_base::AsyncSocket* socket) { if (!transport_socket_->OnReadEvent(socket)) AsyncSocketAdapter::OnReadEvent(socket); } void SSLSocketAdapter::OnWriteEvent(talk_base::AsyncSocket* socket) { if (!transport_socket_->OnWriteEvent(socket)) AsyncSocketAdapter::OnWriteEvent(socket); } void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) { if (state_ != STATE_SSL_WAIT) { AsyncSocketAdapter::OnConnectEvent(socket); } else { state_ = STATE_NONE; int result = BeginSSL(); if (0 != result) { // TODO(zork): Handle this case gracefully. LOG(WARNING) << "BeginSSL() failed with " << result; } } } TransportSocket::TransportSocket(talk_base::AsyncSocket* socket, SSLSocketAdapter *ssl_adapter) : connect_callback_(NULL), read_callback_(NULL), write_callback_(NULL), read_buffer_len_(0), write_buffer_len_(0), socket_(socket) { socket_->SignalConnectEvent.connect(this, &TransportSocket::OnConnectEvent); } int TransportSocket::Connect(net::CompletionCallback* callback, const net::BoundNetLog& /* net_log */) { connect_callback_ = callback; return socket_->Connect(addr_); } void TransportSocket::Disconnect() { socket_->Close(); } bool TransportSocket::IsConnected() const { return (socket_->GetState() == talk_base::Socket::CS_CONNECTED); } bool TransportSocket::IsConnectedAndIdle() const { // Not implemented. NOTREACHED(); return false; } int TransportSocket::GetPeerAddress(net::AddressList* address) const { talk_base::SocketAddress socket_address = socket_->GetRemoteAddress(); // libjingle supports only IPv4 addresses. sockaddr_in ipv4addr; socket_address.ToSockAddr(&ipv4addr); struct addrinfo ai; memset(&ai, 0, sizeof(ai)); ai.ai_family = ipv4addr.sin_family; ai.ai_socktype = SOCK_STREAM; ai.ai_protocol = IPPROTO_TCP; ai.ai_addr = reinterpret_cast<struct sockaddr*>(&ipv4addr); ai.ai_addrlen = sizeof(ipv4addr); address->Copy(&ai, false); return net::OK; } int TransportSocket::Read(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!read_callback_); DCHECK(!read_buffer_.get()); int result = socket_->Recv(buf->data(), buf_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buf; read_buffer_len_ = buf_len; } } return result; } int TransportSocket::Write(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!write_callback_); DCHECK(!write_buffer_.get()); int result = socket_->Send(buf->data(), buf_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buf; write_buffer_len_ = buf_len; } } return result; } bool TransportSocket::SetReceiveBufferSize(int32 size) { // Not implemented. return false; } bool TransportSocket::SetSendBufferSize(int32 size) { // Not implemented. return false; } void TransportSocket::OnConnectEvent(talk_base::AsyncSocket * socket) { if (connect_callback_) { net::CompletionCallback *callback = connect_callback_; connect_callback_ = NULL; callback->RunWithParams(Tuple1<int>(MapPosixError(socket_->GetError()))); } else { LOG(WARNING) << "OnConnectEvent called with no callback."; } } bool TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) { if (read_callback_) { DCHECK(read_buffer_.get()); net::CompletionCallback* callback = read_callback_; scoped_refptr<net::IOBuffer> buffer = read_buffer_; int buffer_len = read_buffer_len_; read_callback_ = NULL; read_buffer_ = NULL; read_buffer_len_ = 0; int result = socket_->Recv(buffer->data(), buffer_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buffer; read_buffer_len_ = buffer_len; return true; } } callback->RunWithParams(Tuple1<int>(result)); return true; } else { LOG(WARNING) << "OnReadEvent called with no callback."; return false; } } bool TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) { if (write_callback_) { DCHECK(write_buffer_.get()); net::CompletionCallback* callback = write_callback_; scoped_refptr<net::IOBuffer> buffer = write_buffer_; int buffer_len = write_buffer_len_; write_callback_ = NULL; write_buffer_ = NULL; write_buffer_len_ = 0; int result = socket_->Send(buffer->data(), buffer_len); if (result < 0) { result = MapPosixError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buffer; write_buffer_len_ = buffer_len; return true; } } callback->RunWithParams(Tuple1<int>(result)); return true; } else { LOG(WARNING) << "OnWriteEvent called with no callback."; return false; } } } // namespace notifier <|endoftext|>
<commit_before>#include <iostream> #include <boost/foreach.hpp> #include <libport/package-info.hh> namespace libport { PackageInfo::PackageInfo () : map_() { } PackageInfo::data_type PackageInfo::name_version_revision() const { return (get ("name") + " version " + get ("version") + " rev. " + get ("revision")); } PackageInfo::data_type PackageInfo::signature() const { return ( get ("name") + " version " + get ("version") + " rev. " + get ("revision") + " (C) " + get ("copyright-years") + " " + get ("copyright-holder") ); } PackageInfo::data_type& PackageInfo::operator[](const key_type& k) { return map_[k]; } const PackageInfo::data_type& PackageInfo::get(const key_type& k) const { return map_.find(k)->second; } std::ostream& PackageInfo::dump(std::ostream& o) const { bool not_first = false; BOOST_FOREACH(value_type p, map_) o << (not_first++ ? ", " : "") << p.first << " = " << p.second; return o; } std::ostream& operator<<(std::ostream& o, const PackageInfo& p) { return o << p.signature(); } } <commit_msg>Stylistic changes.<commit_after>#include <iostream> #include <libport/foreach.hh> #include <libport/package-info.hh> namespace libport { PackageInfo::PackageInfo () : map_() { } PackageInfo::data_type PackageInfo::name_version_revision() const { return (get ("name") + " version " + get ("version") + " rev. " + get ("revision")); } PackageInfo::data_type PackageInfo::signature() const { return ( get ("name") + " version " + get ("version") + " rev. " + get ("revision") + " (C) " + get ("copyright-years") + " " + get ("copyright-holder") ); } PackageInfo::data_type& PackageInfo::operator[](const key_type& k) { return map_[k]; } const PackageInfo::data_type& PackageInfo::get(const key_type& k) const { return map_.find(k)->second; } std::ostream& PackageInfo::dump(std::ostream& o) const { bool tail = false; foreach(value_type p, map_) o << (tail++ ? ", " : "") << p.first << " = " << p.second; return o; } std::ostream& operator<<(std::ostream& o, const PackageInfo& p) { return o << p.signature(); } } <|endoftext|>
<commit_before>#include "dreal/contractor/contractor.h" #include <algorithm> #include <utility> #include "dreal/contractor/contractor_cell.h" #include "dreal/contractor/contractor_fixpoint.h" #include "dreal/contractor/contractor_forall.h" #include "dreal/contractor/contractor_ibex_fwdbwd.h" #include "dreal/contractor/contractor_ibex_polytope.h" #include "dreal/contractor/contractor_id.h" #include "dreal/contractor/contractor_integer.h" #include "dreal/contractor/contractor_join.h" #include "dreal/contractor/contractor_seq.h" #include "dreal/contractor/contractor_worklist_fixpoint.h" using std::any_of; using std::make_shared; using std::move; using std::ostream; using std::shared_ptr; using std::vector; namespace dreal { namespace { // Flattens contractors and filters out ID contractors. vector<Contractor> Flatten(const vector<Contractor>& contractors) { vector<Contractor> vec; vec.reserve(contractors.size()); for (const Contractor& contractor : contractors) { const Contractor::Kind kind{contractor.kind()}; if (kind == Contractor::Kind::ID) { // Skip if contractor == ID. continue; } else if (kind == Contractor::Kind::SEQ) { // Flatten it out if contractor == SEQ. const vector<Contractor>& contractors_inside{ to_seq(contractor)->contractors()}; vec.insert(vec.end(), contractors_inside.begin(), contractors_inside.end()); } else { vec.push_back(contractor); } } return vec; } } // namespace Contractor::Contractor() : ptr_{make_shared<ContractorId>()} {} Contractor::Contractor(const shared_ptr<ContractorCell>& ptr) : ptr_(ptr) {} const ibex::BitSet& Contractor::input() const { return ptr_->input(); } void Contractor::Prune(ContractorStatus* cs) const { ptr_->Prune(cs); } Contractor::Kind Contractor::kind() const { return ptr_->kind(); } Contractor make_contractor_id() { return Contractor{}; } Contractor make_contractor_integer(const Box& box) { if (any_of(box.variables().begin(), box.variables().end(), [](const Variable& v) { const Variable::Type type{v.get_type()}; return type == Variable::Type::INTEGER || type == Variable::Type::BINARY; })) { return Contractor{make_shared<ContractorInteger>(box)}; } else { return make_contractor_id(); } } Contractor make_contractor_seq(const vector<Contractor>& contractors) { return Contractor{make_shared<ContractorSeq>(Flatten(contractors))}; } Contractor make_contractor_ibex_fwdbwd(Formula f, const Box& box) { return Contractor{make_shared<ContractorIbexFwdbwd>(move(f), box)}; } Contractor make_contractor_ibex_polytope(vector<Formula> formulas, const Box& box) { return Contractor{make_shared<ContractorIbexPolytope>(move(formulas), box)}; } Contractor make_contractor_fixpoint(TerminationCondition term_cond, const vector<Contractor>& contractors) { return Contractor{ make_shared<ContractorFixpoint>(move(term_cond), Flatten(contractors))}; } Contractor make_contractor_worklist_fixpoint( TerminationCondition term_cond, const vector<Contractor>& contractors) { return Contractor{make_shared<ContractorWorklistFixpoint>( move(term_cond), Flatten(contractors))}; } Contractor make_contractor_join(vector<Contractor> vec) { return Contractor{make_shared<ContractorJoin>(move(vec))}; } ostream& operator<<(ostream& os, const Contractor& ctc) { if (ctc.ptr_) { os << *(ctc.ptr_); } return os; } bool is_id(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::ID; } bool is_integer(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::INTEGER; } bool is_seq(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::SEQ; } bool is_ibex_fwdbwd(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::IBEX_FWDBWD; } bool is_ibex_polytope(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::IBEX_POLYTOPE; } bool is_fixpoint(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::FIXPOINT; } bool is_worklist_fixpoint(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::WORKLIST_FIXPOINT; } bool is_forall(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::FORALL; } bool is_join(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::JOIN; } } // namespace dreal <commit_msg>feat(contractor): Add ContractorStat which shows stat info at INFO level<commit_after>#include "dreal/contractor/contractor.h" #include <algorithm> #include <utility> #include "dreal/contractor/contractor_cell.h" #include "dreal/contractor/contractor_fixpoint.h" #include "dreal/contractor/contractor_forall.h" #include "dreal/contractor/contractor_ibex_fwdbwd.h" #include "dreal/contractor/contractor_ibex_polytope.h" #include "dreal/contractor/contractor_id.h" #include "dreal/contractor/contractor_integer.h" #include "dreal/contractor/contractor_join.h" #include "dreal/contractor/contractor_seq.h" #include "dreal/contractor/contractor_worklist_fixpoint.h" using std::any_of; using std::make_shared; using std::move; using std::ostream; using std::shared_ptr; using std::vector; namespace dreal { namespace { // Flattens contractors and filters out ID contractors. vector<Contractor> Flatten(const vector<Contractor>& contractors) { vector<Contractor> vec; vec.reserve(contractors.size()); for (const Contractor& contractor : contractors) { const Contractor::Kind kind{contractor.kind()}; if (kind == Contractor::Kind::ID) { // Skip if contractor == ID. continue; } else if (kind == Contractor::Kind::SEQ) { // Flatten it out if contractor == SEQ. const vector<Contractor>& contractors_inside{ to_seq(contractor)->contractors()}; vec.insert(vec.end(), contractors_inside.begin(), contractors_inside.end()); } else { vec.push_back(contractor); } } return vec; } // A class to show statistics information at destruction. We have a // static instance in Contractor::Prune() to keep track of the number // of pruning operations. class ContractorStat { public: ContractorStat() = default; ~ContractorStat() { DREAL_LOG_INFO("Total # of Pruning @ Contractor level = {}", num_prune_); } int num_prune_{0}; }; } // namespace Contractor::Contractor() : ptr_{make_shared<ContractorId>()} {} Contractor::Contractor(const shared_ptr<ContractorCell>& ptr) : ptr_(ptr) {} const ibex::BitSet& Contractor::input() const { return ptr_->input(); } void Contractor::Prune(ContractorStatus* cs) const { static ContractorStat stat; stat.num_prune_++; ptr_->Prune(cs); } Contractor::Kind Contractor::kind() const { return ptr_->kind(); } Contractor make_contractor_id() { return Contractor{}; } Contractor make_contractor_integer(const Box& box) { if (any_of(box.variables().begin(), box.variables().end(), [](const Variable& v) { const Variable::Type type{v.get_type()}; return type == Variable::Type::INTEGER || type == Variable::Type::BINARY; })) { return Contractor{make_shared<ContractorInteger>(box)}; } else { return make_contractor_id(); } } Contractor make_contractor_seq(const vector<Contractor>& contractors) { return Contractor{make_shared<ContractorSeq>(Flatten(contractors))}; } Contractor make_contractor_ibex_fwdbwd(Formula f, const Box& box) { return Contractor{make_shared<ContractorIbexFwdbwd>(move(f), box)}; } Contractor make_contractor_ibex_polytope(vector<Formula> formulas, const Box& box) { return Contractor{make_shared<ContractorIbexPolytope>(move(formulas), box)}; } Contractor make_contractor_fixpoint(TerminationCondition term_cond, const vector<Contractor>& contractors) { return Contractor{ make_shared<ContractorFixpoint>(move(term_cond), Flatten(contractors))}; } Contractor make_contractor_worklist_fixpoint( TerminationCondition term_cond, const vector<Contractor>& contractors) { return Contractor{make_shared<ContractorWorklistFixpoint>( move(term_cond), Flatten(contractors))}; } Contractor make_contractor_join(vector<Contractor> vec) { return Contractor{make_shared<ContractorJoin>(move(vec))}; } ostream& operator<<(ostream& os, const Contractor& ctc) { if (ctc.ptr_) { os << *(ctc.ptr_); } return os; } bool is_id(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::ID; } bool is_integer(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::INTEGER; } bool is_seq(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::SEQ; } bool is_ibex_fwdbwd(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::IBEX_FWDBWD; } bool is_ibex_polytope(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::IBEX_POLYTOPE; } bool is_fixpoint(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::FIXPOINT; } bool is_worklist_fixpoint(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::WORKLIST_FIXPOINT; } bool is_forall(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::FORALL; } bool is_join(const Contractor& contractor) { return contractor.kind() == Contractor::Kind::JOIN; } } // namespace dreal <|endoftext|>
<commit_before>#include "directories.h" #include "logging.h" Directories::Controller::Controller(Directories::Config& cfg) : config_(cfg) { m_ScrolledWindow.add(m_TreeView); m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); } void Directories::Controller:: open_folder(const boost::filesystem::path& dir_path) { INFO("Open folder"); m_refTreeModel = Gtk::TreeStore::create(view()); m_TreeView.set_model(m_refTreeModel); m_TreeView.remove_all_columns(); std::string project_name = GetCmakeVarValue(dir_path, "project"); m_TreeView.append_column(project_name, view().m_col_name); int row_id = 0; Gtk::TreeModel::Row row; list_dirs(dir_path, row, row_id); m_refTreeModel->set_sort_column(0, Gtk::SortType::SORT_ASCENDING); INFO("Folder opened"); } bool Directories::Controller::IsIgnored(std::string path) { std::transform(path.begin(), path.end(), path.begin(), ::tolower); // std::cout << "ignored?: " << path << std::endl; if (config().IsException(path)) { return false; } if (config().IsIgnored(path)) { return true; } return false; } void Directories::Controller:: list_dirs(const boost::filesystem::path& dir_path, Gtk::TreeModel::Row &parent, unsigned row_id) { boost::filesystem::directory_iterator end_itr; unsigned dir_counter = row_id; unsigned file_counter = 0; Gtk::TreeModel::Row child; Gtk::TreeModel::Row row; // Fill the treeview for ( boost::filesystem::directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if (!IsIgnored(itr->path().filename().string())) { if (boost::filesystem::is_directory(itr->status())) { if (count(itr->path().string()) > count(dir_path.string())) { // is child child = *(m_refTreeModel->append(parent.children())); std::string col_id("a"+itr->path().filename().string()); child[view().m_col_id] = col_id; child[view().m_col_name] = itr->path().filename().string(); child[view().m_col_path] = itr->path().string(); list_dirs(itr->path(), child, row_id); } else { row = *(m_refTreeModel->append()); std::string col_id("a"+itr->path().filename().string()); row[view().m_col_path] = itr->path().string(); row[view().m_col_id] = col_id; row[view().m_col_name] = itr->path().filename().string(); list_dirs(itr->path(), parent, row_id); } } else { // is a file child = *(m_refTreeModel->append(parent.children())); std::string col_id("b"+itr->path().filename().string()); child[view().m_col_id] = col_id; child[view().m_col_name] = itr->path().filename().string(); child[view().m_col_path] = itr->path().string(); } } } } int Directories::Controller::count(const std::string path) { int count = 0; for (int i = 0; i < path.size(); i++) if (path[i] == '/') count++; return count; } std::string Directories::Controller:: GetCmakeVarValue(const boost::filesystem::path& dir_path, std::string command_name) { INFO("fetches cmake variable value for: "+command_name); std::string project_name; std::string project_name_var; boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if (itr->path().filename().string() == "CMakeLists.txt") { std::ifstream ifs(itr->path().string()); std::string line; while (std::getline(ifs, line)) { if (line.find(command_name+"(", 0) != std::string::npos || line.find(command_name+" (", 0) != std::string::npos ) { size_t variable_start = line.find("{", 0); size_t variable_end = line.find("}", variable_start); project_name_var = line.substr(variable_start+1, (variable_end)-variable_start-1); boost::algorithm::trim(project_name_var); if (variable_start == std::string::npos) { // not a variabel variable_start = line.find("(", 0); variable_end = line.find(' ', variable_start); if(variable_end != std::string::npos){ return line.substr(variable_start+1, (variable_end)-variable_start-1); } variable_end = line.find("#", variable_start); if(variable_end != std::string::npos){ return line.substr(variable_start+1, (variable_end)-variable_start-1); } variable_end = line.find(")", variable_start); return line.substr(variable_start+1, (variable_end)-variable_start-1); if (variable_start == std::string::npos) { // not a variable variable_start = line.find("(", 0); variable_end = line.find(")", variable_start); INFO("Wasn't a variable, returning value"); return line.substr(variable_start+1, (variable_end)-variable_start-1); } break; } } } std::ifstream ifs2(itr->path().string()); while (std::getline(ifs2, line)) { if (line.find("set(", 0) != std::string::npos || line.find("set (", 0) != std::string::npos) { if( line.find(project_name_var, 0) != std::string::npos) { size_t variable_start = line.find(project_name_var, 0) +project_name_var.length(); size_t variable_end = line.find(")", variable_start); project_name = line.substr(variable_start+1, variable_end-variable_start-1); boost::algorithm::trim(project_name); INFO("found variable, returning value"); return project_name; } } } break; } } INFO("Couldn't find value in CMakeLists.txt"); return "no project name"; } Directories::Config::Config() { } Directories::Config::Config(Directories::Config& cfg) : ignore_list_(cfg.ignore_list()), exception_list_(cfg.exception_list()) { } void Directories::Config::AddIgnore(std::string filter) { ignore_list_.push_back(filter); } void Directories::Config::AddException(std::string filter) { exception_list_.push_back(filter); } bool Directories::Config::IsIgnored(std::string str) { for ( auto &i : ignore_list() ) if (str.find(i, 0) != std::string::npos) return true; return false; } bool Directories::Config::IsException(std::string str) { for ( std::string &i : exception_list() ) if (i == str) return true; return false; } <commit_msg>added some debugging in directories<commit_after>#include "directories.h" #include "logging.h" Directories::Controller::Controller(Directories::Config& cfg) : config_(cfg) { DEBUG("adding treeview to scrolledwindow"); m_ScrolledWindow.add(m_TreeView); m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); } void Directories::Controller:: open_folder(const boost::filesystem::path& dir_path) { INFO("Open folder"); m_refTreeModel = Gtk::TreeStore::create(view()); m_TreeView.set_model(m_refTreeModel); m_TreeView.remove_all_columns(); DEBUG("Getting project name from CMakeLists.txt"); std::string project_name = GetCmakeVarValue(dir_path, "project"); m_TreeView.append_column(project_name, view().m_col_name); int row_id = 0; Gtk::TreeModel::Row row; DEBUG("Listing directories"); list_dirs(dir_path, row, row_id); DEBUG("Sorting directories"); m_refTreeModel->set_sort_column(0, Gtk::SortType::SORT_ASCENDING); DEBUG("Folder opened"); } bool Directories::Controller::IsIgnored(std::string path) { DEBUG("Checking if file-/directory is filtered"); std::transform(path.begin(), path.end(), path.begin(), ::tolower); // std::cout << "ignored?: " << path << std::endl; if (config().IsException(path)) { return false; } if (config().IsIgnored(path)) { return true; } return false; } void Directories::Controller:: list_dirs(const boost::filesystem::path& dir_path, Gtk::TreeModel::Row &parent, unsigned row_id) { boost::filesystem::directory_iterator end_itr; unsigned dir_counter = row_id; unsigned file_counter = 0; Gtk::TreeModel::Row child; Gtk::TreeModel::Row row; DEBUG_VAR(dir_path); // Fill the treeview for ( boost::filesystem::directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if (!IsIgnored(itr->path().filename().string())) { if (boost::filesystem::is_directory(itr->status())) { if (count(itr->path().string()) > count(dir_path.string())) { // is child child = *(m_refTreeModel->append(parent.children())); std::string col_id("a"+itr->path().filename().string()); child[view().m_col_id] = col_id; child[view().m_col_name] = itr->path().filename().string(); child[view().m_col_path] = itr->path().string(); list_dirs(itr->path(), child, row_id); } else { row = *(m_refTreeModel->append()); std::string col_id("a"+itr->path().filename().string()); row[view().m_col_path] = itr->path().string(); row[view().m_col_id] = col_id; row[view().m_col_name] = itr->path().filename().string(); list_dirs(itr->path(), parent, row_id); } } else { // is a file child = *(m_refTreeModel->append(parent.children())); std::string col_id("b"+itr->path().filename().string()); child[view().m_col_id] = col_id; child[view().m_col_name] = itr->path().filename().string(); child[view().m_col_path] = itr->path().string(); } } } } int Directories::Controller::count(const std::string path) { int count = 0; for (int i = 0; i < path.size(); i++) if (path[i] == '/') count++; return count; } std::string Directories::Controller:: GetCmakeVarValue(const boost::filesystem::path& dir_path, std::string command_name) { INFO("fetches cmake variable value for: "+command_name); std::string project_name; std::string project_name_var; boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if (itr->path().filename().string() == "CMakeLists.txt") { std::ifstream ifs(itr->path().string()); std::string line; while (std::getline(ifs, line)) { if (line.find(command_name+"(", 0) != std::string::npos || line.find(command_name+" (", 0) != std::string::npos ) { size_t variable_start = line.find("{", 0); size_t variable_end = line.find("}", variable_start); project_name_var = line.substr(variable_start+1, (variable_end)-variable_start-1); boost::algorithm::trim(project_name_var); if (variable_start == std::string::npos) { // not a variabel variable_start = line.find("(", 0); variable_end = line.find(' ', variable_start); if(variable_end != std::string::npos){ return line.substr(variable_start+1, (variable_end)-variable_start-1); } variable_end = line.find("#", variable_start); if(variable_end != std::string::npos){ return line.substr(variable_start+1, (variable_end)-variable_start-1); } variable_end = line.find(")", variable_start); return line.substr(variable_start+1, (variable_end)-variable_start-1); if (variable_start == std::string::npos) { // not a variable variable_start = line.find("(", 0); variable_end = line.find(")", variable_start); INFO("Wasn't a variable, returning value"); return line.substr(variable_start+1, (variable_end)-variable_start-1); } break; } } } std::ifstream ifs2(itr->path().string()); while (std::getline(ifs2, line)) { if (line.find("set(", 0) != std::string::npos || line.find("set (", 0) != std::string::npos) { if( line.find(project_name_var, 0) != std::string::npos) { size_t variable_start = line.find(project_name_var, 0) +project_name_var.length(); size_t variable_end = line.find(")", variable_start); project_name = line.substr(variable_start+1, variable_end-variable_start-1); boost::algorithm::trim(project_name); INFO("found variable, returning value"); return project_name; } } } break; } } INFO("Couldn't find value in CMakeLists.txt"); return "no project name"; } Directories::Config::Config() { } Directories::Config::Config(Directories::Config& cfg) : ignore_list_(cfg.ignore_list()), exception_list_(cfg.exception_list()) { } void Directories::Config::AddIgnore(std::string filter) { ignore_list_.push_back(filter); } void Directories::Config::AddException(std::string filter) { exception_list_.push_back(filter); } bool Directories::Config::IsIgnored(std::string str) { for ( auto &i : ignore_list() ) if (str.find(i, 0) != std::string::npos) return true; return false; } bool Directories::Config::IsException(std::string str) { for ( std::string &i : exception_list() ) if (i == str) return true; return false; } <|endoftext|>
<commit_before>#include "Histogram.h" #include "Matrix.h" void Histogram::Init(Local<Object> target) { Nan::Persistent<Object> inner; Local<Object> obj = Nan::New<Object>(); inner.Reset(obj); Nan::SetMethod(obj, "calcHist", CalcHist); Nan::SetMethod(obj, "emd", Emd); target->Set(Nan::New("histogram").ToLocalChecked(), obj); } NAN_METHOD(Histogram::CalcHist) { Nan::EscapableHandleScope scope; try { // Arg 0 is the image Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat inputImage = m0->mat; //int dims = 3; // Arg 1 is the channel Local<Array> nodeChannels = Local<Array>::Cast(info[1]->ToObject()); const unsigned int dims = nodeChannels->Length(); int channels[dims]; for (unsigned int i = 0; i < dims; i++) { channels[i] = nodeChannels->Get(i)->IntegerValue(); } //int channels[] = {0, 1, 2}; // Arg 2 is histogram sizes in each dimension Local<Array> nodeHistSizes = Local<Array>::Cast(info[2]->ToObject()); int histSize[dims]; for (unsigned int i = 0; i < dims; i++) { histSize[i] = nodeHistSizes->Get(i)->IntegerValue(); } // Arg 3 is array of the histogram bin boundaries in each dimension Local<Array> nodeRanges = Local<Array>::Cast(info[3]->ToObject()); /// Set the ranges ( for B,G,R) ) float histRanges[dims][2]; for (unsigned int i = 0; i < dims; i++) { Local<Array> nodeRange = Local<Array>::Cast(nodeRanges->Get(i)->ToObject()); float lower = nodeRange->Get(0)->NumberValue(); float higher = nodeRange->Get(1)->NumberValue(); histRanges[i][0] = lower; histRanges[i][1] = higher; } float first_range[] = { histRanges[0][0], histRanges[0][1] }; float second_range[] = { 0, 0}; float third_range[] = { 0, 0}; if(dims >= 2){ second_range[0] = histRanges[1][0]; second_range[1] = histRanges[1][1]; } if(dims >= 3){ third_range[0] = histRanges[2][0]; third_range[1] = histRanges[2][1]; } const float* histRanges1[] = {first_range, second_range, third_range}; //const float** histRanges1 = const_cast<const float**>(histRanges); // Arg 4 is uniform flag bool uniform = info[4]->BooleanValue(); // Make a mat to hold the result image cv::Mat outputHist; // Perform calcHist cv::calcHist(&inputImage, 1, channels, cv::Mat(), outputHist, dims, histSize, histRanges1, uniform); // Wrap the output image /*Local<Object> outMatrixWrap = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *outMatrix = Nan::ObjectWrap::Unwrap<Matrix>(outMatrixWrap); outMatrix->mat = outputHist; info.GetReturnValue().Set(outMatrixWrap);*/ v8::Local<v8::Array> arr = Nan::New<Array>(histSize[0]); if(dims < 1 || dims > 3){ return Nan::ThrowTypeError("OPENCV nodejs binding error : only dimensions from 1 to 3 are allowed"); } for (unsigned int i=0; i < (unsigned int) histSize[0]; i++) { if(dims <= 1){ arr->Set(i, Nan::New<Number>(outputHist.at<float>(i))); } else { v8::Local<v8::Array> arr2 = Nan::New<Array>(dims); for (unsigned int j=0; j < (unsigned int) histSize[1]; j++) { if(dims <= 2){ arr2->Set(j, Nan::New<Number>(outputHist.at<float>(i,j))); } else { v8::Local<v8::Array> arr3 = Nan::New<Array>(dims); for (unsigned int k=0; k < (unsigned int) histSize[1]; k++) { arr3->Set(k, Nan::New<Number>(outputHist.at<float>(i,j,k))); } arr2->Set(j, arr3); } } arr->Set(i, arr2); } } info.GetReturnValue().Set(arr); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } std::vector<std::vector<float>> nodeArrayToVec(Local<Object> input){ std::vector<std::vector<float>> ret; Local<Array> nodeMatrix = Local<Array>::Cast(input); const unsigned int size = nodeMatrix->Length(); for (unsigned int i = 0; i < size; i++) { Local<Array> nodeRow = Local<Array>::Cast(nodeMatrix->Get(i)->ToObject()); std::vector<float> row; const unsigned int size2 = nodeRow->Length(); for (unsigned int j = 0; j < size2; j++) { row.push_back(nodeRow->Get(j)->NumberValue()); } ret.push_back(row); } return ret; } // cv::distanceTransform NAN_METHOD(Histogram::Emd) { Nan::EscapableHandleScope scope; try { // Arg 0 is the first signature //std::vector<std::vector<float>> sig1 = nodeArrayToVec(info[0]->ToObject()); Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat sig1 = m0->mat; // Arg 1 is the second signature //std::vector<std::vector<float>> sig2 = nodeArrayToVec(info[1]->ToObject()); Matrix* m1 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); cv::Mat sig2 = m1->mat; // Arg 2 is the distance type int distType = info[2]->IntegerValue(); float emd; // Arg 3 is the cost matrix if (info.Length() > 3) { Matrix* m3 = Nan::ObjectWrap::Unwrap<Matrix>(info[3]->ToObject()); cv::Mat costs = m3->mat; emd = cv::EMD(sig1, sig2, distType, costs); info.GetReturnValue().Set(emd); } else { emd = cv::EMD(sig1, sig2, distType); } //printf("similarity %5.5f %%\n, DistanceType is %i\n", (1-emd)*100, distType); info.GetReturnValue().Set(emd); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } <commit_msg>cleanup code following https://stackoverflow.com/questions/45868943/convert-node-array-variable-lenght-to-a-const-float-to-call-opencv-calchist/45870887#45870887<commit_after>#include "Histogram.h" #include "Matrix.h" void Histogram::Init(Local<Object> target) { Nan::Persistent<Object> inner; Local<Object> obj = Nan::New<Object>(); inner.Reset(obj); Nan::SetMethod(obj, "calcHist", CalcHist); Nan::SetMethod(obj, "emd", Emd); target->Set(Nan::New("histogram").ToLocalChecked(), obj); } NAN_METHOD(Histogram::CalcHist) { Nan::EscapableHandleScope scope; try { // Arg 0 is the image Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat inputImage = m0->mat; //int dims = 3; // Arg 1 is the channel Local<Array> nodeChannels = Local<Array>::Cast(info[1]->ToObject()); const unsigned int dims = nodeChannels->Length(); int channels[dims]; for (unsigned int i = 0; i < dims; i++) { channels[i] = nodeChannels->Get(i)->IntegerValue(); } //int channels[] = {0, 1, 2}; // Arg 2 is histogram sizes in each dimension Local<Array> nodeHistSizes = Local<Array>::Cast(info[2]->ToObject()); int histSize[dims]; for (unsigned int i = 0; i < dims; i++) { histSize[i] = nodeHistSizes->Get(i)->IntegerValue(); } // Arg 3 is array of the histogram bin boundaries in each dimension Local<Array> nodeRanges = Local<Array>::Cast(info[3]->ToObject()); /// Set the ranges ( for B,G,R) ) float histRanges[dims][2]; const float* ranges[dims]; for (unsigned int i = 0; i < dims; i++) { Local<Array> nodeRange = Local<Array>::Cast(nodeRanges->Get(i)->ToObject()); float lower = nodeRange->Get(0)->NumberValue(); float higher = nodeRange->Get(1)->NumberValue(); histRanges[i][0] = lower; histRanges[i][1] = higher; ranges[i] = histRanges[i]; } //const float** histRanges1 = const_cast<const float**>(histRanges); // Arg 4 is uniform flag bool uniform = info[4]->BooleanValue(); // Make a mat to hold the result image cv::Mat outputHist; // Perform calcHist cv::calcHist(&inputImage, 1, channels, cv::Mat(), outputHist, dims, histSize, ranges, uniform); // Wrap the output image /*Local<Object> outMatrixWrap = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *outMatrix = Nan::ObjectWrap::Unwrap<Matrix>(outMatrixWrap); outMatrix->mat = outputHist; info.GetReturnValue().Set(outMatrixWrap);*/ v8::Local<v8::Array> arr = Nan::New<Array>(histSize[0]); if(dims < 1 || dims > 3){ return Nan::ThrowTypeError("OPENCV nodejs binding error : only dimensions from 1 to 3 are allowed"); } for (unsigned int i=0; i < (unsigned int) histSize[0]; i++) { if(dims <= 1){ arr->Set(i, Nan::New<Number>(outputHist.at<float>(i))); } else { v8::Local<v8::Array> arr2 = Nan::New<Array>(dims); for (unsigned int j=0; j < (unsigned int) histSize[1]; j++) { if(dims <= 2){ arr2->Set(j, Nan::New<Number>(outputHist.at<float>(i,j))); } else { v8::Local<v8::Array> arr3 = Nan::New<Array>(dims); for (unsigned int k=0; k < (unsigned int) histSize[1]; k++) { arr3->Set(k, Nan::New<Number>(outputHist.at<float>(i,j,k))); } arr2->Set(j, arr3); } } arr->Set(i, arr2); } } info.GetReturnValue().Set(arr); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } std::vector<std::vector<float>> nodeArrayToVec(Local<Object> input){ std::vector<std::vector<float>> ret; Local<Array> nodeMatrix = Local<Array>::Cast(input); const unsigned int size = nodeMatrix->Length(); for (unsigned int i = 0; i < size; i++) { Local<Array> nodeRow = Local<Array>::Cast(nodeMatrix->Get(i)->ToObject()); std::vector<float> row; const unsigned int size2 = nodeRow->Length(); for (unsigned int j = 0; j < size2; j++) { row.push_back(nodeRow->Get(j)->NumberValue()); } ret.push_back(row); } return ret; } // cv::distanceTransform NAN_METHOD(Histogram::Emd) { Nan::EscapableHandleScope scope; try { // Arg 0 is the first signature //std::vector<std::vector<float>> sig1 = nodeArrayToVec(info[0]->ToObject()); Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat sig1 = m0->mat; // Arg 1 is the second signature //std::vector<std::vector<float>> sig2 = nodeArrayToVec(info[1]->ToObject()); Matrix* m1 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); cv::Mat sig2 = m1->mat; // Arg 2 is the distance type int distType = info[2]->IntegerValue(); float emd; // Arg 3 is the cost matrix if (info.Length() > 3) { Matrix* m3 = Nan::ObjectWrap::Unwrap<Matrix>(info[3]->ToObject()); cv::Mat costs = m3->mat; emd = cv::EMD(sig1, sig2, distType, costs); info.GetReturnValue().Set(emd); } else { emd = cv::EMD(sig1, sig2, distType); } //printf("similarity %5.5f %%\n, DistanceType is %i\n", (1-emd)*100, distType); info.GetReturnValue().Set(emd); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } <|endoftext|>
<commit_before>#include "Histogram.h" #include "Matrix.h" void Histogram::Init(Local<Object> target) { Nan::Persistent<Object> inner; Local<Object> obj = Nan::New<Object>(); inner.Reset(obj); Nan::SetMethod(obj, "calcHist", CalcHist); Nan::SetMethod(obj, "emd", Emd); target->Set(Nan::New("histogram").ToLocalChecked(), obj); } NAN_METHOD(Histogram::CalcHist) { Nan::EscapableHandleScope scope; try { // Arg 0 is the image Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat inputImage = m0->mat; // Arg 1 is the channel Local<Array> nodeChannels = Local<Array>::Cast(info[1]->ToObject()); const unsigned int dims = nodeChannels->Length(); int channels[dims]; for (unsigned int i = 0; i < dims; i++) { channels[i] = nodeChannels->Get(i)->IntegerValue(); } // Arg 2 is histogram sizes in each dimension Local<Array> nodeHistSizes = Local<Array>::Cast(info[2]->ToObject()); int histSize[dims]; for (unsigned int i = 0; i < dims; i++) { histSize[i] = nodeHistSizes->Get(i)->IntegerValue(); } // Arg 3 is array of the histogram bin boundaries in each dimension Local<Array> nodeRanges = Local<Array>::Cast(info[3]->ToObject()); /// Set the ranges ( for B,G,R) ) float histRanges[dims][2]; const float* ranges[dims]; for (unsigned int i = 0; i < dims; i++) { Local<Array> nodeRange = Local<Array>::Cast(nodeRanges->Get(i)->ToObject()); float lower = nodeRange->Get(0)->NumberValue(); float higher = nodeRange->Get(1)->NumberValue(); histRanges[i][0] = lower; histRanges[i][1] = higher; ranges[i] = histRanges[i]; } // Arg 4 is uniform flag bool uniform = info[4]->BooleanValue(); // Make a mat to hold the result image cv::Mat outputHist; // Perform calcHist cv::calcHist(&inputImage, 1, channels, cv::Mat(), outputHist, dims, histSize, ranges, uniform); v8::Local<v8::Array> arr = Nan::New<Array>(histSize[0]); if(dims < 1 || dims > 3){ return Nan::ThrowTypeError("OPENCV nodejs binding error : only dimensions from 1 to 3 are allowed"); } for (unsigned int i=0; i < (unsigned int) histSize[0]; i++) { if(dims <= 1){ arr->Set(i, Nan::New<Number>(outputHist.at<float>(i))); } else { v8::Local<v8::Array> arr2 = Nan::New<Array>(dims); for (unsigned int j=0; j < (unsigned int) histSize[1]; j++) { if(dims <= 2){ arr2->Set(j, Nan::New<Number>(outputHist.at<float>(i,j))); } else { v8::Local<v8::Array> arr3 = Nan::New<Array>(dims); for (unsigned int k=0; k < (unsigned int) histSize[1]; k++) { arr3->Set(k, Nan::New<Number>(outputHist.at<float>(i,j,k))); } arr2->Set(j, arr3); } } arr->Set(i, arr2); } } info.GetReturnValue().Set(arr); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } // cv::distanceTransform NAN_METHOD(Histogram::Emd) { Nan::EscapableHandleScope scope; try { // Arg 0 is the first signature //std::vector<std::vector<float>> sig1 = nodeArrayToVec(info[0]->ToObject()); Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat sig1 = m0->mat; // Arg 1 is the second signature //std::vector<std::vector<float>> sig2 = nodeArrayToVec(info[1]->ToObject()); Matrix* m1 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); cv::Mat sig2 = m1->mat; // Arg 2 is the distance type int distType = info[2]->IntegerValue(); float emd; // Arg 3 is the cost matrix if (info.Length() > 3) { Matrix* m3 = Nan::ObjectWrap::Unwrap<Matrix>(info[3]->ToObject()); cv::Mat costs = m3->mat; emd = cv::EMD(sig1, sig2, distType, costs); info.GetReturnValue().Set(emd); } else { emd = cv::EMD(sig1, sig2, distType); } //printf("similarity %5.5f %%\n, DistanceType is %i\n", (1-emd)*100, distType); info.GetReturnValue().Set(emd); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } <commit_msg>Histogram - fix VS compilation by setting constant size arrays.<commit_after>#include "Histogram.h" #include "Matrix.h" void Histogram::Init(Local<Object> target) { Nan::Persistent<Object> inner; Local<Object> obj = Nan::New<Object>(); inner.Reset(obj); Nan::SetMethod(obj, "calcHist", CalcHist); Nan::SetMethod(obj, "emd", Emd); target->Set(Nan::New("histogram").ToLocalChecked(), obj); } NAN_METHOD(Histogram::CalcHist) { Nan::EscapableHandleScope scope; try { // Arg 0 is the image Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat inputImage = m0->mat; // Arg 1 is the channel Local<Array> nodeChannels = Local<Array>::Cast(info[1]->ToObject()); // vs does not like this const, no need for it? /*const */unsigned int dims = nodeChannels->Length(); if(dims < 1 || dims > 3){ return Nan::ThrowTypeError("OPENCV nodejs binding error : only dimensions from 1 to 3 are allowed"); } // in vs, can't create an array of non-constant size; but since we have dims<3, just use 3.. int channels[3]; for (unsigned int i = 0; i < dims; i++) { channels[i] = nodeChannels->Get(i)->IntegerValue(); } // Arg 2 is histogram sizes in each dimension Local<Array> nodeHistSizes = Local<Array>::Cast(info[2]->ToObject()); int histSize[3]; for (unsigned int i = 0; i < dims; i++) { histSize[i] = nodeHistSizes->Get(i)->IntegerValue(); } // Arg 3 is array of the histogram bin boundaries in each dimension Local<Array> nodeRanges = Local<Array>::Cast(info[3]->ToObject()); /// Set the ranges ( for B,G,R) ) float histRanges[3][2]; const float* ranges[3]; for (unsigned int i = 0; i < dims; i++) { Local<Array> nodeRange = Local<Array>::Cast(nodeRanges->Get(i)->ToObject()); float lower = nodeRange->Get(0)->NumberValue(); float higher = nodeRange->Get(1)->NumberValue(); histRanges[i][0] = lower; histRanges[i][1] = higher; ranges[i] = histRanges[i]; } // Arg 4 is uniform flag bool uniform = info[4]->BooleanValue(); // Make a mat to hold the result image cv::Mat outputHist; // Perform calcHist cv::calcHist(&inputImage, 1, channels, cv::Mat(), outputHist, dims, histSize, ranges, uniform); v8::Local<v8::Array> arr = Nan::New<Array>(histSize[0]); for (unsigned int i=0; i < (unsigned int) histSize[0]; i++) { if(dims <= 1){ arr->Set(i, Nan::New<Number>(outputHist.at<float>(i))); } else { v8::Local<v8::Array> arr2 = Nan::New<Array>(dims); for (unsigned int j=0; j < (unsigned int) histSize[1]; j++) { if(dims <= 2){ arr2->Set(j, Nan::New<Number>(outputHist.at<float>(i,j))); } else { v8::Local<v8::Array> arr3 = Nan::New<Array>(dims); for (unsigned int k=0; k < (unsigned int) histSize[1]; k++) { arr3->Set(k, Nan::New<Number>(outputHist.at<float>(i,j,k))); } arr2->Set(j, arr3); } } arr->Set(i, arr2); } } info.GetReturnValue().Set(arr); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } // cv::distanceTransform NAN_METHOD(Histogram::Emd) { Nan::EscapableHandleScope scope; try { // Arg 0 is the first signature //std::vector<std::vector<float>> sig1 = nodeArrayToVec(info[0]->ToObject()); Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat sig1 = m0->mat; // Arg 1 is the second signature //std::vector<std::vector<float>> sig2 = nodeArrayToVec(info[1]->ToObject()); Matrix* m1 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); cv::Mat sig2 = m1->mat; // Arg 2 is the distance type int distType = info[2]->IntegerValue(); float emd; // Arg 3 is the cost matrix if (info.Length() > 3) { Matrix* m3 = Nan::ObjectWrap::Unwrap<Matrix>(info[3]->ToObject()); cv::Mat costs = m3->mat; emd = cv::EMD(sig1, sig2, distType, costs); info.GetReturnValue().Set(emd); } else { emd = cv::EMD(sig1, sig2, distType); } //printf("similarity %5.5f %%\n, DistanceType is %i\n", (1-emd)*100, distType); info.GetReturnValue().Set(emd); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } <|endoftext|>
<commit_before><commit_msg>さっきのうそ<commit_after>#include <cstdio> #include <vector> #include <deque> #include <string> #include <algorithm> #include <sstream> /* definitions */ const int stone_size = 8; const int field_size = 32; const int empty_val = 257; // 障害物やzkの無いことを表す const int filled_val = 256; // 障害物を表す FILE* dumpout = stdout; // dump系関数の出力先 struct Position { /*座標を表現するクラス*/ int y, x; bool operator==(const Position&obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position&obj) const { if (y == obj.y) { return x < obj.x; } return y < obj.y; } }; struct Stone { /* 石 */ int raw[stone_size][stone_size]; // empty_val -> 空き, otherwise -> うまり std::deque<Position> fills; // 埋まってる座標を持っておく }; struct Field { /* フィールド */ int raw[field_size][field_size]; std::deque<std::string> answer; // 答えとなる石の置き方を持っておく }; int number_of_stones; // 与えられる石の数 Stone stones[256 * 8]; // 石を持っておくインスタンス(回転反転を考慮して8倍とってある) Field initial_field; // 初期フィールド状態 std::deque<Position> initial_empties; // 初期フィールドで空いている場所を探す int rotated(int deg) { /* 石をdeg度まわした石の番号のバイアスを返す */ return number_of_stones * (deg/90); } int fliped() { /* 石を反転した時の石の番号のバイアスを返す */ return number_of_stones * 4; } int operated(bool flip, int deg) { /* 石を操作した時の石の番号のバイアスを返す */ if (flip) { if (deg == 0) { return fliped(); } return fliped() + rotated(deg); } return rotated(deg); } int rotated(int n, int deg) { /* 石をdeg度まわした石の番号を返す */ return n + rotated(deg); } int fliped(int n) { /* 石を反転した時の石の番号を返す */ return n + fliped(); } int operated(int n, bool flip, int deg) { /* 石を操作した時の石の番号のバイアスを返す */ return n + operated(flip, deg); } int all_stones_num() { /* 全部で石が何個になるか */ return 8*number_of_stones; } /* util */ std::string to_s(int n) { /* std::to_stringとかぶるけど、本番環境では必要になりそう*/ std::stringstream ss; ss << n; return ss.str(); } int get() { return getc(stdin) - '0'; } void read_br() { /* CRLFを読み飛ばす */ get(); get(); }; /* dump */ void dump_stone(int n) { for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { if (stones[n].raw[i][j] == empty_val) { /* 空き */ putc('.', dumpout); } else { /* うまり */ putc('@', dumpout); } } putc('\n', dumpout); } } void dump_field(Field& f, std::deque<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) { /* 次の候補 */ putc('_', dumpout); } else if (f.raw[i][j] == empty_val) { /* あき */ putc('.', dumpout); } else if (f.raw[i][j] == filled_val) { /* 障害物 */ putc('#', dumpout); } else { /* 石 */ putc('@', dumpout); } } putc('\n', dumpout); } } void dump_field(Field& f) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (f.raw[i][j] == empty_val) { /* あき */ putc('.', dumpout); } else if (f.raw[i][j] == filled_val) { /* 障害物 */ putc('#', dumpout); } else { /* 石 */ putc('@', dumpout); } } putc('\n', dumpout); } } /* stone manipurates */ void init_stone(int n) { /* 石を初期化しておく */ for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { stones[n].raw[i][j] = empty_val; } } } void rotate_stone(int n, int deg) { /* 石を回す。deg = 90でよばれて、内部で180, 270をよぶ */ init_stone(rotated(n, deg)); for (int i = 0; i < stones[n].fills.size(); ++i) { int newy = stones[n].fills[i].x; int newx = 7 - stones[n].fills[i].y; stones[rotated(n, deg)].fills.push_back(Position{newy, newx}); stones[rotated(n, deg)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x]; } if (deg != 270) { rotate_stone(n, deg+90); } } void flip_stone(int n) { /* 石を反転させる */ init_stone(fliped(n)); for (int i = 0; i < stones[n].fills.size(); ++i) { int newy = stones[n].fills[i].y; int newx = 7 - stones[n].fills[i].x; stones[fliped(n)].fills.push_back(Position{newy, newx}); stones[fliped(n)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x]; } } /* parsing */ void get_field() { /* 初期フィールドを得る */ for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (get() == 0) { initial_field.raw[i][j] = empty_val; initial_empties.push_back(Position{i, j}); } else { initial_field.raw[i][j] = filled_val; } } read_br(); } } void get_stone(int index) { /* 石をひとつ読む */ for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (get() == 0) { stones[index].raw[i][j] = empty_val; } else { stones[index].raw[i][j] = index; stones[index].fills.push_back(Position{i, j}); } } read_br(); } } void get_stones() { /* 石をnumber_of_stones個よむ */ for (int i = 0; i < number_of_stones; ++i) { get_stone(i); read_br(); flip_stone(i); rotate_stone(i, 90); rotate_stone(fliped(i), 90); } } void get_input() { /* 入力を読む */ get_field(); read_br(); scanf("%d\n", &number_of_stones); get_stones(); } /* helper */ void create_candidates(std::deque<Position>& next_candidates, int n, std::deque<Position>& empties) { /* 石の埋まっている場所とフィールド上の候補から、次に石を置く可能性のある場所に置く*/ // next_candidates.resize(empties.size() * stones[n].fills.size()); for (auto p1 : empties) { for (auto p2 : stones[n].fills) { next_candidates.push_back(Position{ p1.y - p2.y, p1.x - p2.x }); } } } bool pos_check(int y, int x) { /* 与えられた座標が、fieldからはみ出ていたらfalseを返す */ return (0 <= y && y < field_size) && (0 <= x < field_size); } std::string create_answer_format(int n, bool flip, int deg, Position p) { /* 石を置いた様子から回答フォーマットに沿った文字列を返す */ return to_s(p.x) + " " + to_s(p.y) + " " + (flip ? "T" : "H") + " " + to_s(deg); } void print_anser(Field& f) { for (auto l : f.answer) { printf("%s\r\n", l.c_str()); } } /* solver */ int put_stone(int m, bool flip, int deg, Position base, Field& f, std::deque<Position>& next_candidates) { /* 石を置く処理。ついでに次に石を置けそうな場所を探す */ int score = 0; int n = operated(m, flip, deg); bool flag = false; // となりに石があるかフラグ。本来不要 Field backup = f; for (auto p : stones[n].fills) { // zkごとにおけるかどうかを判定する int y = base.y + p.y; int x = base.x + p.x; if (!pos_check(y, x) || f.raw[y][x] != empty_val) { // 置きたい場所が空いてないと置けない next_candidates.clear(); f = backup; return 0; } score += 1; f.raw[y][x] = m; /* 置いたところは候補から外す */ auto exists = std::find(next_candidates.begin(), next_candidates.end(), Position{y, x}); if (exists != next_candidates.end()) { next_candidates.erase(exists); } /* 隣接している空きマスを次の候補に */ int dy[] = {-1, 0, 0, 1}; int dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { if (!flag && pos_check(y + dy[i], x + dx[i]) && f.raw[y + dy[i]][x + dx[i]] > n) { flag = true; } if (pos_check(y + dy[i], x + dx[i]) && f.raw[y + dy[i]][x + dx[i]] == empty_val) { Position newpos{y+dy[i], x+dx[i]}; if (std::find(next_candidates.begin(), next_candidates.end(), newpos) == next_candidates.end()) { next_candidates.push_back(newpos); } } } } if (!flag) { next_candidates.clear(); f = backup; return 0; } return score; } void dfs(int nowscore, int n, bool fliped, int deg, Position p, Field f, std::deque<Position> next_empties) { /* n番の石をfliped + degの状態で、f上のpに置くところから深く */ if (n >= number_of_stones) { return; } int score; if ((score = put_stone(n, fliped, deg, p, f, next_empties)) > 0) { score += nowscore; fprintf(stderr, "score - %d\n", score); /* 石を置いた時の処理 */ f.answer[n] = create_answer_format(n, fliped, deg, p); printf("score: %d\n", score); dump_field(f, next_empties); print_anser(f); fflush(dumpout); } /* 次の石を置く処理 */ std::deque<Position> next_candidates; for (int j = 0; j <= 270; j += 90) { // 回転 for (bool k = false; !k; k = true) { // 反転 for (int i = n + 1; i < number_of_stones; ++i) { create_candidates(next_candidates, operated(i, k, j), next_empties); // 石を置く場所の候補を生成 for (auto p : next_candidates) { dfs(score, i, k, j, p, f, next_empties); } } } } } void solve() { /* とりあえずこれを呼んでsolveする */ std::deque<Position> first_candidates; // 最初の石を置く場所 std::deque<Position> empty_positions; empty_positions.empty(); for (int j = 0; j <= 270; j += 90) { // 回転 for (bool k = false; !k; k = true) { // 反転 for (int i = 0; i < number_of_stones; ++i) { create_candidates(first_candidates, operated(i, k, j), initial_empties); // 一個目の石を置く場所の候補を生成 for (auto p : first_candidates) { dfs(0, i, k, j, p, initial_field, empty_positions); } } } } } /* main */ int main() { get_input(); initial_field.answer.resize(number_of_stones); solve(); } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ryan Luna, Ioan Sucan */ #include "console_bridge/console.h" #include <cstdio> #include <cstdarg> #include <iostream> #include <mutex> /// @cond IGNORE struct DefaultOutputHandler { DefaultOutputHandler(void) { output_handler_ = static_cast<console_bridge::OutputHandler*>(&std_output_handler_); previous_output_handler_ = output_handler_; logLevel_ = console_bridge::CONSOLE_BRIDGE_LOG_WARN; } console_bridge::OutputHandlerSTD std_output_handler_; console_bridge::OutputHandler *output_handler_; console_bridge::OutputHandler *previous_output_handler_; console_bridge::LogLevel logLevel_; std::mutex lock_; // it is likely the outputhandler does some I/O, so we serialize it }; // we use this function because we want to handle static initialization correctly // however, the first run of this function is not thread safe, due to the use of a static // variable inside the function. For this reason, we ensure the first call happens during // static initialization using a proxy class static DefaultOutputHandler* getDOH(void) { static DefaultOutputHandler DOH; return &DOH; } #define USE_DOH \ DefaultOutputHandler *doh = getDOH(); \ std::lock_guard<std::mutex> lock_guard(doh->lock_) #define MAX_BUFFER_SIZE 1024 /// @endcond void console_bridge::noOutputHandler(void) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = NULL; } void console_bridge::restorePreviousOutputHandler(void) { USE_DOH; std::swap(doh->previous_output_handler_, doh->output_handler_); } void console_bridge::useOutputHandler(OutputHandler *oh) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = oh; } console_bridge::OutputHandler* console_bridge::getOutputHandler(void) { return getDOH()->output_handler_; } void console_bridge::log(const char *file, int line, LogLevel level, const char* m, ...) { USE_DOH; if (doh->output_handler_ && level >= doh->logLevel_) { va_list __ap; va_start(__ap, m); char buf[MAX_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), m, __ap); va_end(__ap); buf[MAX_BUFFER_SIZE - 1] = '\0'; doh->output_handler_->log(buf, level, file, line); } } void console_bridge::setLogLevel(LogLevel level) { USE_DOH; doh->logLevel_ = level; } console_bridge::LogLevel console_bridge::getLogLevel(void) { USE_DOH; return doh->logLevel_; } static const char* LogLevelString[4] = {"Debug: ", "Info: ", "Warning: ", "Error: "}; void console_bridge::OutputHandlerSTD::log(const std::string &text, LogLevel level, const char *filename, int line) { if (level >= CONSOLE_BRIDGE_LOG_WARN) { std::cerr << LogLevelString[level] << text << std::endl; std::cerr << " at line " << line << " in " << filename << std::endl; std::cerr.flush(); } else { std::cout << LogLevelString[level] << text << std::endl; std::cout.flush(); } } console_bridge::OutputHandlerFile::OutputHandlerFile(const char *filename) : OutputHandler() { file_ = fopen(filename, "a"); if (!file_) std::cerr << "Unable to open log file: '" << filename << "'" << std::endl; } console_bridge::OutputHandlerFile::~OutputHandlerFile(void) { if (file_) if (fclose(file_) != 0) std::cerr << "Error closing logfile" << std::endl; } void console_bridge::OutputHandlerFile::log(const std::string &text, LogLevel level, const char *filename, int line) { if (file_) { fprintf(file_, "%s%s\n", LogLevelString[level], text.c_str()); if(level >= CONSOLE_BRIDGE_LOG_WARN) fprintf(file_, " at line %d in %s\n", line, filename); fflush(file_); } } <commit_msg>Fix windows compiler warning<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ryan Luna, Ioan Sucan */ #include "console_bridge/console.h" #include <cstdio> #include <cstdarg> #include <iostream> #include <mutex> /// @cond IGNORE struct DefaultOutputHandler { DefaultOutputHandler(void) { output_handler_ = static_cast<console_bridge::OutputHandler*>(&std_output_handler_); previous_output_handler_ = output_handler_; logLevel_ = console_bridge::CONSOLE_BRIDGE_LOG_WARN; } console_bridge::OutputHandlerSTD std_output_handler_; console_bridge::OutputHandler *output_handler_; console_bridge::OutputHandler *previous_output_handler_; console_bridge::LogLevel logLevel_; std::mutex lock_; // it is likely the outputhandler does some I/O, so we serialize it }; // we use this function because we want to handle static initialization correctly // however, the first run of this function is not thread safe, due to the use of a static // variable inside the function. For this reason, we ensure the first call happens during // static initialization using a proxy class static DefaultOutputHandler* getDOH(void) { static DefaultOutputHandler DOH; return &DOH; } #define USE_DOH \ DefaultOutputHandler *doh = getDOH(); \ std::lock_guard<std::mutex> lock_guard(doh->lock_) #define MAX_BUFFER_SIZE 1024 /// @endcond void console_bridge::noOutputHandler(void) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = NULL; } void console_bridge::restorePreviousOutputHandler(void) { USE_DOH; std::swap(doh->previous_output_handler_, doh->output_handler_); } void console_bridge::useOutputHandler(OutputHandler *oh) { USE_DOH; doh->previous_output_handler_ = doh->output_handler_; doh->output_handler_ = oh; } console_bridge::OutputHandler* console_bridge::getOutputHandler(void) { return getDOH()->output_handler_; } void console_bridge::log(const char *file, int line, LogLevel level, const char* m, ...) { USE_DOH; if (doh->output_handler_ && level >= doh->logLevel_) { va_list __ap; va_start(__ap, m); char buf[MAX_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), m, __ap); va_end(__ap); buf[MAX_BUFFER_SIZE - 1] = '\0'; doh->output_handler_->log(buf, level, file, line); } } void console_bridge::setLogLevel(LogLevel level) { USE_DOH; doh->logLevel_ = level; } console_bridge::LogLevel console_bridge::getLogLevel(void) { USE_DOH; return doh->logLevel_; } static const char* LogLevelString[4] = {"Debug: ", "Info: ", "Warning: ", "Error: "}; void console_bridge::OutputHandlerSTD::log(const std::string &text, LogLevel level, const char *filename, int line) { if (level >= CONSOLE_BRIDGE_LOG_WARN) { std::cerr << LogLevelString[level] << text << std::endl; std::cerr << " at line " << line << " in " << filename << std::endl; std::cerr.flush(); } else { std::cout << LogLevelString[level] << text << std::endl; std::cout.flush(); } } console_bridge::OutputHandlerFile::OutputHandlerFile(const char *filename) : OutputHandler() { #ifdef _MSC_VER errno_t err = fopen_s(&file_, filename, "a"); if (err != 0 || !file_) #else file_ = fopen(filename, "a"); if (!file_) #endif std::cerr << "Unable to open log file: '" << filename << "'" << std::endl; } console_bridge::OutputHandlerFile::~OutputHandlerFile(void) { if (file_) if (fclose(file_) != 0) std::cerr << "Error closing logfile" << std::endl; } void console_bridge::OutputHandlerFile::log(const std::string &text, LogLevel level, const char *filename, int line) { if (file_) { fprintf(file_, "%s%s\n", LogLevelString[level], text.c_str()); if(level >= CONSOLE_BRIDGE_LOG_WARN) fprintf(file_, " at line %d in %s\n", line, filename); fflush(file_); } } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <mpd/client.h> #include "consumer.hh" #include "globals.hh" using namespace boost::filesystem; using namespace std; #include <fstream> Consumer::Consumer(string throwaway) : _playlist_file_(std::move(throwaway)) , _write_to_file_(true) { std::ifstream file(_playlist_file_); if (file) { string temp; while (getline(file, temp)) { _playlist_lines_.insert(temp); } } } void Consumer::_sorted_insert_song_(const std::string& str) { bool inserted = _playlist_lines_.insert(str).second; if (NONO && inserted) { printf("Insert `%s` into playlist `%s`.\n", str.c_str(), _playlist_file_.c_str()); } } Consumer::~Consumer() { if (_write_to_file_) { if (!NONO) { std::ofstream file(_playlist_file_); if (!file) throw std::runtime_error("Problem opening file " + _playlist_file_); for (const auto& s : _playlist_lines_) { file << s << '\n'; } if (USE_MPD) { _run_mpd_(); } } else if (USE_MPD) { printf("Will clear the mpd playlist, update the mpd " "database, and load %s.\n", path(_playlist_file_) .filename() .replace_extension() .c_str()); } } } #include <taglib/fileref.h> void Consumer::_apply_tags_(const path& path, const string& artist, const string& title) { using namespace TagLib; bool changed = false; FileRef file(path.c_str()); Tag* tags = file.tag(); if (!tags) { fprintf(stderr, "Music file `%s` has no tags!\n", path.c_str()); return; } if (tags->artist() != artist) { if (NONO) { printf(" Artist: `%s` -> `%s`\n", tags->artist().toCString(), artist.c_str()); } else { changed = true; tags->setArtist(artist); } } if (tags->title() != title) { if (NONO) { printf(" Title: `%s` -> `%s`\n", tags->title().toCString(), title.c_str()); } else { changed = true; tags->setTitle(title); } } if (changed) { file.save(); } } <commit_msg>In consumer.cc, remove double negative condition to test file validity.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <mpd/client.h> #include "consumer.hh" #include "globals.hh" using namespace boost::filesystem; using namespace std; #include <fstream> Consumer::Consumer(string throwaway) : _playlist_file_(std::move(throwaway)) , _write_to_file_(true) { std::ifstream file(_playlist_file_); if (file) { string temp; while (getline(file, temp)) { _playlist_lines_.insert(temp); } } } void Consumer::_sorted_insert_song_(const std::string& str) { bool inserted = _playlist_lines_.insert(str).second; if (NONO && inserted) { printf("Insert `%s` into playlist `%s`.\n", str.c_str(), _playlist_file_.c_str()); } } Consumer::~Consumer() { if (_write_to_file_) { if (!NONO) { std::ofstream file(_playlist_file_); if (file) { for (const auto& s : _playlist_lines_) { file << s << '\n'; } if (USE_MPD) { _run_mpd_(); } } else { throw std::runtime_error("Problem opening file " + _playlist_file_); } } else if (USE_MPD) { printf("Will clear the mpd playlist, update the mpd " "database, and load %s.\n", path(_playlist_file_) .filename() .replace_extension() .c_str()); } } } #include <taglib/fileref.h> void Consumer::_apply_tags_(const path& path, const string& artist, const string& title) { using namespace TagLib; bool changed = false; FileRef file(path.c_str()); Tag* tags = file.tag(); if (!tags) { fprintf(stderr, "Music file `%s` has no tags!\n", path.c_str()); return; } if (tags->artist() != artist) { if (NONO) { printf(" Artist: `%s` -> `%s`\n", tags->artist().toCString(), artist.c_str()); } else { changed = true; tags->setArtist(artist); } } if (tags->title() != title) { if (NONO) { printf(" Title: `%s` -> `%s`\n", tags->title().toCString(), title.c_str()); } else { changed = true; tags->setTitle(title); } } if (changed) { file.save(); } } <|endoftext|>
<commit_before>//===------- X86ExpandPseudo.cpp - Expand pseudo instructions -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a pass that expands pseudo instructions into target // instructions to allow proper scheduling, if-conversion, other late // optimizations, or simply the encoding of the instructions. // //===----------------------------------------------------------------------===// #include "X86.h" #include "X86FrameLowering.h" #include "X86InstrBuilder.h" #include "X86InstrInfo.h" #include "X86MachineFunctionInfo.h" #include "X86Subtarget.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved. #include "llvm/IR/GlobalValue.h" using namespace llvm; #define DEBUG_TYPE "x86-pseudo" namespace { class X86ExpandPseudo : public MachineFunctionPass { public: static char ID; X86ExpandPseudo() : MachineFunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addPreservedID(MachineLoopInfoID); AU.addPreservedID(MachineDominatorsID); MachineFunctionPass::getAnalysisUsage(AU); } const X86Subtarget *STI; const X86InstrInfo *TII; const X86RegisterInfo *TRI; const X86FrameLowering *X86FL; bool runOnMachineFunction(MachineFunction &Fn) override; const char *getPassName() const override { return "X86 pseudo instruction expansion pass"; } private: bool ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI); bool ExpandMBB(MachineBasicBlock &MBB); }; char X86ExpandPseudo::ID = 0; } // End anonymous namespace. /// If \p MBBI is a pseudo instruction, this method expands /// it to the corresponding (sequence of) actual instruction(s). /// \returns true if \p MBBI has been expanded. bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) { MachineInstr &MI = *MBBI; unsigned Opcode = MI.getOpcode(); DebugLoc DL = MBBI->getDebugLoc(); switch (Opcode) { default: return false; case X86::TCRETURNdi: case X86::TCRETURNri: case X86::TCRETURNmi: case X86::TCRETURNdi64: case X86::TCRETURNri64: case X86::TCRETURNmi64: { bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64; MachineOperand &JumpTarget = MBBI->getOperand(0); MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1); assert(StackAdjust.isImm() && "Expecting immediate value."); // Adjust stack pointer. int StackAdj = StackAdjust.getImm(); if (StackAdj) { // Check for possible merge with preceding ADD instruction. StackAdj += X86FL->mergeSPUpdates(MBB, MBBI, true); X86FL->emitSPUpdate(MBB, MBBI, StackAdj, /*InEpilogue=*/true); } // Jump to label or value in register. bool IsWin64 = STI->isTargetWin64(); if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdi64) { unsigned Op = (Opcode == X86::TCRETURNdi) ? X86::TAILJMPd : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); if (JumpTarget.isGlobal()) MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), JumpTarget.getTargetFlags()); else { assert(JumpTarget.isSymbol()); MIB.addExternalSymbol(JumpTarget.getSymbolName(), JumpTarget.getTargetFlags()); } } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) { unsigned Op = (Opcode == X86::TCRETURNmi) ? X86::TAILJMPm : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); for (unsigned i = 0; i != 5; ++i) MIB.addOperand(MBBI->getOperand(i)); } else if (Opcode == X86::TCRETURNri64) { BuildMI(MBB, MBBI, DL, TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64)) .addReg(JumpTarget.getReg(), RegState::Kill); } else { BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr)) .addReg(JumpTarget.getReg(), RegState::Kill); } MachineInstr *NewMI = std::prev(MBBI); NewMI->copyImplicitOps(*MBBI->getParent()->getParent(), MBBI); // Delete the pseudo instruction TCRETURN. MBB.erase(MBBI); return true; } case X86::EH_RETURN: case X86::EH_RETURN64: { MachineOperand &DestAddr = MBBI->getOperand(0); assert(DestAddr.isReg() && "Offset should be in register!"); const bool Uses64BitFramePtr = STI->isTarget64BitLP64() || STI->isTargetNaCl64(); unsigned StackPtr = TRI->getStackRegister(); BuildMI(MBB, MBBI, DL, TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr) .addReg(DestAddr.getReg()); // The EH_RETURN pseudo is really removed during the MC Lowering. return true; } case X86::IRET: { // Adjust stack to erase error code int64_t StackAdj = MBBI->getOperand(0).getImm(); X86FL->emitSPUpdate(MBB, MBBI, StackAdj, true); // Replace pseudo with machine iret BuildMI(MBB, MBBI, DL, TII->get(STI->is64Bit() ? X86::IRET64 : X86::IRET32)); MBB.erase(MBBI); return true; } case X86::EH_RESTORE: { // Restore ESP and EBP, and optionally ESI if required. bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality( MBB.getParent()->getFunction()->getPersonalityFn())); X86FL->restoreWin32EHStackPointers(MBB, MBBI, DL, /*RestoreSP=*/IsSEH); MBBI->eraseFromParent(); return true; } } llvm_unreachable("Previous switch has a fallthrough?"); } /// Expand all pseudo instructions contained in \p MBB. /// \returns true if any expansion occurred for \p MBB. bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) { bool Modified = false; // MBBI may be invalidated by the expansion. MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); while (MBBI != E) { MachineBasicBlock::iterator NMBBI = std::next(MBBI); Modified |= ExpandMI(MBB, MBBI); MBBI = NMBBI; } return Modified; } bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) { STI = &static_cast<const X86Subtarget &>(MF.getSubtarget()); TII = STI->getInstrInfo(); TRI = STI->getRegisterInfo(); X86FL = STI->getFrameLowering(); bool Modified = false; for (MachineBasicBlock &MBB : MF) Modified |= ExpandMBB(MBB); return Modified; } /// Returns an instance of the pseudo instruction expansion pass. FunctionPass *llvm::createX86ExpandPseudoPass() { return new X86ExpandPseudo(); } <commit_msg>Fix line endings after r256155. NFC.<commit_after>//===------- X86ExpandPseudo.cpp - Expand pseudo instructions -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a pass that expands pseudo instructions into target // instructions to allow proper scheduling, if-conversion, other late // optimizations, or simply the encoding of the instructions. // //===----------------------------------------------------------------------===// #include "X86.h" #include "X86FrameLowering.h" #include "X86InstrBuilder.h" #include "X86InstrInfo.h" #include "X86MachineFunctionInfo.h" #include "X86Subtarget.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved. #include "llvm/IR/GlobalValue.h" using namespace llvm; #define DEBUG_TYPE "x86-pseudo" namespace { class X86ExpandPseudo : public MachineFunctionPass { public: static char ID; X86ExpandPseudo() : MachineFunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addPreservedID(MachineLoopInfoID); AU.addPreservedID(MachineDominatorsID); MachineFunctionPass::getAnalysisUsage(AU); } const X86Subtarget *STI; const X86InstrInfo *TII; const X86RegisterInfo *TRI; const X86FrameLowering *X86FL; bool runOnMachineFunction(MachineFunction &Fn) override; const char *getPassName() const override { return "X86 pseudo instruction expansion pass"; } private: bool ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI); bool ExpandMBB(MachineBasicBlock &MBB); }; char X86ExpandPseudo::ID = 0; } // End anonymous namespace. /// If \p MBBI is a pseudo instruction, this method expands /// it to the corresponding (sequence of) actual instruction(s). /// \returns true if \p MBBI has been expanded. bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) { MachineInstr &MI = *MBBI; unsigned Opcode = MI.getOpcode(); DebugLoc DL = MBBI->getDebugLoc(); switch (Opcode) { default: return false; case X86::TCRETURNdi: case X86::TCRETURNri: case X86::TCRETURNmi: case X86::TCRETURNdi64: case X86::TCRETURNri64: case X86::TCRETURNmi64: { bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64; MachineOperand &JumpTarget = MBBI->getOperand(0); MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1); assert(StackAdjust.isImm() && "Expecting immediate value."); // Adjust stack pointer. int StackAdj = StackAdjust.getImm(); if (StackAdj) { // Check for possible merge with preceding ADD instruction. StackAdj += X86FL->mergeSPUpdates(MBB, MBBI, true); X86FL->emitSPUpdate(MBB, MBBI, StackAdj, /*InEpilogue=*/true); } // Jump to label or value in register. bool IsWin64 = STI->isTargetWin64(); if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdi64) { unsigned Op = (Opcode == X86::TCRETURNdi) ? X86::TAILJMPd : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); if (JumpTarget.isGlobal()) MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), JumpTarget.getTargetFlags()); else { assert(JumpTarget.isSymbol()); MIB.addExternalSymbol(JumpTarget.getSymbolName(), JumpTarget.getTargetFlags()); } } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) { unsigned Op = (Opcode == X86::TCRETURNmi) ? X86::TAILJMPm : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); for (unsigned i = 0; i != 5; ++i) MIB.addOperand(MBBI->getOperand(i)); } else if (Opcode == X86::TCRETURNri64) { BuildMI(MBB, MBBI, DL, TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64)) .addReg(JumpTarget.getReg(), RegState::Kill); } else { BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr)) .addReg(JumpTarget.getReg(), RegState::Kill); } MachineInstr *NewMI = std::prev(MBBI); NewMI->copyImplicitOps(*MBBI->getParent()->getParent(), MBBI); // Delete the pseudo instruction TCRETURN. MBB.erase(MBBI); return true; } case X86::EH_RETURN: case X86::EH_RETURN64: { MachineOperand &DestAddr = MBBI->getOperand(0); assert(DestAddr.isReg() && "Offset should be in register!"); const bool Uses64BitFramePtr = STI->isTarget64BitLP64() || STI->isTargetNaCl64(); unsigned StackPtr = TRI->getStackRegister(); BuildMI(MBB, MBBI, DL, TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr) .addReg(DestAddr.getReg()); // The EH_RETURN pseudo is really removed during the MC Lowering. return true; } case X86::IRET: { // Adjust stack to erase error code int64_t StackAdj = MBBI->getOperand(0).getImm(); X86FL->emitSPUpdate(MBB, MBBI, StackAdj, true); // Replace pseudo with machine iret BuildMI(MBB, MBBI, DL, TII->get(STI->is64Bit() ? X86::IRET64 : X86::IRET32)); MBB.erase(MBBI); return true; } case X86::EH_RESTORE: { // Restore ESP and EBP, and optionally ESI if required. bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality( MBB.getParent()->getFunction()->getPersonalityFn())); X86FL->restoreWin32EHStackPointers(MBB, MBBI, DL, /*RestoreSP=*/IsSEH); MBBI->eraseFromParent(); return true; } } llvm_unreachable("Previous switch has a fallthrough?"); } /// Expand all pseudo instructions contained in \p MBB. /// \returns true if any expansion occurred for \p MBB. bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) { bool Modified = false; // MBBI may be invalidated by the expansion. MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); while (MBBI != E) { MachineBasicBlock::iterator NMBBI = std::next(MBBI); Modified |= ExpandMI(MBB, MBBI); MBBI = NMBBI; } return Modified; } bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) { STI = &static_cast<const X86Subtarget &>(MF.getSubtarget()); TII = STI->getInstrInfo(); TRI = STI->getRegisterInfo(); X86FL = STI->getFrameLowering(); bool Modified = false; for (MachineBasicBlock &MBB : MF) Modified |= ExpandMBB(MBB); return Modified; } /// Returns an instance of the pseudo instruction expansion pass. FunctionPass *llvm::createX86ExpandPseudoPass() { return new X86ExpandPseudo(); } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "VertexArray.h" #include "../base/Exception.h" #include "../base/WideLine.h" #include "../base/ObjectCounter.h" #include <iostream> #include <stddef.h> #include <string.h> using namespace std; using namespace boost; namespace avg { thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLVertexBufferIDs; thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLIndexBufferIDs; VertexArray::VertexArray(int reserveVerts, int reserveIndexes) : m_NumVerts(0), m_NumIndexes(0), m_ReserveVerts(reserveVerts), m_ReserveIndexes(reserveIndexes), m_bDataChanged(true) { ObjectCounter::get()->incRef(&typeid(*this)); if (m_ReserveVerts < 10) { m_ReserveVerts = 10; } if (m_ReserveIndexes < 20) { m_ReserveIndexes = 20; } m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; m_pIndexData = new unsigned int[m_ReserveIndexes]; initBufferCache(); if (s_pGLVertexBufferIDs->empty() || m_ReserveVerts != 10 || m_ReserveIndexes != 20) { glproc::GenBuffers(1, &m_GLVertexBufferID); glproc::GenBuffers(1, &m_GLIndexBufferID); } else { m_GLVertexBufferID = s_pGLVertexBufferIDs->back(); s_pGLVertexBufferIDs->pop_back(); m_GLIndexBufferID = s_pGLIndexBufferIDs->back(); s_pGLIndexBufferIDs->pop_back(); } } VertexArray::~VertexArray() { if (m_ReserveVerts == 10) { s_pGLVertexBufferIDs->push_back(m_GLVertexBufferID); } else { glproc::DeleteBuffers(1, &m_GLVertexBufferID); } if (m_ReserveIndexes == 20) { s_pGLIndexBufferIDs->push_back(m_GLIndexBufferID); } else { glproc::DeleteBuffers(1, &m_GLIndexBufferID); } delete[] m_pVertexData; delete[] m_pIndexData; ObjectCounter::get()->decRef(&typeid(*this)); } void VertexArray::appendPos(const DPoint& pos, const DPoint& texPos, const Pixel32& color) { if (m_NumVerts >= m_ReserveVerts-1) { grow(); } T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]); pVertex->m_Pos[0] = (GLfloat)pos.x; pVertex->m_Pos[1] = (GLfloat)pos.y; pVertex->m_Pos[2] = 0.0; pVertex->m_Tex[0] = (GLfloat)texPos.x; pVertex->m_Tex[1] = (GLfloat)texPos.y; pVertex->m_Color = color; m_bDataChanged = true; m_NumVerts++; } void VertexArray::appendTriIndexes(int v0, int v1, int v2) { if (m_NumIndexes >= m_ReserveIndexes-3) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_NumIndexes += 3; } void VertexArray::appendQuadIndexes(int v0, int v1, int v2, int v3) { if (m_NumIndexes >= m_ReserveIndexes-6) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_pIndexData[m_NumIndexes+3] = v1; m_pIndexData[m_NumIndexes+4] = v2; m_pIndexData[m_NumIndexes+5] = v3; m_NumIndexes += 6; } void VertexArray::addLineData(Pixel32 color, const DPoint& p1, const DPoint& p2, double width, double tc1, double tc2) { WideLine wl(p1, p2, width); int curVertex = getCurVert(); appendPos(wl.pl0, DPoint(tc1, 1), color); appendPos(wl.pr0, DPoint(tc1, 0), color); appendPos(wl.pl1, DPoint(tc2, 1), color); appendPos(wl.pr1, DPoint(tc2, 0), color); appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2); } void VertexArray::reset() { m_NumVerts = 0; m_NumIndexes = 0; } void VertexArray::update() { if (m_bDataChanged) { glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID); glproc::BufferData(GL_ARRAY_BUFFER, m_ReserveVerts*sizeof(T2V3C4Vertex), 0, GL_DYNAMIC_DRAW); void * pBuffer = glproc::MapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(pBuffer, m_pVertexData, m_NumVerts*sizeof(T2V3C4Vertex)); glproc::UnmapBuffer(GL_ARRAY_BUFFER); glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID); glproc::BufferData(GL_ELEMENT_ARRAY_BUFFER, m_ReserveIndexes*sizeof(unsigned int), 0, GL_DYNAMIC_DRAW); pBuffer = glproc::MapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(pBuffer, m_pIndexData, m_NumIndexes*sizeof(unsigned int)); glproc::UnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::update"); } m_bDataChanged = false; } void VertexArray::draw() { update(); glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID); glTexCoordPointer(2, GL_FLOAT, sizeof(T2V3C4Vertex), 0); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(T2V3C4Vertex), (void *)(offsetof(T2V3C4Vertex, m_Color))); glVertexPointer(3, GL_FLOAT, sizeof(T2V3C4Vertex), (void *)(offsetof(T2V3C4Vertex, m_Pos))); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw:1"); glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID); glDrawElements(GL_TRIANGLES, m_NumIndexes, GL_UNSIGNED_INT, 0); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw():2"); } int VertexArray::getCurVert() const { return m_NumVerts; } int VertexArray::getCurIndex() const { return m_NumIndexes; } void VertexArray::grow() { bool bChanged = false; if (m_NumVerts >= m_ReserveVerts-1) { bChanged = true; int oldReserveVerts = m_ReserveVerts; m_ReserveVerts = int(m_ReserveVerts*1.5); if (m_ReserveVerts < m_NumVerts) { m_ReserveVerts = m_NumVerts; } T2V3C4Vertex* pVertexData = m_pVertexData; m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts); delete[] pVertexData; } if (m_NumIndexes >= m_ReserveIndexes-6) { bChanged = true; int oldReserveIndexes = m_ReserveIndexes; m_ReserveIndexes = int(m_ReserveIndexes*1.5); if (m_ReserveIndexes < m_NumIndexes) { m_ReserveIndexes = m_NumIndexes; } unsigned int * pIndexData = m_pIndexData; m_pIndexData = new unsigned int[m_ReserveIndexes]; memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes); delete[] pIndexData; } if (bChanged) { m_bDataChanged = true; } } void VertexArray::initBufferCache() { if (s_pGLVertexBufferIDs.get() == 0) { s_pGLVertexBufferIDs.reset(new vector<unsigned int>); } if (s_pGLIndexBufferIDs.get() == 0) { s_pGLIndexBufferIDs.reset(new vector<unsigned int>); } } void VertexArray::deleteBufferCache() { if (s_pGLVertexBufferIDs.get() != 0) { for (unsigned i=0; i<s_pGLVertexBufferIDs->size(); ++i) { glproc::DeleteBuffers(1, &((*s_pGLVertexBufferIDs)[i])); } s_pGLVertexBufferIDs->clear(); } if (s_pGLIndexBufferIDs.get() != 0) { for (unsigned i=0; i<s_pGLIndexBufferIDs->size(); ++i) { glproc::DeleteBuffers(1, &((*s_pGLIndexBufferIDs)[i])); } s_pGLIndexBufferIDs->clear(); } } } <commit_msg>Fixed bug in vertex buffer caching across multiple Player.play() calls.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "VertexArray.h" #include "../base/Exception.h" #include "../base/WideLine.h" #include "../base/ObjectCounter.h" #include <iostream> #include <stddef.h> #include <string.h> using namespace std; using namespace boost; namespace avg { thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLVertexBufferIDs; thread_specific_ptr<vector<unsigned int> > VertexArray::s_pGLIndexBufferIDs; VertexArray::VertexArray(int reserveVerts, int reserveIndexes) : m_NumVerts(0), m_NumIndexes(0), m_ReserveVerts(reserveVerts), m_ReserveIndexes(reserveIndexes), m_bDataChanged(true) { ObjectCounter::get()->incRef(&typeid(*this)); if (m_ReserveVerts < 10) { m_ReserveVerts = 10; } if (m_ReserveIndexes < 20) { m_ReserveIndexes = 20; } m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; m_pIndexData = new unsigned int[m_ReserveIndexes]; initBufferCache(); if (s_pGLVertexBufferIDs->empty() || m_ReserveVerts != 10 || m_ReserveIndexes != 20) { glproc::GenBuffers(1, &m_GLVertexBufferID); glproc::GenBuffers(1, &m_GLIndexBufferID); } else { m_GLVertexBufferID = s_pGLVertexBufferIDs->back(); s_pGLVertexBufferIDs->pop_back(); m_GLIndexBufferID = s_pGLIndexBufferIDs->back(); s_pGLIndexBufferIDs->pop_back(); } } VertexArray::~VertexArray() { if (m_ReserveVerts == 10 && s_pGLVertexBufferIDs.get() != 0) { s_pGLVertexBufferIDs->push_back(m_GLVertexBufferID); } else { glproc::DeleteBuffers(1, &m_GLVertexBufferID); } if (m_ReserveIndexes == 20 && s_pGLIndexBufferIDs.get() != 0) { s_pGLIndexBufferIDs->push_back(m_GLIndexBufferID); } else { glproc::DeleteBuffers(1, &m_GLIndexBufferID); } delete[] m_pVertexData; delete[] m_pIndexData; ObjectCounter::get()->decRef(&typeid(*this)); } void VertexArray::appendPos(const DPoint& pos, const DPoint& texPos, const Pixel32& color) { if (m_NumVerts >= m_ReserveVerts-1) { grow(); } T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]); pVertex->m_Pos[0] = (GLfloat)pos.x; pVertex->m_Pos[1] = (GLfloat)pos.y; pVertex->m_Pos[2] = 0.0; pVertex->m_Tex[0] = (GLfloat)texPos.x; pVertex->m_Tex[1] = (GLfloat)texPos.y; pVertex->m_Color = color; m_bDataChanged = true; m_NumVerts++; } void VertexArray::appendTriIndexes(int v0, int v1, int v2) { if (m_NumIndexes >= m_ReserveIndexes-3) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_NumIndexes += 3; } void VertexArray::appendQuadIndexes(int v0, int v1, int v2, int v3) { if (m_NumIndexes >= m_ReserveIndexes-6) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_pIndexData[m_NumIndexes+3] = v1; m_pIndexData[m_NumIndexes+4] = v2; m_pIndexData[m_NumIndexes+5] = v3; m_NumIndexes += 6; } void VertexArray::addLineData(Pixel32 color, const DPoint& p1, const DPoint& p2, double width, double tc1, double tc2) { WideLine wl(p1, p2, width); int curVertex = getCurVert(); appendPos(wl.pl0, DPoint(tc1, 1), color); appendPos(wl.pr0, DPoint(tc1, 0), color); appendPos(wl.pl1, DPoint(tc2, 1), color); appendPos(wl.pr1, DPoint(tc2, 0), color); appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2); } void VertexArray::reset() { m_NumVerts = 0; m_NumIndexes = 0; } void VertexArray::update() { if (m_bDataChanged) { glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID); glproc::BufferData(GL_ARRAY_BUFFER, m_ReserveVerts*sizeof(T2V3C4Vertex), 0, GL_DYNAMIC_DRAW); void * pBuffer = glproc::MapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(pBuffer, m_pVertexData, m_NumVerts*sizeof(T2V3C4Vertex)); glproc::UnmapBuffer(GL_ARRAY_BUFFER); glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID); glproc::BufferData(GL_ELEMENT_ARRAY_BUFFER, m_ReserveIndexes*sizeof(unsigned int), 0, GL_DYNAMIC_DRAW); pBuffer = glproc::MapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(pBuffer, m_pIndexData, m_NumIndexes*sizeof(unsigned int)); glproc::UnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::update"); } m_bDataChanged = false; } void VertexArray::draw() { update(); glproc::BindBuffer(GL_ARRAY_BUFFER, m_GLVertexBufferID); glTexCoordPointer(2, GL_FLOAT, sizeof(T2V3C4Vertex), 0); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(T2V3C4Vertex), (void *)(offsetof(T2V3C4Vertex, m_Color))); glVertexPointer(3, GL_FLOAT, sizeof(T2V3C4Vertex), (void *)(offsetof(T2V3C4Vertex, m_Pos))); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw:1"); glproc::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLIndexBufferID); glDrawElements(GL_TRIANGLES, m_NumIndexes, GL_UNSIGNED_INT, 0); OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "VertexArray::draw():2"); } int VertexArray::getCurVert() const { return m_NumVerts; } int VertexArray::getCurIndex() const { return m_NumIndexes; } void VertexArray::grow() { bool bChanged = false; if (m_NumVerts >= m_ReserveVerts-1) { bChanged = true; int oldReserveVerts = m_ReserveVerts; m_ReserveVerts = int(m_ReserveVerts*1.5); if (m_ReserveVerts < m_NumVerts) { m_ReserveVerts = m_NumVerts; } T2V3C4Vertex* pVertexData = m_pVertexData; m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts); delete[] pVertexData; } if (m_NumIndexes >= m_ReserveIndexes-6) { bChanged = true; int oldReserveIndexes = m_ReserveIndexes; m_ReserveIndexes = int(m_ReserveIndexes*1.5); if (m_ReserveIndexes < m_NumIndexes) { m_ReserveIndexes = m_NumIndexes; } unsigned int * pIndexData = m_pIndexData; m_pIndexData = new unsigned int[m_ReserveIndexes]; memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes); delete[] pIndexData; } if (bChanged) { m_bDataChanged = true; } } void VertexArray::initBufferCache() { if (s_pGLVertexBufferIDs.get() == 0) { s_pGLVertexBufferIDs.reset(new vector<unsigned int>); } if (s_pGLIndexBufferIDs.get() == 0) { s_pGLIndexBufferIDs.reset(new vector<unsigned int>); } } void VertexArray::deleteBufferCache() { if (s_pGLVertexBufferIDs.get() != 0) { for (unsigned i=0; i<s_pGLVertexBufferIDs->size(); ++i) { glproc::DeleteBuffers(1, &((*s_pGLVertexBufferIDs)[i])); } s_pGLVertexBufferIDs->clear(); s_pGLVertexBufferIDs.reset(); } if (s_pGLIndexBufferIDs.get() != 0) { for (unsigned i=0; i<s_pGLIndexBufferIDs->size(); ++i) { glproc::DeleteBuffers(1, &((*s_pGLIndexBufferIDs)[i])); } s_pGLIndexBufferIDs->clear(); s_pGLIndexBufferIDs.reset(); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkShepardMethod.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ #include "vtkShepardMethod.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" vtkStandardNewMacro(vtkShepardMethod); // Construct with sample dimensions=(50,50,50) and so that model bounds are // automatically computed from input. Null value for each unvisited output // point is 0.0. Maximum distance is 0.25. vtkShepardMethod::vtkShepardMethod() { this->MaximumDistance = 0.25; this->ModelBounds[0] = 0.0; this->ModelBounds[1] = 0.0; this->ModelBounds[2] = 0.0; this->ModelBounds[3] = 0.0; this->ModelBounds[4] = 0.0; this->ModelBounds[5] = 0.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->NullValue = 0.0; } // Compute ModelBounds from input geometry. double vtkShepardMethod::ComputeModelBounds(double origin[3], double spacing[3]) { double *bounds, maxDist; int i, adjustBounds=0; // compute model bounds if not set previously if ( this->ModelBounds[0] >= this->ModelBounds[1] || this->ModelBounds[2] >= this->ModelBounds[3] || this->ModelBounds[4] >= this->ModelBounds[5] ) { adjustBounds = 1; vtkDataSet *ds = vtkDataSet::SafeDownCast(this->GetInput()); // ds better be non null otherwise something is very wrong here bounds = ds->GetBounds(); } else { bounds = this->ModelBounds; } for (maxDist=0.0, i=0; i<3; i++) { if ( (bounds[2*i+1] - bounds[2*i]) > maxDist ) { maxDist = bounds[2*i+1] - bounds[2*i]; } } maxDist *= this->MaximumDistance; // adjust bounds so model fits strictly inside (only if not set previously) if ( adjustBounds ) { for (i=0; i<3; i++) { this->ModelBounds[2*i] = bounds[2*i] - maxDist; this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist; } } // Set volume origin and data spacing for (i=0; i<3; i++) { origin[i] = this->ModelBounds[2*i]; spacing[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } return maxDist; } int vtkShepardMethod::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed( inputVector ), vtkInformationVector *outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); int i; double ar[3], origin[3]; outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), 0, this->SampleDimensions[0]-1, 0, this->SampleDimensions[1]-1, 0, this->SampleDimensions[2]-1); for (i=0; i < 3; i++) { origin[i] = this->ModelBounds[2*i]; if ( this->SampleDimensions[i] <= 1 ) { ar[i] = 1; } else { ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } } outInfo->Set(vtkDataObject::ORIGIN(),origin,3); outInfo->Set(vtkDataObject::SPACING(),ar,3); vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1); return 1; } int vtkShepardMethod::RequestData( vtkInformation* vtkNotUsed( request ), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the input vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); // get the output vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkImageData *output = vtkImageData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // We need to allocate our own scalars since we are overriding // the superclasses "Execute()" method. output->SetExtent( outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT())); output->AllocateScalars(outInfo); vtkIdType ptId, i; int j, k; double *px, x[3], s, *sum, spacing[3], origin[3]; double maxDistance, distance2, inScalar; vtkDataArray *inScalars; vtkIdType numPts, numNewPts, idx; int min[3], max[3]; int jkFactor; vtkFloatArray *newScalars = vtkFloatArray::SafeDownCast(output->GetPointData()->GetScalars()); vtkDebugMacro(<< "Executing Shepard method"); // Check input // if ( (numPts=input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"Points must be defined!"); return 1; } if ( (inScalars = input->GetPointData()->GetScalars()) == NULL ) { vtkErrorMacro(<<"Scalars must be defined!"); return 1; } newScalars->SetName(inScalars->GetName()); // Allocate // numNewPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; sum = new double[numNewPts]; for (i=0; i<numNewPts; i++) { newScalars->SetComponent(i,0,0.0); sum[i] = 0.0; } maxDistance = this->ComputeModelBounds(origin,spacing); outInfo->Set(vtkDataObject::ORIGIN(),origin,3); outInfo->Set(vtkDataObject::SPACING(),spacing,3); // Traverse all input points. // Each input point affects voxels within maxDistance. // int abortExecute=0; for (ptId=0; ptId < numPts && !abortExecute; ptId++) { if ( ! (ptId % 1000) ) { vtkDebugMacro(<<"Inserting point #" << ptId); this->UpdateProgress (ptId/numPts); if (this->GetAbortExecute()) { abortExecute = 1; break; } } px = input->GetPoint(ptId); inScalar = inScalars->GetComponent(ptId,0); for (i=0; i<3; i++) //compute dimensional bounds in data set { double amin = static_cast<double>( (px[i] - maxDistance) - origin[i]) / spacing[i]; double amax = static_cast<double>( (px[i] + maxDistance) - origin[i]) / spacing[i]; min[i] = static_cast<int>(amin); max[i] = static_cast<int>(amax); if (min[i] < amin) { min[i]++; // round upward to nearest integer to get min[i] } if (max[i] > amax) { max[i]--; // round downward to nearest integer to get max[i] } if (min[i] < 0) { min[i] = 0; // valid range check } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } for (i=0; i<3; i++) //compute dimensional bounds in data set { min[i] = static_cast<int>( static_cast<double>((px[i] - maxDistance) - origin[i]) / spacing[i]); max[i] = static_cast<int>( static_cast<double>((px[i] + maxDistance) - origin[i]) / spacing[i]); if (min[i] < 0) { min[i] = 0; } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1]; for (k = min[2]; k <= max[2]; k++) { x[2] = spacing[2] * k + origin[2]; for (j = min[1]; j <= max[1]; j++) { x[1] = spacing[1] * j + origin[1]; for (i = min[0]; i <= max[0]; i++) { x[0] = spacing[0] * i + origin[0]; idx = jkFactor*k + this->SampleDimensions[0]*j + i; distance2 = vtkMath::Distance2BetweenPoints(x,px); if ( distance2 == 0.0 ) { sum[idx] = VTK_DOUBLE_MAX; newScalars->SetComponent(idx,0,VTK_FLOAT_MAX); } else { s = newScalars->GetComponent(idx,0); sum[idx] += 1.0 / distance2; newScalars->SetComponent(idx,0,s+(inScalar/distance2)); } } } } } // Run through scalars and compute final values // for (ptId=0; ptId<numNewPts; ptId++) { s = newScalars->GetComponent(ptId,0); if ( sum[ptId] != 0.0 ) { newScalars->SetComponent(ptId,0,s/sum[ptId]); } else { newScalars->SetComponent(ptId,0,this->NullValue); } } // Update self // delete [] sum; return 1; } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int dim[3]) { int dataDim, i; vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != this->SampleDimensions[1] || dim[2] != this->SampleDimensions[2] ) { if ( dim[0]<1 || dim[1]<1 || dim[2]<1 ) { vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values"); return; } for (dataDim=0, i=0; i<3 ; i++) { if (dim[i] > 1) { dataDim++; } } if ( dataDim < 3 ) { vtkErrorMacro(<<"Sample dimensions must define a volume!"); return; } for ( i=0; i<3; i++) { this->SampleDimensions[i] = dim[i]; } this->Modified(); } } int vtkShepardMethod::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); return 1; } void vtkShepardMethod::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Maximum Distance: " << this->MaximumDistance << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Null Value: " << this->NullValue << "\n"; } <commit_msg>fix warning by eliminating redundant loop termination variable<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkShepardMethod.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ #include "vtkShepardMethod.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" vtkStandardNewMacro(vtkShepardMethod); // Construct with sample dimensions=(50,50,50) and so that model bounds are // automatically computed from input. Null value for each unvisited output // point is 0.0. Maximum distance is 0.25. vtkShepardMethod::vtkShepardMethod() { this->MaximumDistance = 0.25; this->ModelBounds[0] = 0.0; this->ModelBounds[1] = 0.0; this->ModelBounds[2] = 0.0; this->ModelBounds[3] = 0.0; this->ModelBounds[4] = 0.0; this->ModelBounds[5] = 0.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->NullValue = 0.0; } // Compute ModelBounds from input geometry. double vtkShepardMethod::ComputeModelBounds(double origin[3], double spacing[3]) { double *bounds, maxDist; int i, adjustBounds=0; // compute model bounds if not set previously if ( this->ModelBounds[0] >= this->ModelBounds[1] || this->ModelBounds[2] >= this->ModelBounds[3] || this->ModelBounds[4] >= this->ModelBounds[5] ) { adjustBounds = 1; vtkDataSet *ds = vtkDataSet::SafeDownCast(this->GetInput()); // ds better be non null otherwise something is very wrong here bounds = ds->GetBounds(); } else { bounds = this->ModelBounds; } for (maxDist=0.0, i=0; i<3; i++) { if ( (bounds[2*i+1] - bounds[2*i]) > maxDist ) { maxDist = bounds[2*i+1] - bounds[2*i]; } } maxDist *= this->MaximumDistance; // adjust bounds so model fits strictly inside (only if not set previously) if ( adjustBounds ) { for (i=0; i<3; i++) { this->ModelBounds[2*i] = bounds[2*i] - maxDist; this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist; } } // Set volume origin and data spacing for (i=0; i<3; i++) { origin[i] = this->ModelBounds[2*i]; spacing[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } return maxDist; } int vtkShepardMethod::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed( inputVector ), vtkInformationVector *outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); int i; double ar[3], origin[3]; outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), 0, this->SampleDimensions[0]-1, 0, this->SampleDimensions[1]-1, 0, this->SampleDimensions[2]-1); for (i=0; i < 3; i++) { origin[i] = this->ModelBounds[2*i]; if ( this->SampleDimensions[i] <= 1 ) { ar[i] = 1; } else { ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } } outInfo->Set(vtkDataObject::ORIGIN(),origin,3); outInfo->Set(vtkDataObject::SPACING(),ar,3); vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1); return 1; } int vtkShepardMethod::RequestData( vtkInformation* vtkNotUsed( request ), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the input vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); // get the output vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkImageData *output = vtkImageData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // We need to allocate our own scalars since we are overriding // the superclasses "Execute()" method. output->SetExtent( outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT())); output->AllocateScalars(outInfo); vtkIdType ptId, i; int j, k; double *px, x[3], s, *sum, spacing[3], origin[3]; double maxDistance, distance2, inScalar; vtkDataArray *inScalars; vtkIdType numPts, numNewPts, idx; int min[3], max[3]; int jkFactor; vtkFloatArray *newScalars = vtkFloatArray::SafeDownCast(output->GetPointData()->GetScalars()); vtkDebugMacro(<< "Executing Shepard method"); // Check input // if ( (numPts=input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"Points must be defined!"); return 1; } if ( (inScalars = input->GetPointData()->GetScalars()) == NULL ) { vtkErrorMacro(<<"Scalars must be defined!"); return 1; } newScalars->SetName(inScalars->GetName()); // Allocate // numNewPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; sum = new double[numNewPts]; for (i=0; i<numNewPts; i++) { newScalars->SetComponent(i,0,0.0); sum[i] = 0.0; } maxDistance = this->ComputeModelBounds(origin,spacing); outInfo->Set(vtkDataObject::ORIGIN(),origin,3); outInfo->Set(vtkDataObject::SPACING(),spacing,3); // Traverse all input points. // Each input point affects voxels within maxDistance. // for (ptId=0; ptId < numPts; ptId++) { if ( ! (ptId % 1000) ) { vtkDebugMacro(<<"Inserting point #" << ptId); this->UpdateProgress (ptId/numPts); if (this->GetAbortExecute()) { break; } } px = input->GetPoint(ptId); inScalar = inScalars->GetComponent(ptId,0); for (i=0; i<3; i++) //compute dimensional bounds in data set { double amin = static_cast<double>( (px[i] - maxDistance) - origin[i]) / spacing[i]; double amax = static_cast<double>( (px[i] + maxDistance) - origin[i]) / spacing[i]; min[i] = static_cast<int>(amin); max[i] = static_cast<int>(amax); if (min[i] < amin) { min[i]++; // round upward to nearest integer to get min[i] } if (max[i] > amax) { max[i]--; // round downward to nearest integer to get max[i] } if (min[i] < 0) { min[i] = 0; // valid range check } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } for (i=0; i<3; i++) //compute dimensional bounds in data set { min[i] = static_cast<int>( static_cast<double>((px[i] - maxDistance) - origin[i]) / spacing[i]); max[i] = static_cast<int>( static_cast<double>((px[i] + maxDistance) - origin[i]) / spacing[i]); if (min[i] < 0) { min[i] = 0; } if (max[i] >= this->SampleDimensions[i]) { max[i] = this->SampleDimensions[i] - 1; } } jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1]; for (k = min[2]; k <= max[2]; k++) { x[2] = spacing[2] * k + origin[2]; for (j = min[1]; j <= max[1]; j++) { x[1] = spacing[1] * j + origin[1]; for (i = min[0]; i <= max[0]; i++) { x[0] = spacing[0] * i + origin[0]; idx = jkFactor*k + this->SampleDimensions[0]*j + i; distance2 = vtkMath::Distance2BetweenPoints(x,px); if ( distance2 == 0.0 ) { sum[idx] = VTK_DOUBLE_MAX; newScalars->SetComponent(idx,0,VTK_FLOAT_MAX); } else { s = newScalars->GetComponent(idx,0); sum[idx] += 1.0 / distance2; newScalars->SetComponent(idx,0,s+(inScalar/distance2)); } } } } } // Run through scalars and compute final values // for (ptId=0; ptId<numNewPts; ptId++) { s = newScalars->GetComponent(ptId,0); if ( sum[ptId] != 0.0 ) { newScalars->SetComponent(ptId,0,s/sum[ptId]); } else { newScalars->SetComponent(ptId,0,this->NullValue); } } // Update self // delete [] sum; return 1; } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int dim[3]) { int dataDim, i; vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != this->SampleDimensions[1] || dim[2] != this->SampleDimensions[2] ) { if ( dim[0]<1 || dim[1]<1 || dim[2]<1 ) { vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values"); return; } for (dataDim=0, i=0; i<3 ; i++) { if (dim[i] > 1) { dataDim++; } } if ( dataDim < 3 ) { vtkErrorMacro(<<"Sample dimensions must define a volume!"); return; } for ( i=0; i<3; i++) { this->SampleDimensions[i] = dim[i]; } this->Modified(); } } int vtkShepardMethod::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); return 1; } void vtkShepardMethod::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Maximum Distance: " << this->MaximumDistance << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Null Value: " << this->NullValue << "\n"; } <|endoftext|>
<commit_before>/** * echo.cpp - echo serial characters back * * connect using putty/hyperterm/minicom .. 9600-8-N-1 * what ever you type is echoed back */ #include <fabooh.h> #include <main.h> #include <serial.h> namespace { const uint32_t BAUD_RATE = 9600; serial_default_t<BAUD_RATE, CPU::frequency, TX_PIN, RX_PIN> Serial; // TX=varies, RX=varies const char *prompt = "\r\ntype here: "; } void setup() { Serial.begin(BAUD_RATE); // configure serial device for Timer or SW only serial } void loop() { Serial.print(prompt); for (;;) { int c; // use a blocking read to get a character switch ((c = Serial.read())) { case '\r': return; default: Serial.write(c); break; } } } <commit_msg>make demo compatible with g2231 and g2452<commit_after>/** * echo.cpp - echo serial characters back * * connect using putty/hyperterm/minicom .. 9600-8-N-1 * what ever you type is echoed back */ #include <fabooh.h> #include <main.h> #include <serial.h> namespace { const uint32_t BAUD_RATE = 9600; #if defined(__MSP430G2231__) || defined(__MSP430G2452__) timer_serial_t<BAUD_RATE, CPU::frequency, TX_PIN, RX_PIN> Serial; // TX=varies, RX=varies #else serial_default_t<BAUD_RATE, CPU::frequency, TX_PIN, RX_PIN> Serial; // TX=varies, RX=varies #endif const char *prompt = "\r\ntype here:\r"; } void setup() { Serial.begin(BAUD_RATE); // configure serial device for Timer or SW only serial } void loop() { Serial.print(prompt); for (;;) { int c; // use a blocking read to get a character switch ((c = Serial.read())) { case '\r': return; default: Serial.write(c); break; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: urp_bridgeimpl.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: svesik $ $Date: 2004-04-21 13:44:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <osl/thread.h> #include <bridges/remote/helper.hxx> #include <algorithm> #include "urp_bridgeimpl.hxx" using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; namespace bridges_urp { template < class t > inline t mymin( const t & val1, const t & val2 ) { return val1 < val2 ? val1 : val2; } /*********** * urp_BridgeImpl ***********/ urp_BridgeImpl::urp_BridgeImpl( sal_Int32 nCacheSize , sal_uInt32 nInitialMarshalerSize ) : m_blockMarshaler( this , nInitialMarshalerSize , ::bridges_remote::remote_retrieveOidFromProxy), m_nMarshaledMessages( 0 ), m_oidCacheOut( (sal_uInt16)nCacheSize ), m_tidCacheOut( (sal_uInt16)nCacheSize ), m_typeCacheOut( (sal_uInt16)nCacheSize ) { m_pOidIn = new OUString[ nCacheSize ]; m_pTidIn = new ByteSequence[ nCacheSize ]; m_pTypeIn = new Type[ nCacheSize ]; m_nRemoteThreads = 0; } urp_BridgeImpl::~urp_BridgeImpl() { delete [] m_pOidIn; delete [] m_pTidIn; delete [] m_pTypeIn; } void urp_BridgeImpl::applyProtocolChanges( const Properties &props ) { if( m_properties.nTypeCacheSize != props.nTypeCacheSize ) { if( props.nTypeCacheSize == 0 ) { delete [] m_pTypeIn; m_pTypeIn = 0; } else { Type *pNew = new Type[props.nTypeCacheSize]; sal_Int32 i; sal_Int32 iMin = mymin( m_properties.nTypeCacheSize , props.nTypeCacheSize ); for( i = 0; i < iMin ; i ++ ) { pNew[i] = m_pTypeIn[i]; } delete [] m_pTypeIn; m_pTypeIn = pNew; } OSL_ASSERT( props.nTypeCacheSize <= 0xffff ); m_properties.nTypeCacheSize = props.nTypeCacheSize; m_typeCacheOut.resize( (sal_uInt16)props.nTypeCacheSize ); } if( m_properties.nOidCacheSize != props.nOidCacheSize ) { if( 0 == props.nOidCacheSize ) { delete [] m_pOidIn; m_pOidIn = 0; } else { OUString *pNew = new OUString[props.nOidCacheSize]; sal_Int32 i; sal_Int32 iMin = mymin( m_properties.nOidCacheSize , props.nOidCacheSize ); for( i = 0; i < iMin ; i ++ ) { pNew[i] = m_pOidIn[i]; } delete [] m_pOidIn; m_pOidIn = pNew; } OSL_ASSERT( props.nOidCacheSize <= 0xffff ); m_oidCacheOut.resize( (sal_uInt16)props.nOidCacheSize ); m_properties.nOidCacheSize = props.nOidCacheSize; } if( m_properties.nTidCacheSize != props.nTidCacheSize ) { if( 0 == props.nTidCacheSize ) { delete [] m_pTidIn; m_pTidIn = 0; } else { ByteSequence *pNew = new ByteSequence[props.nTidCacheSize]; sal_Int32 i; sal_Int32 iMin = mymin( m_properties.nTidCacheSize , props.nTidCacheSize ); for( i = 0; i < iMin ; i ++ ) { pNew[i] = m_pTidIn[i]; } delete [] m_pTidIn; m_pTidIn = pNew; } OSL_ASSERT( props.nTidCacheSize <= 0xffff ); m_tidCacheOut.resize( (sal_uInt16)props.nTidCacheSize ); m_properties.nTidCacheSize = props.nTidCacheSize; } if( m_properties.sVersion != props.sVersion ) { m_properties.sVersion = props.sVersion; } if( m_properties.nFlushBlockSize != props.nFlushBlockSize ) { m_properties.nFlushBlockSize = props.nFlushBlockSize; } if( m_properties.nOnewayTimeoutMUSEC != props.nOnewayTimeoutMUSEC ) { m_properties.nOnewayTimeoutMUSEC = props.nOnewayTimeoutMUSEC; } if( props.bClearCache ) { if( m_properties.nTypeCacheSize ) { delete [] m_pTypeIn; m_pTypeIn = new Type[m_properties.nTypeCacheSize]; m_typeCacheOut.clear(); } m_lastInType = Type(); m_lastOutType = Type(); if( m_properties.nOidCacheSize ) { delete [] m_pOidIn; m_pOidIn = new OUString[ m_properties.nOidCacheSize]; m_oidCacheOut.clear(); } m_lastOutOid = OUString(); m_lastInOid = OUString(); if( m_properties.nTidCacheSize ) { delete [] m_pTidIn; m_pTidIn = new ByteSequence[m_properties.nTidCacheSize]; m_tidCacheOut.clear(); } m_lastInTid = ByteSequence(); m_lastOutTid = ByteSequence(); } if( m_properties.bNegotiate != props.bNegotiate ) { m_properties.bNegotiate = props.bNegotiate; } if( m_properties.bForceSynchronous != props.bForceSynchronous ) { m_properties.bForceSynchronous = props.bForceSynchronous; } } void urp_BridgeImpl::addError( char *pError ) { OUString message = OUString( RTL_CONSTASCII_USTRINGPARAM( "(tid=" ) ); message += OUString::valueOf( (sal_Int32 ) osl_getThreadIdentifier( 0 ) ); message += OUString::createFromAscii( ") " ); message += OUString::createFromAscii( pError ); MutexGuard guard( m_errorListMutex ); m_lstErrors.push_back( message ); } void urp_BridgeImpl::addError( const OUString & error ) { OUString message = OUString( RTL_CONSTASCII_USTRINGPARAM( "(tid=" ) ); message += OUString::valueOf( (sal_Int32 ) osl_getThreadIdentifier( 0 ) ); message += OUString::createFromAscii( ") " ); message += error; MutexGuard guard( m_errorListMutex ); m_lstErrors.push_back( message ); } void urp_BridgeImpl::dumpErrors( FILE * f) { MutexGuard guard( m_errorListMutex ); for( ::std::list< OUString >::iterator ii = m_lstErrors.begin() ; ii != m_lstErrors.end() ; ++ii ) { OString o = OUStringToOString( *ii , RTL_TEXTENCODING_UTF8 ); fprintf( f, "%s\n" , o.getStr() ); } } OUString urp_BridgeImpl::getErrorsAsString( ) { MutexGuard guard( m_errorListMutex ); OUString ret; for( ::std::list< OUString >::iterator ii = m_lstErrors.begin() ; ii != m_lstErrors.end() ; ++ii ) { ret += *ii; } return ret; } } <commit_msg>INTEGRATION: CWS ooo19126 (1.8.86); FILE MERGED 2005/09/05 17:07:53 rt 1.8.86.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: urp_bridgeimpl.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-07 22:44:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <osl/thread.h> #include <bridges/remote/helper.hxx> #include <algorithm> #include "urp_bridgeimpl.hxx" using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; namespace bridges_urp { template < class t > inline t mymin( const t & val1, const t & val2 ) { return val1 < val2 ? val1 : val2; } /*********** * urp_BridgeImpl ***********/ urp_BridgeImpl::urp_BridgeImpl( sal_Int32 nCacheSize , sal_uInt32 nInitialMarshalerSize ) : m_blockMarshaler( this , nInitialMarshalerSize , ::bridges_remote::remote_retrieveOidFromProxy), m_nMarshaledMessages( 0 ), m_oidCacheOut( (sal_uInt16)nCacheSize ), m_tidCacheOut( (sal_uInt16)nCacheSize ), m_typeCacheOut( (sal_uInt16)nCacheSize ) { m_pOidIn = new OUString[ nCacheSize ]; m_pTidIn = new ByteSequence[ nCacheSize ]; m_pTypeIn = new Type[ nCacheSize ]; m_nRemoteThreads = 0; } urp_BridgeImpl::~urp_BridgeImpl() { delete [] m_pOidIn; delete [] m_pTidIn; delete [] m_pTypeIn; } void urp_BridgeImpl::applyProtocolChanges( const Properties &props ) { if( m_properties.nTypeCacheSize != props.nTypeCacheSize ) { if( props.nTypeCacheSize == 0 ) { delete [] m_pTypeIn; m_pTypeIn = 0; } else { Type *pNew = new Type[props.nTypeCacheSize]; sal_Int32 i; sal_Int32 iMin = mymin( m_properties.nTypeCacheSize , props.nTypeCacheSize ); for( i = 0; i < iMin ; i ++ ) { pNew[i] = m_pTypeIn[i]; } delete [] m_pTypeIn; m_pTypeIn = pNew; } OSL_ASSERT( props.nTypeCacheSize <= 0xffff ); m_properties.nTypeCacheSize = props.nTypeCacheSize; m_typeCacheOut.resize( (sal_uInt16)props.nTypeCacheSize ); } if( m_properties.nOidCacheSize != props.nOidCacheSize ) { if( 0 == props.nOidCacheSize ) { delete [] m_pOidIn; m_pOidIn = 0; } else { OUString *pNew = new OUString[props.nOidCacheSize]; sal_Int32 i; sal_Int32 iMin = mymin( m_properties.nOidCacheSize , props.nOidCacheSize ); for( i = 0; i < iMin ; i ++ ) { pNew[i] = m_pOidIn[i]; } delete [] m_pOidIn; m_pOidIn = pNew; } OSL_ASSERT( props.nOidCacheSize <= 0xffff ); m_oidCacheOut.resize( (sal_uInt16)props.nOidCacheSize ); m_properties.nOidCacheSize = props.nOidCacheSize; } if( m_properties.nTidCacheSize != props.nTidCacheSize ) { if( 0 == props.nTidCacheSize ) { delete [] m_pTidIn; m_pTidIn = 0; } else { ByteSequence *pNew = new ByteSequence[props.nTidCacheSize]; sal_Int32 i; sal_Int32 iMin = mymin( m_properties.nTidCacheSize , props.nTidCacheSize ); for( i = 0; i < iMin ; i ++ ) { pNew[i] = m_pTidIn[i]; } delete [] m_pTidIn; m_pTidIn = pNew; } OSL_ASSERT( props.nTidCacheSize <= 0xffff ); m_tidCacheOut.resize( (sal_uInt16)props.nTidCacheSize ); m_properties.nTidCacheSize = props.nTidCacheSize; } if( m_properties.sVersion != props.sVersion ) { m_properties.sVersion = props.sVersion; } if( m_properties.nFlushBlockSize != props.nFlushBlockSize ) { m_properties.nFlushBlockSize = props.nFlushBlockSize; } if( m_properties.nOnewayTimeoutMUSEC != props.nOnewayTimeoutMUSEC ) { m_properties.nOnewayTimeoutMUSEC = props.nOnewayTimeoutMUSEC; } if( props.bClearCache ) { if( m_properties.nTypeCacheSize ) { delete [] m_pTypeIn; m_pTypeIn = new Type[m_properties.nTypeCacheSize]; m_typeCacheOut.clear(); } m_lastInType = Type(); m_lastOutType = Type(); if( m_properties.nOidCacheSize ) { delete [] m_pOidIn; m_pOidIn = new OUString[ m_properties.nOidCacheSize]; m_oidCacheOut.clear(); } m_lastOutOid = OUString(); m_lastInOid = OUString(); if( m_properties.nTidCacheSize ) { delete [] m_pTidIn; m_pTidIn = new ByteSequence[m_properties.nTidCacheSize]; m_tidCacheOut.clear(); } m_lastInTid = ByteSequence(); m_lastOutTid = ByteSequence(); } if( m_properties.bNegotiate != props.bNegotiate ) { m_properties.bNegotiate = props.bNegotiate; } if( m_properties.bForceSynchronous != props.bForceSynchronous ) { m_properties.bForceSynchronous = props.bForceSynchronous; } } void urp_BridgeImpl::addError( char *pError ) { OUString message = OUString( RTL_CONSTASCII_USTRINGPARAM( "(tid=" ) ); message += OUString::valueOf( (sal_Int32 ) osl_getThreadIdentifier( 0 ) ); message += OUString::createFromAscii( ") " ); message += OUString::createFromAscii( pError ); MutexGuard guard( m_errorListMutex ); m_lstErrors.push_back( message ); } void urp_BridgeImpl::addError( const OUString & error ) { OUString message = OUString( RTL_CONSTASCII_USTRINGPARAM( "(tid=" ) ); message += OUString::valueOf( (sal_Int32 ) osl_getThreadIdentifier( 0 ) ); message += OUString::createFromAscii( ") " ); message += error; MutexGuard guard( m_errorListMutex ); m_lstErrors.push_back( message ); } void urp_BridgeImpl::dumpErrors( FILE * f) { MutexGuard guard( m_errorListMutex ); for( ::std::list< OUString >::iterator ii = m_lstErrors.begin() ; ii != m_lstErrors.end() ; ++ii ) { OString o = OUStringToOString( *ii , RTL_TEXTENCODING_UTF8 ); fprintf( f, "%s\n" , o.getStr() ); } } OUString urp_BridgeImpl::getErrorsAsString( ) { MutexGuard guard( m_errorListMutex ); OUString ret; for( ::std::list< OUString >::iterator ii = m_lstErrors.begin() ; ii != m_lstErrors.end() ; ++ii ) { ret += *ii; } return ret; } } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * ClockTest.cpp * Unittest for String functions. * Copyright (C) 2005-2010 Simon Newton */ #include <cppunit/extensions/HelperMacros.h> #include <string> #include "ola/Clock.h" class ClockTest: public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ClockTest); CPPUNIT_TEST(testTimeStamp); CPPUNIT_TEST_SUITE_END(); public: void testTimeStamp(); }; CPPUNIT_TEST_SUITE_REGISTRATION(ClockTest); using ola::Clock; using ola::TimeStamp; using ola::TimeInterval; using std::string; /* * Test the TimeStamp class */ void ClockTest::testTimeStamp() { TimeStamp timestamp, timestamp2; CPPUNIT_ASSERT(!timestamp.IsSet()); CPPUNIT_ASSERT(!timestamp2.IsSet()); // test assignment & copy constructor Clock::CurrentTime(timestamp); CPPUNIT_ASSERT(timestamp.IsSet()); timestamp2 = timestamp; CPPUNIT_ASSERT(timestamp2.IsSet()); TimeStamp timestamp3(timestamp); CPPUNIT_ASSERT(timestamp3.IsSet()); CPPUNIT_ASSERT_EQUAL(timestamp, timestamp2); CPPUNIT_ASSERT_EQUAL(timestamp, timestamp3); // test equalities Clock::CurrentTime(timestamp3); CPPUNIT_ASSERT(timestamp3 != timestamp); CPPUNIT_ASSERT(timestamp3 > timestamp); CPPUNIT_ASSERT(timestamp < timestamp3); // test intervals TimeInterval interval = timestamp3 - timestamp; TimeInterval interval2 = interval; TimeInterval interval3(interval); CPPUNIT_ASSERT_EQUAL(interval, interval2); CPPUNIT_ASSERT_EQUAL(interval, interval3); // test subtraction / addition timestamp2 = timestamp + interval; CPPUNIT_ASSERT_EQUAL(timestamp2, timestamp3); timestamp2 -= interval; CPPUNIT_ASSERT_EQUAL(timestamp, timestamp2); // test toString and AsInt TimeInterval one_point_five_seconds(1500); CPPUNIT_ASSERT_EQUAL(string("1.500000"), one_point_five_seconds.ToString()); CPPUNIT_ASSERT_EQUAL(static_cast<int64_t>(1500000), one_point_five_seconds.AsInt()); } <commit_msg>Make the clock tests pass on windows<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * ClockTest.cpp * Unittest for String functions. * Copyright (C) 2005-2010 Simon Newton */ #include <cppunit/extensions/HelperMacros.h> #include <unistd.h> #include <string> #include "ola/Clock.h" class ClockTest: public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ClockTest); CPPUNIT_TEST(testTimeStamp); CPPUNIT_TEST_SUITE_END(); public: void testTimeStamp(); }; CPPUNIT_TEST_SUITE_REGISTRATION(ClockTest); using ola::Clock; using ola::TimeStamp; using ola::TimeInterval; using std::string; /* * Test the TimeStamp class */ void ClockTest::testTimeStamp() { TimeStamp timestamp, timestamp2; CPPUNIT_ASSERT(!timestamp.IsSet()); CPPUNIT_ASSERT(!timestamp2.IsSet()); // test assignment & copy constructor Clock::CurrentTime(timestamp); CPPUNIT_ASSERT(timestamp.IsSet()); timestamp2 = timestamp; CPPUNIT_ASSERT(timestamp2.IsSet()); TimeStamp timestamp3(timestamp); CPPUNIT_ASSERT(timestamp3.IsSet()); CPPUNIT_ASSERT_EQUAL(timestamp, timestamp2); CPPUNIT_ASSERT_EQUAL(timestamp, timestamp3); // test equalities // Windows only seems to have ms resolution, to make the tests pass we need // to sleep here usleep(1000); Clock::CurrentTime(timestamp3); CPPUNIT_ASSERT(timestamp3 != timestamp); CPPUNIT_ASSERT(timestamp3 > timestamp); CPPUNIT_ASSERT(timestamp < timestamp3); // test intervals TimeInterval interval = timestamp3 - timestamp; TimeInterval interval2 = interval; TimeInterval interval3(interval); CPPUNIT_ASSERT_EQUAL(interval, interval2); CPPUNIT_ASSERT_EQUAL(interval, interval3); // test subtraction / addition timestamp2 = timestamp + interval; CPPUNIT_ASSERT_EQUAL(timestamp2, timestamp3); timestamp2 -= interval; CPPUNIT_ASSERT_EQUAL(timestamp, timestamp2); // test toString and AsInt TimeInterval one_point_five_seconds(1500); CPPUNIT_ASSERT_EQUAL(string("1.500000"), one_point_five_seconds.ToString()); CPPUNIT_ASSERT_EQUAL(static_cast<int64_t>(1500000), one_point_five_seconds.AsInt()); } <|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 <com/sun/star/awt/WindowEvent.hpp> #include <comphelper/processfactory.hxx> #include <toolkit/helper/unowrapper.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <toolkit/helper/convert.hxx> #include <toolkit/awt/vclxwindow.hxx> #include <toolkit/awt/vclxwindows.hxx> #include <toolkit/awt/vclxcontainer.hxx> #include <toolkit/awt/vclxtopwindow.hxx> #include <toolkit/awt/vclxgraphics.hxx> #include "toolkit/dllapi.h" #include <vcl/svapp.hxx> #include <vcl/syswin.hxx> #include <vcl/menu.hxx> #include <tools/debug.hxx> using namespace ::com::sun::star; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > CreateXWindow( Window* pWindow ) { switch ( pWindow->GetType() ) { case WINDOW_IMAGEBUTTON: case WINDOW_SPINBUTTON: case WINDOW_MENUBUTTON: case WINDOW_MOREBUTTON: case WINDOW_PUSHBUTTON: case WINDOW_HELPBUTTON: case WINDOW_OKBUTTON: case WINDOW_CANCELBUTTON: return new VCLXButton; case WINDOW_CHECKBOX: return new VCLXCheckBox; // #i95042# // A Window of type <MetricBox> is inherited from type <ComboBox>. // Thus, it does make more sense to return a <VCLXComboBox> instance // instead of only a <VCLXWindow> instance, especially regarding its // corresponding accessibility API. case WINDOW_METRICBOX: case WINDOW_COMBOBOX: return new VCLXComboBox; case WINDOW_SPINFIELD: case WINDOW_NUMERICFIELD: case WINDOW_CURRENCYFIELD: return new VCLXNumericField; case WINDOW_DATEFIELD: return new VCLXDateField; case WINDOW_MULTILINEEDIT: case WINDOW_EDIT: return new VCLXEdit; case WINDOW_METRICFIELD: return new VCLXSpinField; case WINDOW_MESSBOX: case WINDOW_INFOBOX: case WINDOW_WARNINGBOX: case WINDOW_QUERYBOX: case WINDOW_ERRORBOX: return new VCLXMessageBox; case WINDOW_FIXEDIMAGE: return new VCLXImageControl; case WINDOW_FIXEDTEXT: return new VCLXFixedText; case WINDOW_MULTILISTBOX: case WINDOW_LISTBOX: return new VCLXListBox; case WINDOW_LONGCURRENCYFIELD: return new VCLXCurrencyField; case WINDOW_DIALOG: case WINDOW_MODALDIALOG: case WINDOW_TABDIALOG: case WINDOW_BUTTONDIALOG: case WINDOW_MODELESSDIALOG: return new VCLXDialog; case WINDOW_PATTERNFIELD: return new VCLXPatternField; case WINDOW_RADIOBUTTON: return new VCLXRadioButton; case WINDOW_SCROLLBAR: return new VCLXScrollBar; case WINDOW_TIMEFIELD: return new VCLXTimeField; case WINDOW_SYSWINDOW: case WINDOW_WORKWINDOW: case WINDOW_DOCKINGWINDOW: case WINDOW_FLOATINGWINDOW: case WINDOW_HELPTEXTWINDOW: return new VCLXTopWindow; case WINDOW_WINDOW: case WINDOW_TABPAGE: return new VCLXContainer; case WINDOW_TOOLBOX: return new VCLXToolBox; case WINDOW_TABCONTROL: return new VCLXMultiPage; // case WINDOW_FIXEDLINE: // case WINDOW_FIXEDBITMAP: // case WINDOW_DATEBOX: // case WINDOW_GROUPBOX: // case WINDOW_LONGCURRENCYBOX: // case WINDOW_SPLITTER: // case WINDOW_STATUSBAR: // case WINDOW_TABCONTROL: // case WINDOW_NUMERICBOX: // case WINDOW_TRISTATEBOX: // case WINDOW_TIMEBOX: // case WINDOW_SPLITWINDOW: // case WINDOW_SCROLLBARBOX: // case WINDOW_PATTERNBOX: // case WINDOW_CURRENCYBOX: default: return new VCLXWindow( true ); } } // ---------------------------------------------------- // class UnoWrapper // ---------------------------------------------------- extern "C" { TOOLKIT_DLLPUBLIC UnoWrapperBase* CreateUnoWrapper() { return new UnoWrapper( NULL ); } } // extern "C" UnoWrapper::UnoWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit>& rxToolkit ) { mxToolkit = rxToolkit; } void UnoWrapper::Destroy() { delete this; } UnoWrapper::~UnoWrapper() { } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> UnoWrapper::GetVCLToolkit() { if ( !mxToolkit.is() ) mxToolkit = VCLUnoHelper::CreateToolkit(); return mxToolkit.get(); } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> UnoWrapper::GetWindowInterface( Window* pWindow, sal_Bool bCreate ) { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xPeer = pWindow->GetWindowPeer(); if ( !xPeer.is() && bCreate ) { xPeer = CreateXWindow( pWindow ); SetWindowInterface( pWindow, xPeer ); } return xPeer; } void UnoWrapper::SetWindowInterface( Window* pWindow, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xIFace ) { VCLXWindow* pVCLXWindow = VCLXWindow::GetImplementation( xIFace ); DBG_ASSERT( pVCLXWindow, "SetComponentInterface - unsupported type" ); if ( pVCLXWindow ) { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xPeer = pWindow->GetWindowPeer(); if( xPeer.is() ) { bool bSameInstance( pVCLXWindow == dynamic_cast< VCLXWindow* >( xPeer.get() )); DBG_ASSERT( bSameInstance, "UnoWrapper::SetWindowInterface: there already *is* a WindowInterface for this window!" ); if ( bSameInstance ) return; } pVCLXWindow->SetWindow( pWindow ); pWindow->SetWindowPeer( xIFace, pVCLXWindow ); } } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics> UnoWrapper::CreateGraphics( OutputDevice* pOutDev ) { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics> xGrf; VCLXGraphics* pGrf = new VCLXGraphics; xGrf = pGrf; pGrf->Init( pOutDev ); return xGrf; } void UnoWrapper::ReleaseAllGraphics( OutputDevice* pOutDev ) { VCLXGraphicsList_impl* pLst = pOutDev->GetUnoGraphicsList(); if ( pLst ) { for ( size_t n = 0; n < pLst->size(); n++ ) { VCLXGraphics* pGrf = (*pLst)[ n ]; pGrf->SetOutputDevice( NULL ); } } } static sal_Bool lcl_ImplIsParent( Window* pParentWindow, Window* pPossibleChild ) { Window* pWindow = ( pPossibleChild != pParentWindow ) ? pPossibleChild : NULL; while ( pWindow && ( pWindow != pParentWindow ) ) pWindow = pWindow->GetParent(); return pWindow ? sal_True : sal_False; } void UnoWrapper::WindowDestroyed( Window* pWindow ) { // their still might be some children created with ::com::sun::star::loader::Java // that would otherwise not be destroyed until the garbage collector cleans up Window* pChild = pWindow->GetWindow( WINDOW_FIRSTCHILD ); while ( pChild ) { Window* pNextChild = pChild->GetWindow( WINDOW_NEXT ); Window* pClient = pChild->GetWindow( WINDOW_CLIENT ); if ( pClient->GetWindowPeer() ) { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xComp( pClient->GetComponentInterface( sal_False ), ::com::sun::star::uno::UNO_QUERY ); xComp->dispose(); } pChild = pNextChild; } // ::com::sun::star::chaos::System-Windows suchen... Window* pOverlap = pWindow->GetWindow( WINDOW_OVERLAP ); if ( pOverlap ) { pOverlap = pOverlap->GetWindow( WINDOW_FIRSTOVERLAP ); while ( pOverlap ) { Window* pNextOverlap = pOverlap->GetWindow( WINDOW_NEXT ); Window* pClient = pOverlap->GetWindow( WINDOW_CLIENT ); if ( pClient->GetWindowPeer() && lcl_ImplIsParent( pWindow, pClient ) ) { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xComp( pClient->GetComponentInterface( sal_False ), ::com::sun::star::uno::UNO_QUERY ); xComp->dispose(); } pOverlap = pNextOverlap; } } Window* pParent = pWindow->GetParent(); if ( pParent && pParent->GetWindowPeer() ) pParent->GetWindowPeer()->notifyWindowRemoved( *pWindow ); VCLXWindow* pWindowPeer = pWindow->GetWindowPeer(); uno::Reference< lang::XComponent > xWindowPeerComp( pWindow->GetComponentInterface( sal_False ), uno::UNO_QUERY ); OSL_ENSURE( ( pWindowPeer != NULL ) == xWindowPeerComp.is(), "UnoWrapper::WindowDestroyed: inconsistency in the window's peers!" ); if ( pWindowPeer ) { pWindowPeer->SetWindow( NULL ); pWindow->SetWindowPeer( NULL, NULL ); } if ( xWindowPeerComp.is() ) xWindowPeerComp->dispose(); // #102132# Iterate over frames after setting Window peer to NULL, // because while destroying other frames, we get get into the method again and try // to destroy this window again... // #i42462#/#116855# no, don't loop: Instead, just ensure that all our top-window-children // are disposed, too (which should also be a valid fix for #102132#, but doesn't have the extreme // performance penalties) if ( pWindow ) { Window* pTopWindowChild = pWindow->GetWindow( WINDOW_FIRSTTOPWINDOWCHILD ); while ( pTopWindowChild ) { OSL_ENSURE( pTopWindowChild->GetParent() == pWindow, "UnoWrapper::WindowDestroyed: inconsistency in the SystemWindow relationship!" ); Window* pNextTopChild = pTopWindowChild->GetWindow( WINDOW_NEXTTOPWINDOWSIBLING ); //the window still could be on the stack, so we have to // use lazy delete ( it will automatically // disconnect from the currently destroyed parent window ) pTopWindowChild->doLazyDelete(); pTopWindowChild = pNextTopChild; } } } // ---------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > UnoWrapper::CreateAccessible( Menu* pMenu, sal_Bool bIsMenuBar ) { return maAccessibleFactoryAccess.getFactory().createAccessible( pMenu, bIsMenuBar ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#705963 Dereference before null check<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 <com/sun/star/awt/WindowEvent.hpp> #include <comphelper/processfactory.hxx> #include <toolkit/helper/unowrapper.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <toolkit/helper/convert.hxx> #include <toolkit/awt/vclxwindow.hxx> #include <toolkit/awt/vclxwindows.hxx> #include <toolkit/awt/vclxcontainer.hxx> #include <toolkit/awt/vclxtopwindow.hxx> #include <toolkit/awt/vclxgraphics.hxx> #include "toolkit/dllapi.h" #include <vcl/svapp.hxx> #include <vcl/syswin.hxx> #include <vcl/menu.hxx> #include <tools/debug.hxx> using namespace ::com::sun::star; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > CreateXWindow( Window* pWindow ) { switch ( pWindow->GetType() ) { case WINDOW_IMAGEBUTTON: case WINDOW_SPINBUTTON: case WINDOW_MENUBUTTON: case WINDOW_MOREBUTTON: case WINDOW_PUSHBUTTON: case WINDOW_HELPBUTTON: case WINDOW_OKBUTTON: case WINDOW_CANCELBUTTON: return new VCLXButton; case WINDOW_CHECKBOX: return new VCLXCheckBox; // #i95042# // A Window of type <MetricBox> is inherited from type <ComboBox>. // Thus, it does make more sense to return a <VCLXComboBox> instance // instead of only a <VCLXWindow> instance, especially regarding its // corresponding accessibility API. case WINDOW_METRICBOX: case WINDOW_COMBOBOX: return new VCLXComboBox; case WINDOW_SPINFIELD: case WINDOW_NUMERICFIELD: case WINDOW_CURRENCYFIELD: return new VCLXNumericField; case WINDOW_DATEFIELD: return new VCLXDateField; case WINDOW_MULTILINEEDIT: case WINDOW_EDIT: return new VCLXEdit; case WINDOW_METRICFIELD: return new VCLXSpinField; case WINDOW_MESSBOX: case WINDOW_INFOBOX: case WINDOW_WARNINGBOX: case WINDOW_QUERYBOX: case WINDOW_ERRORBOX: return new VCLXMessageBox; case WINDOW_FIXEDIMAGE: return new VCLXImageControl; case WINDOW_FIXEDTEXT: return new VCLXFixedText; case WINDOW_MULTILISTBOX: case WINDOW_LISTBOX: return new VCLXListBox; case WINDOW_LONGCURRENCYFIELD: return new VCLXCurrencyField; case WINDOW_DIALOG: case WINDOW_MODALDIALOG: case WINDOW_TABDIALOG: case WINDOW_BUTTONDIALOG: case WINDOW_MODELESSDIALOG: return new VCLXDialog; case WINDOW_PATTERNFIELD: return new VCLXPatternField; case WINDOW_RADIOBUTTON: return new VCLXRadioButton; case WINDOW_SCROLLBAR: return new VCLXScrollBar; case WINDOW_TIMEFIELD: return new VCLXTimeField; case WINDOW_SYSWINDOW: case WINDOW_WORKWINDOW: case WINDOW_DOCKINGWINDOW: case WINDOW_FLOATINGWINDOW: case WINDOW_HELPTEXTWINDOW: return new VCLXTopWindow; case WINDOW_WINDOW: case WINDOW_TABPAGE: return new VCLXContainer; case WINDOW_TOOLBOX: return new VCLXToolBox; case WINDOW_TABCONTROL: return new VCLXMultiPage; // case WINDOW_FIXEDLINE: // case WINDOW_FIXEDBITMAP: // case WINDOW_DATEBOX: // case WINDOW_GROUPBOX: // case WINDOW_LONGCURRENCYBOX: // case WINDOW_SPLITTER: // case WINDOW_STATUSBAR: // case WINDOW_TABCONTROL: // case WINDOW_NUMERICBOX: // case WINDOW_TRISTATEBOX: // case WINDOW_TIMEBOX: // case WINDOW_SPLITWINDOW: // case WINDOW_SCROLLBARBOX: // case WINDOW_PATTERNBOX: // case WINDOW_CURRENCYBOX: default: return new VCLXWindow( true ); } } // ---------------------------------------------------- // class UnoWrapper // ---------------------------------------------------- extern "C" { TOOLKIT_DLLPUBLIC UnoWrapperBase* CreateUnoWrapper() { return new UnoWrapper( NULL ); } } // extern "C" UnoWrapper::UnoWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit>& rxToolkit ) { mxToolkit = rxToolkit; } void UnoWrapper::Destroy() { delete this; } UnoWrapper::~UnoWrapper() { } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> UnoWrapper::GetVCLToolkit() { if ( !mxToolkit.is() ) mxToolkit = VCLUnoHelper::CreateToolkit(); return mxToolkit.get(); } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> UnoWrapper::GetWindowInterface( Window* pWindow, sal_Bool bCreate ) { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xPeer = pWindow->GetWindowPeer(); if ( !xPeer.is() && bCreate ) { xPeer = CreateXWindow( pWindow ); SetWindowInterface( pWindow, xPeer ); } return xPeer; } void UnoWrapper::SetWindowInterface( Window* pWindow, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xIFace ) { VCLXWindow* pVCLXWindow = VCLXWindow::GetImplementation( xIFace ); DBG_ASSERT( pVCLXWindow, "SetComponentInterface - unsupported type" ); if ( pVCLXWindow ) { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xPeer = pWindow->GetWindowPeer(); if( xPeer.is() ) { bool bSameInstance( pVCLXWindow == dynamic_cast< VCLXWindow* >( xPeer.get() )); DBG_ASSERT( bSameInstance, "UnoWrapper::SetWindowInterface: there already *is* a WindowInterface for this window!" ); if ( bSameInstance ) return; } pVCLXWindow->SetWindow( pWindow ); pWindow->SetWindowPeer( xIFace, pVCLXWindow ); } } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics> UnoWrapper::CreateGraphics( OutputDevice* pOutDev ) { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics> xGrf; VCLXGraphics* pGrf = new VCLXGraphics; xGrf = pGrf; pGrf->Init( pOutDev ); return xGrf; } void UnoWrapper::ReleaseAllGraphics( OutputDevice* pOutDev ) { VCLXGraphicsList_impl* pLst = pOutDev->GetUnoGraphicsList(); if ( pLst ) { for ( size_t n = 0; n < pLst->size(); n++ ) { VCLXGraphics* pGrf = (*pLst)[ n ]; pGrf->SetOutputDevice( NULL ); } } } static sal_Bool lcl_ImplIsParent( Window* pParentWindow, Window* pPossibleChild ) { Window* pWindow = ( pPossibleChild != pParentWindow ) ? pPossibleChild : NULL; while ( pWindow && ( pWindow != pParentWindow ) ) pWindow = pWindow->GetParent(); return pWindow ? sal_True : sal_False; } void UnoWrapper::WindowDestroyed( Window* pWindow ) { // their still might be some children created with ::com::sun::star::loader::Java // that would otherwise not be destroyed until the garbage collector cleans up Window* pChild = pWindow->GetWindow( WINDOW_FIRSTCHILD ); while ( pChild ) { Window* pNextChild = pChild->GetWindow( WINDOW_NEXT ); Window* pClient = pChild->GetWindow( WINDOW_CLIENT ); if ( pClient->GetWindowPeer() ) { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xComp( pClient->GetComponentInterface( sal_False ), ::com::sun::star::uno::UNO_QUERY ); xComp->dispose(); } pChild = pNextChild; } // ::com::sun::star::chaos::System-Windows suchen... Window* pOverlap = pWindow->GetWindow( WINDOW_OVERLAP ); if ( pOverlap ) { pOverlap = pOverlap->GetWindow( WINDOW_FIRSTOVERLAP ); while ( pOverlap ) { Window* pNextOverlap = pOverlap->GetWindow( WINDOW_NEXT ); Window* pClient = pOverlap->GetWindow( WINDOW_CLIENT ); if ( pClient->GetWindowPeer() && lcl_ImplIsParent( pWindow, pClient ) ) { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xComp( pClient->GetComponentInterface( sal_False ), ::com::sun::star::uno::UNO_QUERY ); xComp->dispose(); } pOverlap = pNextOverlap; } } Window* pParent = pWindow->GetParent(); if ( pParent && pParent->GetWindowPeer() ) pParent->GetWindowPeer()->notifyWindowRemoved( *pWindow ); VCLXWindow* pWindowPeer = pWindow->GetWindowPeer(); uno::Reference< lang::XComponent > xWindowPeerComp( pWindow->GetComponentInterface( sal_False ), uno::UNO_QUERY ); OSL_ENSURE( ( pWindowPeer != NULL ) == xWindowPeerComp.is(), "UnoWrapper::WindowDestroyed: inconsistency in the window's peers!" ); if ( pWindowPeer ) { pWindowPeer->SetWindow( NULL ); pWindow->SetWindowPeer( NULL, NULL ); } if ( xWindowPeerComp.is() ) xWindowPeerComp->dispose(); // #102132# Iterate over frames after setting Window peer to NULL, // because while destroying other frames, we get get into the method again and try // to destroy this window again... // #i42462#/#116855# no, don't loop: Instead, just ensure that all our top-window-children // are disposed, too (which should also be a valid fix for #102132#, but doesn't have the extreme // performance penalties) Window* pTopWindowChild = pWindow->GetWindow( WINDOW_FIRSTTOPWINDOWCHILD ); while ( pTopWindowChild ) { OSL_ENSURE( pTopWindowChild->GetParent() == pWindow, "UnoWrapper::WindowDestroyed: inconsistency in the SystemWindow relationship!" ); Window* pNextTopChild = pTopWindowChild->GetWindow( WINDOW_NEXTTOPWINDOWSIBLING ); //the window still could be on the stack, so we have to // use lazy delete ( it will automatically // disconnect from the currently destroyed parent window ) pTopWindowChild->doLazyDelete(); pTopWindowChild = pNextTopChild; } } // ---------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > UnoWrapper::CreateAccessible( Menu* pMenu, sal_Bool bIsMenuBar ) { return maAccessibleFactoryAccess.getFactory().createAccessible( pMenu, bIsMenuBar ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "../HierarchicalEA.hpp" #include "../PopulationNodeFactory.hpp" #include "../../exception/MismatchedCountsException.hpp" #pragma once template<typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<Locus*>> contextLoci, std::vector<ToStringFunction*> toStrings, std::vector<std::vector<EndCondition*>> conditions, std::vector<std::vector<std::string>> names, std::vector<bool> print, std::vector<bool> end, params... as ) { this->addConstructiveLattice<NodeType>( formula, contextLoci, std::vector<std::vector<ObjectiveFunction*>>( names.size(), std::vector<ObjectiveFunction*>() ), toStrings, conditions, names, print, end, as... ); } template<typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<Locus*>> contextLoci, ObjectiveFunction * globalObjective, std::vector<ToStringFunction*> toStrings, std::vector<std::vector<EndCondition*>> conditions, std::vector<std::vector<std::string>> names, std::vector<bool> print, std::vector<bool> end, params... as ) { this->addConstructiveLattice<NodeType>( formula, contextLoci, std::vector<std::vector<ObjectiveFunction*>>( names.size(), std::vector<ObjectiveFunction*>(1, globalObjective) ), toStrings, conditions, names, print, end, as... ); } template<typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<Locus*>> contextLoci, std::vector<std::vector<ObjectiveFunction*>> objectives, std::vector<ToStringFunction*> toStrings, std::vector<std::vector<EndCondition*>> conditions, std::vector<std::vector<std::string>> names, std::vector<bool> print, std::vector<bool> end, params... as ) { std::vector<unsigned int> counts; for (unsigned int i = 0; i < names.size(); i++) counts.push_back(names[i].size()); this->addConstructiveLattice<NodeType>( formula, this->wrapForPass(contextLoci, counts), this->wrapForPass(objectives, counts), this->wrapForPass(toStrings, counts), this->wrapForPass(conditions, counts), names, this->wrapForPass(print, counts), this->wrapForPass(end, counts), as... ); } template <typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<std::vector<Locus*>>> contextLoci, std::vector<std::vector<std::vector<ObjectiveFunction*>>> objectives, std::vector<std::vector<ToStringFunction*>> toStrings, std::vector<std::vector<std::vector<EndCondition*>>> conditions, std::vector<std::vector<std::string>> names, std::vector<std::vector<bool>> print, std::vector<std::vector<bool>> end, params... as ) { if (!this->compareVectorLengths( contextLoci, objectives, toStrings, conditions, names, print, end )) throw MismatchedCountsException(); // TODO TODO: Refactor this std::vector<Locus*> levelLoci; std::vector<PopulationNode*> levelNodes; for (unsigned int i = names.size() - 1; i >= 0; i++) { if (!this->compareVectorLengths( contextLoci[i], objectives[i], toStrings[i], conditions[i], names[i], print[i], end[i] )) throw MismatchedCountsException(); levelNodes.clear(); std::vector<Locus*> nodeLoci; for (unsigned int k = 0; k < names[i].size(); k++) { nodeLoci.clear(); nodeLoci.insert( nodeLoci.end(), levelLoci.begin(), levelLoci.end() ); nodeLoci.insert( nodeLoci.end(), contextLoci[i][k].begin(), contextLoci[i][k].end() ); levelNodes.push_back( PopulationNodeFactory::createNode<NodeType>( formula->getPopulationSize( nodeLoci.size() ), nodeLoci, objectives[i][k], toStrings[i][k], conditions[i][k], names[i][k], 1, as... ) ); levelLoci.push_back( new PopulationLocus(levelNodes[k]) ); } this->addNodes(levelNodes, print[i], end[i]); levelNodes.clear(); } // Cleanup - this prevents the nodes at the top of the lattice from // having dangling loci pointing to them that won't get dealloc'd later for (unsigned int i = 0; i < levelLoci.size(); i++) delete(levelLoci[i]); } <commit_msg>[HierEA Lattice Factory]: Fixed counter bug<commit_after>#include "../HierarchicalEA.hpp" #include "../PopulationNodeFactory.hpp" #include "../../exception/MismatchedCountsException.hpp" #pragma once template<typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<Locus*>> contextLoci, std::vector<ToStringFunction*> toStrings, std::vector<std::vector<EndCondition*>> conditions, std::vector<std::vector<std::string>> names, std::vector<bool> print, std::vector<bool> end, params... as ) { this->addConstructiveLattice<NodeType>( formula, contextLoci, std::vector<std::vector<ObjectiveFunction*>>( names.size(), std::vector<ObjectiveFunction*>() ), toStrings, conditions, names, print, end, as... ); } template<typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<Locus*>> contextLoci, ObjectiveFunction * globalObjective, std::vector<ToStringFunction*> toStrings, std::vector<std::vector<EndCondition*>> conditions, std::vector<std::vector<std::string>> names, std::vector<bool> print, std::vector<bool> end, params... as ) { this->addConstructiveLattice<NodeType>( formula, contextLoci, std::vector<std::vector<ObjectiveFunction*>>( names.size(), std::vector<ObjectiveFunction*>(1, globalObjective) ), toStrings, conditions, names, print, end, as... ); } template<typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<Locus*>> contextLoci, std::vector<std::vector<ObjectiveFunction*>> objectives, std::vector<ToStringFunction*> toStrings, std::vector<std::vector<EndCondition*>> conditions, std::vector<std::vector<std::string>> names, std::vector<bool> print, std::vector<bool> end, params... as ) { std::vector<unsigned int> counts; for (unsigned int i = 0; i < names.size(); i++) counts.push_back(names[i].size()); this->addConstructiveLattice<NodeType>( formula, this->wrapForPass(contextLoci, counts), this->wrapForPass(objectives, counts), this->wrapForPass(toStrings, counts), this->wrapForPass(conditions, counts), names, this->wrapForPass(print, counts), this->wrapForPass(end, counts), as... ); } template <typename NodeType, typename... params> void HierarchicalEA::addConstructiveLattice( PopulationFormula * formula, std::vector<std::vector<std::vector<Locus*>>> contextLoci, std::vector<std::vector<std::vector<ObjectiveFunction*>>> objectives, std::vector<std::vector<ToStringFunction*>> toStrings, std::vector<std::vector<std::vector<EndCondition*>>> conditions, std::vector<std::vector<std::string>> names, std::vector<std::vector<bool>> print, std::vector<std::vector<bool>> end, params... as ) { if (!this->compareVectorLengths( contextLoci, objectives, toStrings, conditions, names, print, end )) throw MismatchedCountsException(); // TODO TODO: Refactor this std::vector<Locus*> levelLoci; std::vector<PopulationNode*> levelNodes; for ( unsigned int i = names.size() - 1; i >= 0 && i < names.size(); // Counteracts unsigned overflow i-- ) { if (!this->compareVectorLengths( contextLoci[i], objectives[i], toStrings[i], conditions[i], names[i], print[i], end[i] )) throw MismatchedCountsException(); levelNodes.clear(); std::vector<Locus*> nodeLoci; for (unsigned int k = 0; k < names[i].size(); k++) { nodeLoci.clear(); nodeLoci.insert( nodeLoci.end(), levelLoci.begin(), levelLoci.end() ); nodeLoci.insert( nodeLoci.end(), contextLoci[i][k].begin(), contextLoci[i][k].end() ); levelNodes.push_back( PopulationNodeFactory::createNode<NodeType>( formula->getPopulationSize( nodeLoci.size() ), nodeLoci, objectives[i][k], toStrings[i][k], conditions[i][k], names[i][k], 1, as... ) ); levelLoci.push_back( new PopulationLocus(levelNodes[k]) ); } this->addNodes(levelNodes, print[i], end[i]); levelNodes.clear(); } // Cleanup - this prevents the nodes at the top of the lattice from // having dangling loci pointing to them that won't get dealloc'd later for (unsigned int i = 0; i < levelLoci.size(); i++) delete(levelLoci[i]); } <|endoftext|>
<commit_before>// [WriteFile Name=OpenExistingMap, Category=Maps] // [Legal] // Copyright 2016 Esri. // 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. // [Legal] #include "OpenExistingMap.h" #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "PortalItem.h" using namespace Esri::ArcGISRuntime; OpenExistingMap::OpenExistingMap(QQuickItem* parent) : QQuickItem(parent), m_mapView(nullptr) { } OpenExistingMap::~OpenExistingMap() { } void OpenExistingMap::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); // create a new basemap instance Basemap* basemap = Basemap::imagery(this); // create a new map instance Map* map = new Map(basemap, this); // set map on the map view m_mapView->setMap(map); } void OpenExistingMap::openMap(QString itemId) { // create a portal item with the item id PortalItem portalItem; portalItem.setUrl(QUrl("http://arcgis.com/sharing/rest/content/items/" + itemId)); // create a new map from the portal item Map* map = new Map(portalItem, this); // set the map to the map view m_mapView->setMap(map); } <commit_msg>fix portalItem<commit_after>// [WriteFile Name=OpenExistingMap, Category=Maps] // [Legal] // Copyright 2016 Esri. // 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. // [Legal] #include "OpenExistingMap.h" #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "PortalItem.h" using namespace Esri::ArcGISRuntime; OpenExistingMap::OpenExistingMap(QQuickItem* parent) : QQuickItem(parent), m_mapView(nullptr) { } OpenExistingMap::~OpenExistingMap() { } void OpenExistingMap::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); // create a new basemap instance Basemap* basemap = Basemap::imagery(this); // create a new map instance Map* map = new Map(basemap, this); // set map on the map view m_mapView->setMap(map); } void OpenExistingMap::openMap(QString itemId) { // create a portal item with the item id auto portalItem = new PortalItem(QUrl("http://arcgis.com/sharing/rest/content/items/" + itemId)); // create a new map from the portal item Map* map = new Map(portalItem, this); // set the map to the map view m_mapView->setMap(map); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2009 Manjeet Dahiya * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppStanza.h" #include "QXmppUtils.h" #include "QXmppConstants.h" #include <QDomElement> #include <QXmlStreamWriter> uint QXmppStanza::s_uniqeIdNo = 0; QXmppStanza::Error::Error(): m_code(0), m_type(static_cast<QXmppStanza::Error::Type>(-1)), m_condition(static_cast<QXmppStanza::Error::Condition>(-1)), m_text("") { } QXmppStanza::Error::Error(Type type, Condition cond, const QString& text): m_code(0), m_type(type), m_condition(cond), m_text(text) { } QXmppStanza::Error::Error(const QString& type, const QString& cond, const QString& text): m_code(0), m_text(text) { setTypeFromStr(type); setConditionFromStr(cond); } void QXmppStanza::Error::setText(const QString& text) { m_text = text; } void QXmppStanza::Error::setCode(int code) { m_code = code; } void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond) { m_condition = cond; } void QXmppStanza::Error::setType(QXmppStanza::Error::Type type) { m_type = type; } QString QXmppStanza::Error::getText() const { return m_text; } int QXmppStanza::Error::getCode() const { return m_code; } QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const { return m_condition; } QXmppStanza::Error::Type QXmppStanza::Error::getType() const { return m_type; } QString QXmppStanza::Error::getTypeStr() const { switch(m_type) { case Cancel: return "cancel"; case Continue: return "continue"; case Modify: return "modify"; case Auth: return "auth"; case Wait: return "wait"; default: return ""; } } QString QXmppStanza::Error::getConditionStr() const { switch(m_condition) { case BadRequest: return "bad-request"; case Conflict: return "conflict"; case FeatureNotImplemented: return "feature-not-implemented"; case Forbidden: return "forbidden"; case Gone: return "gone"; case InternalServerError: return "internal-server-error"; case ItemNotFound: return "item-not-found"; case JidMalformed: return "jid-malformed"; case NotAcceptable: return "not-acceptable"; case NotAllowed: return "not-allowed"; case NotAuthorized: return "not-authorized"; case PaymentRequired: return "payment-required"; case RecipientUnavailable: return "recipient-unavailable"; case Redirect: return "redirect"; case RegistrationRequired: return "registration-required"; case RemoteServerNotFound: return "remote-server-not-found"; case RemoteServerTimeout: return "remote-server-timeout"; case ResourceConstraint: return "resource-constraint"; case ServiceUnavailable: return "service-unavailable"; case SubscriptionRequired: return "subscription-required"; case UndefinedCondition: return "undefined-condition"; case UnexpectedRequest: return "unexpected-request"; default: return ""; } } void QXmppStanza::Error::setTypeFromStr(const QString& type) { if(type == "cancel") setType(Cancel); else if(type == "continue") setType(Continue); else if(type == "modify") setType(Modify); else if(type == "auth") setType(Auth); else if(type == "wait") setType(Wait); else setType(static_cast<QXmppStanza::Error::Type>(-1)); } void QXmppStanza::Error::setConditionFromStr(const QString& type) { if(type == "bad-request") setCondition(BadRequest); else if(type == "conflict") setCondition(Conflict); else if(type == "feature-not-implemented") setCondition(FeatureNotImplemented); else if(type == "forbidden") setCondition(Forbidden); else if(type == "gone") setCondition(Gone); else if(type == "internal-server-error") setCondition(InternalServerError); else if(type == "item-not-found") setCondition(ItemNotFound); else if(type == "jid-malformed") setCondition(JidMalformed); else if(type == "not-acceptable") setCondition(NotAcceptable); else if(type == "not-allowed") setCondition(NotAllowed); else if(type == "not-authorized") setCondition(NotAuthorized); else if(type == "payment-required") setCondition(PaymentRequired); else if(type == "recipient-unavailable") setCondition(RecipientUnavailable); else if(type == "redirect") setCondition(Redirect); else if(type == "registration-required") setCondition(RegistrationRequired); else if(type == "remote-server-not-found") setCondition(RemoteServerNotFound); else if(type == "remote-server-timeout") setCondition(RemoteServerTimeout); else if(type == "resource-constraint") setCondition(ResourceConstraint); else if(type == "service-unavailable") setCondition(ServiceUnavailable); else if(type == "subscription-required") setCondition(SubscriptionRequired); else if(type == "undefined-condition") setCondition(UndefinedCondition); else if(type == "unexpected-request") setCondition(UnexpectedRequest); else setCondition(static_cast<QXmppStanza::Error::Condition>(-1)); } bool QXmppStanza::Error::isValid() { return !(getTypeStr().isEmpty() && getConditionStr().isEmpty()); } void QXmppStanza::Error::parse(const QDomElement &errorElement) { setCode(errorElement.attribute("code").toInt()); setTypeFromStr(errorElement.attribute("type")); QString text; QString cond; QDomElement element = errorElement.firstChildElement(); while(!element.isNull()) { if(element.tagName() == "text") text = element.text(); else if(element.namespaceURI() == ns_stanza) { cond = element.tagName(); } element = element.nextSiblingElement(); } setConditionFromStr(cond); setText(text); } void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const { QString cond = getConditionStr(); QString type = getTypeStr(); if(cond.isEmpty() && type.isEmpty()) return; writer->writeStartElement("error"); helperToXmlAddAttribute(writer, "type", type); if (m_code > 0) helperToXmlAddAttribute(writer, "code", QString::number(m_code)); if(!cond.isEmpty()) { writer->writeStartElement(cond); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeEndElement(); } if(!m_text.isEmpty()) { writer->writeStartElement("text"); helperToXmlAddAttribute(writer,"xml:lang", "en"); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeCharacters(m_text); writer->writeEndElement(); } writer->writeEndElement(); } QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(), m_to(to), m_from(from) { } QXmppStanza::~QXmppStanza() { } QString QXmppStanza::to() const { return m_to; } void QXmppStanza::setTo(const QString& to) { m_to = to; } QString QXmppStanza::from() const { return m_from; } void QXmppStanza::setFrom(const QString& from) { m_from = from; } QString QXmppStanza::id() const { return m_id; } void QXmppStanza::setId(const QString& id) { m_id = id; } QString QXmppStanza::lang() const { return m_lang; } void QXmppStanza::setLang(const QString& lang) { m_lang = lang; } QXmppStanza::Error QXmppStanza::error() const { return m_error; } void QXmppStanza::setError(QXmppStanza::Error& error) { m_error = error; } QXmppElementList QXmppStanza::extensions() const { return m_extensions; } void QXmppStanza::setExtensions(const QXmppElementList &extensions) { m_extensions = extensions; } void QXmppStanza::generateAndSetNextId() { // get back ++s_uniqeIdNo; m_id = "qxmpp" + QString::number(s_uniqeIdNo); } bool QXmppStanza::isErrorStanza() { return m_error.isValid(); } void QXmppStanza::parse(const QDomElement &element) { m_from = element.attribute("from"); m_to = element.attribute("to"); m_id = element.attribute("id"); m_lang = element.attribute("lang"); QDomElement errorElement = element.firstChildElement("error"); if(!errorElement.isNull()) m_error.parse(errorElement); } // deprecated QString QXmppStanza::getTo() const { return m_to; } QString QXmppStanza::getFrom() const { return m_from; } QString QXmppStanza::getId() const { return m_id; } QString QXmppStanza::getLang() const { return m_lang; } QXmppStanza::Error QXmppStanza::getError() const { return m_error; } <commit_msg>cleanup QXmppStanza::Error API<commit_after>/* * Copyright (C) 2008-2009 Manjeet Dahiya * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppStanza.h" #include "QXmppUtils.h" #include "QXmppConstants.h" #include <QDomElement> #include <QXmlStreamWriter> uint QXmppStanza::s_uniqeIdNo = 0; QXmppStanza::Error::Error(): m_code(0), m_type(static_cast<QXmppStanza::Error::Type>(-1)), m_condition(static_cast<QXmppStanza::Error::Condition>(-1)), m_text("") { } QXmppStanza::Error::Error(Type type, Condition cond, const QString& text): m_code(0), m_type(type), m_condition(cond), m_text(text) { } QXmppStanza::Error::Error(const QString& type, const QString& cond, const QString& text): m_code(0), m_text(text) { setTypeFromStr(type); setConditionFromStr(cond); } QString QXmppStanza::Error::text() const { return m_text; } void QXmppStanza::Error::setText(const QString& text) { m_text = text; } int QXmppStanza::Error::code() const { return m_code; } void QXmppStanza::Error::setCode(int code) { m_code = code; } QXmppStanza::Error::Condition QXmppStanza::Error::condition() const { return m_condition; } void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond) { m_condition = cond; } QXmppStanza::Error::Type QXmppStanza::Error::type() const { return m_type; } void QXmppStanza::Error::setType(QXmppStanza::Error::Type type) { m_type = type; } QString QXmppStanza::Error::getTypeStr() const { switch(m_type) { case Cancel: return "cancel"; case Continue: return "continue"; case Modify: return "modify"; case Auth: return "auth"; case Wait: return "wait"; default: return ""; } } QString QXmppStanza::Error::getConditionStr() const { switch(m_condition) { case BadRequest: return "bad-request"; case Conflict: return "conflict"; case FeatureNotImplemented: return "feature-not-implemented"; case Forbidden: return "forbidden"; case Gone: return "gone"; case InternalServerError: return "internal-server-error"; case ItemNotFound: return "item-not-found"; case JidMalformed: return "jid-malformed"; case NotAcceptable: return "not-acceptable"; case NotAllowed: return "not-allowed"; case NotAuthorized: return "not-authorized"; case PaymentRequired: return "payment-required"; case RecipientUnavailable: return "recipient-unavailable"; case Redirect: return "redirect"; case RegistrationRequired: return "registration-required"; case RemoteServerNotFound: return "remote-server-not-found"; case RemoteServerTimeout: return "remote-server-timeout"; case ResourceConstraint: return "resource-constraint"; case ServiceUnavailable: return "service-unavailable"; case SubscriptionRequired: return "subscription-required"; case UndefinedCondition: return "undefined-condition"; case UnexpectedRequest: return "unexpected-request"; default: return ""; } } void QXmppStanza::Error::setTypeFromStr(const QString& type) { if(type == "cancel") setType(Cancel); else if(type == "continue") setType(Continue); else if(type == "modify") setType(Modify); else if(type == "auth") setType(Auth); else if(type == "wait") setType(Wait); else setType(static_cast<QXmppStanza::Error::Type>(-1)); } void QXmppStanza::Error::setConditionFromStr(const QString& type) { if(type == "bad-request") setCondition(BadRequest); else if(type == "conflict") setCondition(Conflict); else if(type == "feature-not-implemented") setCondition(FeatureNotImplemented); else if(type == "forbidden") setCondition(Forbidden); else if(type == "gone") setCondition(Gone); else if(type == "internal-server-error") setCondition(InternalServerError); else if(type == "item-not-found") setCondition(ItemNotFound); else if(type == "jid-malformed") setCondition(JidMalformed); else if(type == "not-acceptable") setCondition(NotAcceptable); else if(type == "not-allowed") setCondition(NotAllowed); else if(type == "not-authorized") setCondition(NotAuthorized); else if(type == "payment-required") setCondition(PaymentRequired); else if(type == "recipient-unavailable") setCondition(RecipientUnavailable); else if(type == "redirect") setCondition(Redirect); else if(type == "registration-required") setCondition(RegistrationRequired); else if(type == "remote-server-not-found") setCondition(RemoteServerNotFound); else if(type == "remote-server-timeout") setCondition(RemoteServerTimeout); else if(type == "resource-constraint") setCondition(ResourceConstraint); else if(type == "service-unavailable") setCondition(ServiceUnavailable); else if(type == "subscription-required") setCondition(SubscriptionRequired); else if(type == "undefined-condition") setCondition(UndefinedCondition); else if(type == "unexpected-request") setCondition(UnexpectedRequest); else setCondition(static_cast<QXmppStanza::Error::Condition>(-1)); } bool QXmppStanza::Error::isValid() { return !(getTypeStr().isEmpty() && getConditionStr().isEmpty()); } void QXmppStanza::Error::parse(const QDomElement &errorElement) { setCode(errorElement.attribute("code").toInt()); setTypeFromStr(errorElement.attribute("type")); QString text; QString cond; QDomElement element = errorElement.firstChildElement(); while(!element.isNull()) { if(element.tagName() == "text") text = element.text(); else if(element.namespaceURI() == ns_stanza) { cond = element.tagName(); } element = element.nextSiblingElement(); } setConditionFromStr(cond); setText(text); } void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const { QString cond = getConditionStr(); QString type = getTypeStr(); if(cond.isEmpty() && type.isEmpty()) return; writer->writeStartElement("error"); helperToXmlAddAttribute(writer, "type", type); if (m_code > 0) helperToXmlAddAttribute(writer, "code", QString::number(m_code)); if(!cond.isEmpty()) { writer->writeStartElement(cond); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeEndElement(); } if(!m_text.isEmpty()) { writer->writeStartElement("text"); helperToXmlAddAttribute(writer,"xml:lang", "en"); helperToXmlAddAttribute(writer,"xmlns", ns_stanza); writer->writeCharacters(m_text); writer->writeEndElement(); } writer->writeEndElement(); } QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(), m_to(to), m_from(from) { } QXmppStanza::~QXmppStanza() { } QString QXmppStanza::to() const { return m_to; } void QXmppStanza::setTo(const QString& to) { m_to = to; } QString QXmppStanza::from() const { return m_from; } void QXmppStanza::setFrom(const QString& from) { m_from = from; } QString QXmppStanza::id() const { return m_id; } void QXmppStanza::setId(const QString& id) { m_id = id; } QString QXmppStanza::lang() const { return m_lang; } void QXmppStanza::setLang(const QString& lang) { m_lang = lang; } QXmppStanza::Error QXmppStanza::error() const { return m_error; } void QXmppStanza::setError(QXmppStanza::Error& error) { m_error = error; } QXmppElementList QXmppStanza::extensions() const { return m_extensions; } void QXmppStanza::setExtensions(const QXmppElementList &extensions) { m_extensions = extensions; } void QXmppStanza::generateAndSetNextId() { // get back ++s_uniqeIdNo; m_id = "qxmpp" + QString::number(s_uniqeIdNo); } bool QXmppStanza::isErrorStanza() { return m_error.isValid(); } void QXmppStanza::parse(const QDomElement &element) { m_from = element.attribute("from"); m_to = element.attribute("to"); m_id = element.attribute("id"); m_lang = element.attribute("lang"); QDomElement errorElement = element.firstChildElement("error"); if(!errorElement.isNull()) m_error.parse(errorElement); } // deprecated QString QXmppStanza::Error::getText() const { return m_text; } int QXmppStanza::Error::getCode() const { return m_code; } QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const { return m_condition; } QXmppStanza::Error::Type QXmppStanza::Error::getType() const { return m_type; } QString QXmppStanza::getTo() const { return m_to; } QString QXmppStanza::getFrom() const { return m_from; } QString QXmppStanza::getId() const { return m_id; } QString QXmppStanza::getLang() const { return m_lang; } QXmppStanza::Error QXmppStanza::getError() const { return m_error; } <|endoftext|>
<commit_before>// Copyright 2006-2009 the V8 project authors. All rights reserved. // // Tests of profiler-related functions from log.h #ifdef ENABLE_LOGGING_AND_PROFILING #include <stdlib.h> #include "v8.h" #include "codegen.h" #include "log.h" #include "top.h" #include "cctest.h" #include "disassembler.h" #include "register-allocator-inl.h" using v8::Function; using v8::Local; using v8::Object; using v8::Script; using v8::String; using v8::Value; using v8::internal::byte; using v8::internal::Address; using v8::internal::Handle; using v8::internal::JSFunction; using v8::internal::StackTracer; using v8::internal::TickSample; using v8::internal::Top; namespace i = v8::internal; static v8::Persistent<v8::Context> env; static struct { TickSample* sample; } trace_env = { NULL }; static void InitTraceEnv(TickSample* sample) { trace_env.sample = sample; } static void DoTrace(Address fp) { trace_env.sample->fp = fp; // sp is only used to define stack high bound trace_env.sample->sp = reinterpret_cast<Address>(trace_env.sample) - 10240; StackTracer::Trace(trace_env.sample); } // Hide c_entry_fp to emulate situation when sampling is done while // pure JS code is being executed static void DoTraceHideCEntryFPAddress(Address fp) { v8::internal::Address saved_c_frame_fp = *(Top::c_entry_fp_address()); CHECK(saved_c_frame_fp); *(Top::c_entry_fp_address()) = 0; DoTrace(fp); *(Top::c_entry_fp_address()) = saved_c_frame_fp; } static void CheckRetAddrIsInFunction(const char* func_name, Address ret_addr, Address func_start_addr, unsigned int func_len) { printf("CheckRetAddrIsInFunction \"%s\": %p %p %p\n", func_name, func_start_addr, ret_addr, func_start_addr + func_len); CHECK_GE(ret_addr, func_start_addr); CHECK_GE(func_start_addr + func_len, ret_addr); } static void CheckRetAddrIsInJSFunction(const char* func_name, Address ret_addr, Handle<JSFunction> func) { v8::internal::Code* func_code = func->code(); CheckRetAddrIsInFunction( func_name, ret_addr, func_code->instruction_start(), func_code->ExecutableSize()); } // --- T r a c e E x t e n s i o n --- class TraceExtension : public v8::Extension { public: TraceExtension() : v8::Extension("v8/trace", kSource) { } virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction( v8::Handle<String> name); static v8::Handle<v8::Value> Trace(const v8::Arguments& args); static v8::Handle<v8::Value> JSTrace(const v8::Arguments& args); static v8::Handle<v8::Value> JSEntrySP(const v8::Arguments& args); static v8::Handle<v8::Value> JSEntrySPLevel2(const v8::Arguments& args); private: static Address GetFP(const v8::Arguments& args); static const char* kSource; }; const char* TraceExtension::kSource = "native function trace();" "native function js_trace();" "native function js_entry_sp();" "native function js_entry_sp_level2();"; v8::Handle<v8::FunctionTemplate> TraceExtension::GetNativeFunction( v8::Handle<String> name) { if (name->Equals(String::New("trace"))) { return v8::FunctionTemplate::New(TraceExtension::Trace); } else if (name->Equals(String::New("js_trace"))) { return v8::FunctionTemplate::New(TraceExtension::JSTrace); } else if (name->Equals(String::New("js_entry_sp"))) { return v8::FunctionTemplate::New(TraceExtension::JSEntrySP); } else if (name->Equals(String::New("js_entry_sp_level2"))) { return v8::FunctionTemplate::New(TraceExtension::JSEntrySPLevel2); } else { CHECK(false); return v8::Handle<v8::FunctionTemplate>(); } } Address TraceExtension::GetFP(const v8::Arguments& args) { CHECK_EQ(1, args.Length()); // CodeGenerator::GenerateGetFramePointer pushes EBP / RBP value // on stack. In 64-bit mode we can't use Smi operations code because // they check that value is within Smi bounds. Address fp = *reinterpret_cast<Address*>(*args[0]); printf("Trace: %p\n", fp); return fp; } v8::Handle<v8::Value> TraceExtension::Trace(const v8::Arguments& args) { DoTrace(GetFP(args)); return v8::Undefined(); } v8::Handle<v8::Value> TraceExtension::JSTrace(const v8::Arguments& args) { DoTraceHideCEntryFPAddress(GetFP(args)); return v8::Undefined(); } static Address GetJsEntrySp() { CHECK_NE(NULL, Top::GetCurrentThread()); return Top::js_entry_sp(Top::GetCurrentThread()); } v8::Handle<v8::Value> TraceExtension::JSEntrySP(const v8::Arguments& args) { CHECK_NE(0, GetJsEntrySp()); return v8::Undefined(); } v8::Handle<v8::Value> TraceExtension::JSEntrySPLevel2( const v8::Arguments& args) { v8::HandleScope scope; const Address js_entry_sp = GetJsEntrySp(); CHECK_NE(0, js_entry_sp); CompileRun("js_entry_sp();"); CHECK_EQ(js_entry_sp, GetJsEntrySp()); return v8::Undefined(); } static TraceExtension kTraceExtension; v8::DeclareExtension kTraceExtensionDeclaration(&kTraceExtension); static void InitializeVM() { if (env.IsEmpty()) { v8::HandleScope scope; const char* extensions[] = { "v8/trace" }; v8::ExtensionConfiguration config(1, extensions); env = v8::Context::New(&config); } v8::HandleScope scope; env->Enter(); } static Handle<JSFunction> CompileFunction(const char* source) { Handle<JSFunction> result(JSFunction::cast( *v8::Utils::OpenHandle(*Script::Compile(String::New(source))))); return result; } static Local<Value> GetGlobalProperty(const char* name) { return env->Global()->Get(String::New(name)); } static Handle<JSFunction> GetGlobalJSFunction(const char* name) { Handle<JSFunction> result(JSFunction::cast( *v8::Utils::OpenHandle(*GetGlobalProperty(name)))); return result; } static void CheckRetAddrIsInJSFunction(const char* func_name, Address ret_addr) { CheckRetAddrIsInJSFunction(func_name, ret_addr, GetGlobalJSFunction(func_name)); } static void SetGlobalProperty(const char* name, Local<Value> value) { env->Global()->Set(String::New(name), value); } static Handle<v8::internal::String> NewString(const char* s) { return i::Factory::NewStringFromAscii(i::CStrVector(s)); } namespace v8 { namespace internal { class CodeGeneratorPatcher { public: CodeGeneratorPatcher() { CodeGenerator::InlineRuntimeLUT genGetFramePointer = {&CodeGenerator::GenerateGetFramePointer, "_GetFramePointer", 0}; // _RandomPositiveSmi is not used in our tests. The one we replace need to // have the same number of arguments as the one we put in, which is zero in // this case. bool result = CodeGenerator::PatchInlineRuntimeEntry( NewString("_RandomPositiveSmi"), genGetFramePointer, &oldInlineEntry); CHECK(result); } ~CodeGeneratorPatcher() { CHECK(CodeGenerator::PatchInlineRuntimeEntry( NewString("_GetFramePointer"), oldInlineEntry, NULL)); } private: CodeGenerator::InlineRuntimeLUT oldInlineEntry; }; } } // namespace v8::internal // Creates a global function named 'func_name' that calls the tracing // function 'trace_func_name' with an actual EBP register value, // shifted right to be presented as Smi. static void CreateTraceCallerFunction(const char* func_name, const char* trace_func_name) { i::EmbeddedVector<char, 256> trace_call_buf; i::OS::SNPrintF(trace_call_buf, "%s(%%_GetFramePointer());", trace_func_name); // Compile the script. i::CodeGeneratorPatcher patcher; bool allow_natives_syntax = i::FLAG_allow_natives_syntax; i::FLAG_allow_natives_syntax = true; Handle<JSFunction> func = CompileFunction(trace_call_buf.start()); CHECK(!func.is_null()); i::FLAG_allow_natives_syntax = allow_natives_syntax; #ifdef DEBUG v8::internal::Code* func_code = func->code(); CHECK(func_code->IsCode()); func_code->Print(); #endif SetGlobalProperty(func_name, v8::ToApi<Value>(func)); CHECK_EQ(*func, *GetGlobalJSFunction(func_name)); } TEST(CFromJSStackTrace) { TickSample sample; InitTraceEnv(&sample); InitializeVM(); v8::HandleScope scope; CreateTraceCallerFunction("JSFuncDoTrace", "trace"); Local<Value> result = CompileRun( "function JSTrace() {" " JSFuncDoTrace();" "};\n" "JSTrace();\n" "true;"); CHECK(!result.IsEmpty()); CHECK_GT(sample.frames_count, 1); // Stack sampling will start from the first JS function, i.e. "JSFuncDoTrace" CheckRetAddrIsInJSFunction("JSFuncDoTrace", sample.stack[0]); CheckRetAddrIsInJSFunction("JSTrace", sample.stack[1]); } TEST(PureJSStackTrace) { TickSample sample; InitTraceEnv(&sample); InitializeVM(); v8::HandleScope scope; CreateTraceCallerFunction("JSFuncDoTrace", "js_trace"); Local<Value> result = CompileRun( "function JSTrace() {" " JSFuncDoTrace();" "};\n" "function OuterJSTrace() {" " JSTrace();" "};\n" "OuterJSTrace();\n" "true;"); CHECK(!result.IsEmpty()); // The last JS function called. CHECK_EQ(GetGlobalJSFunction("JSFuncDoTrace")->address(), sample.function); CHECK_GT(sample.frames_count, 1); // Stack sampling will start from the caller of JSFuncDoTrace, i.e. "JSTrace" CheckRetAddrIsInJSFunction("JSTrace", sample.stack[0]); CheckRetAddrIsInJSFunction("OuterJSTrace", sample.stack[1]); } static void CFuncDoTrace(byte dummy_parameter) { Address fp; #ifdef __GNUC__ fp = reinterpret_cast<Address>(__builtin_frame_address(0)); #elif defined _MSC_VER // Approximate a frame pointer address. We compile without base pointers, // so we can't trust ebp/rbp. fp = &dummy_parameter - 2 * sizeof(void*); // NOLINT #else #error Unexpected platform. #endif DoTrace(fp); } static int CFunc(int depth) { if (depth <= 0) { CFuncDoTrace(0); return 0; } else { return CFunc(depth - 1) + 1; } } TEST(PureCStackTrace) { TickSample sample; InitTraceEnv(&sample); // Check that sampler doesn't crash CHECK_EQ(10, CFunc(10)); } TEST(JsEntrySp) { InitializeVM(); v8::HandleScope scope; CHECK_EQ(0, GetJsEntrySp()); CompileRun("a = 1; b = a + 1;"); CHECK_EQ(0, GetJsEntrySp()); CompileRun("js_entry_sp();"); CHECK_EQ(0, GetJsEntrySp()); CompileRun("js_entry_sp_level2();"); CHECK_EQ(0, GetJsEntrySp()); } #endif // ENABLE_LOGGING_AND_PROFILING <commit_msg>Add comments to test-log-stack-tracer.<commit_after>// Copyright 2006-2009 the V8 project authors. All rights reserved. // // Tests of profiler-related functions from log.h #ifdef ENABLE_LOGGING_AND_PROFILING #include <stdlib.h> #include "v8.h" #include "codegen.h" #include "log.h" #include "top.h" #include "cctest.h" #include "disassembler.h" #include "register-allocator-inl.h" using v8::Function; using v8::Local; using v8::Object; using v8::Script; using v8::String; using v8::Value; using v8::internal::byte; using v8::internal::Address; using v8::internal::Handle; using v8::internal::JSFunction; using v8::internal::StackTracer; using v8::internal::TickSample; using v8::internal::Top; namespace i = v8::internal; static v8::Persistent<v8::Context> env; static struct { TickSample* sample; } trace_env = { NULL }; static void InitTraceEnv(TickSample* sample) { trace_env.sample = sample; } static void DoTrace(Address fp) { trace_env.sample->fp = fp; // sp is only used to define stack high bound trace_env.sample->sp = reinterpret_cast<Address>(trace_env.sample) - 10240; StackTracer::Trace(trace_env.sample); } // Hide c_entry_fp to emulate situation when sampling is done while // pure JS code is being executed static void DoTraceHideCEntryFPAddress(Address fp) { v8::internal::Address saved_c_frame_fp = *(Top::c_entry_fp_address()); CHECK(saved_c_frame_fp); *(Top::c_entry_fp_address()) = 0; DoTrace(fp); *(Top::c_entry_fp_address()) = saved_c_frame_fp; } static void CheckRetAddrIsInFunction(const char* func_name, Address ret_addr, Address func_start_addr, unsigned int func_len) { printf("CheckRetAddrIsInFunction \"%s\": %p %p %p\n", func_name, func_start_addr, ret_addr, func_start_addr + func_len); CHECK_GE(ret_addr, func_start_addr); CHECK_GE(func_start_addr + func_len, ret_addr); } static void CheckRetAddrIsInJSFunction(const char* func_name, Address ret_addr, Handle<JSFunction> func) { v8::internal::Code* func_code = func->code(); CheckRetAddrIsInFunction( func_name, ret_addr, func_code->instruction_start(), func_code->ExecutableSize()); } // --- T r a c e E x t e n s i o n --- class TraceExtension : public v8::Extension { public: TraceExtension() : v8::Extension("v8/trace", kSource) { } virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction( v8::Handle<String> name); static v8::Handle<v8::Value> Trace(const v8::Arguments& args); static v8::Handle<v8::Value> JSTrace(const v8::Arguments& args); static v8::Handle<v8::Value> JSEntrySP(const v8::Arguments& args); static v8::Handle<v8::Value> JSEntrySPLevel2(const v8::Arguments& args); private: static Address GetFP(const v8::Arguments& args); static const char* kSource; }; const char* TraceExtension::kSource = "native function trace();" "native function js_trace();" "native function js_entry_sp();" "native function js_entry_sp_level2();"; v8::Handle<v8::FunctionTemplate> TraceExtension::GetNativeFunction( v8::Handle<String> name) { if (name->Equals(String::New("trace"))) { return v8::FunctionTemplate::New(TraceExtension::Trace); } else if (name->Equals(String::New("js_trace"))) { return v8::FunctionTemplate::New(TraceExtension::JSTrace); } else if (name->Equals(String::New("js_entry_sp"))) { return v8::FunctionTemplate::New(TraceExtension::JSEntrySP); } else if (name->Equals(String::New("js_entry_sp_level2"))) { return v8::FunctionTemplate::New(TraceExtension::JSEntrySPLevel2); } else { CHECK(false); return v8::Handle<v8::FunctionTemplate>(); } } Address TraceExtension::GetFP(const v8::Arguments& args) { CHECK_EQ(1, args.Length()); // CodeGenerator::GenerateGetFramePointer pushes EBP / RBP value // on stack. In 64-bit mode we can't use Smi operations code because // they check that value is within Smi bounds. Address fp = *reinterpret_cast<Address*>(*args[0]); printf("Trace: %p\n", fp); return fp; } v8::Handle<v8::Value> TraceExtension::Trace(const v8::Arguments& args) { DoTrace(GetFP(args)); return v8::Undefined(); } v8::Handle<v8::Value> TraceExtension::JSTrace(const v8::Arguments& args) { DoTraceHideCEntryFPAddress(GetFP(args)); return v8::Undefined(); } static Address GetJsEntrySp() { CHECK_NE(NULL, Top::GetCurrentThread()); return Top::js_entry_sp(Top::GetCurrentThread()); } v8::Handle<v8::Value> TraceExtension::JSEntrySP(const v8::Arguments& args) { CHECK_NE(0, GetJsEntrySp()); return v8::Undefined(); } v8::Handle<v8::Value> TraceExtension::JSEntrySPLevel2( const v8::Arguments& args) { v8::HandleScope scope; const Address js_entry_sp = GetJsEntrySp(); CHECK_NE(0, js_entry_sp); CompileRun("js_entry_sp();"); CHECK_EQ(js_entry_sp, GetJsEntrySp()); return v8::Undefined(); } static TraceExtension kTraceExtension; v8::DeclareExtension kTraceExtensionDeclaration(&kTraceExtension); static void InitializeVM() { if (env.IsEmpty()) { v8::HandleScope scope; const char* extensions[] = { "v8/trace" }; v8::ExtensionConfiguration config(1, extensions); env = v8::Context::New(&config); } v8::HandleScope scope; env->Enter(); } static Handle<JSFunction> CompileFunction(const char* source) { Handle<JSFunction> result(JSFunction::cast( *v8::Utils::OpenHandle(*Script::Compile(String::New(source))))); return result; } static Local<Value> GetGlobalProperty(const char* name) { return env->Global()->Get(String::New(name)); } static Handle<JSFunction> GetGlobalJSFunction(const char* name) { Handle<JSFunction> result(JSFunction::cast( *v8::Utils::OpenHandle(*GetGlobalProperty(name)))); return result; } static void CheckRetAddrIsInJSFunction(const char* func_name, Address ret_addr) { CheckRetAddrIsInJSFunction(func_name, ret_addr, GetGlobalJSFunction(func_name)); } static void SetGlobalProperty(const char* name, Local<Value> value) { env->Global()->Set(String::New(name), value); } static Handle<v8::internal::String> NewString(const char* s) { return i::Factory::NewStringFromAscii(i::CStrVector(s)); } namespace v8 { namespace internal { class CodeGeneratorPatcher { public: CodeGeneratorPatcher() { CodeGenerator::InlineRuntimeLUT genGetFramePointer = {&CodeGenerator::GenerateGetFramePointer, "_GetFramePointer", 0}; // _RandomPositiveSmi is not used in our tests. The one we replace need to // have the same number of arguments as the one we put in, which is zero in // this case. bool result = CodeGenerator::PatchInlineRuntimeEntry( NewString("_RandomPositiveSmi"), genGetFramePointer, &oldInlineEntry); CHECK(result); } ~CodeGeneratorPatcher() { CHECK(CodeGenerator::PatchInlineRuntimeEntry( NewString("_GetFramePointer"), oldInlineEntry, NULL)); } private: CodeGenerator::InlineRuntimeLUT oldInlineEntry; }; } } // namespace v8::internal // Creates a global function named 'func_name' that calls the tracing // function 'trace_func_name' with an actual EBP register value, // shifted right to be presented as Smi. static void CreateTraceCallerFunction(const char* func_name, const char* trace_func_name) { i::EmbeddedVector<char, 256> trace_call_buf; i::OS::SNPrintF(trace_call_buf, "%s(%%_GetFramePointer());", trace_func_name); // Compile the script. i::CodeGeneratorPatcher patcher; bool allow_natives_syntax = i::FLAG_allow_natives_syntax; i::FLAG_allow_natives_syntax = true; Handle<JSFunction> func = CompileFunction(trace_call_buf.start()); CHECK(!func.is_null()); i::FLAG_allow_natives_syntax = allow_natives_syntax; #ifdef DEBUG v8::internal::Code* func_code = func->code(); CHECK(func_code->IsCode()); func_code->Print(); #endif SetGlobalProperty(func_name, v8::ToApi<Value>(func)); CHECK_EQ(*func, *GetGlobalJSFunction(func_name)); } // This test verifies that stack tracing works when called during // execution of a native function called from JS code. In this case, // StackTracer uses Top::c_entry_fp as a starting point for stack // walking. TEST(CFromJSStackTrace) { TickSample sample; InitTraceEnv(&sample); InitializeVM(); v8::HandleScope scope; // Create global function JSFuncDoTrace which calls // extension function trace() with the current frame pointer value. CreateTraceCallerFunction("JSFuncDoTrace", "trace"); Local<Value> result = CompileRun( "function JSTrace() {" " JSFuncDoTrace();" "};\n" "JSTrace();\n" "true;"); CHECK(!result.IsEmpty()); // When stack tracer is invoked, the stack should look as follows: // script [JS] // JSTrace() [JS] // JSFuncDoTrace() [JS] [captures EBP value and encodes it as Smi] // trace(EBP encoded as Smi) [native (extension)] // DoTrace(EBP) [native] // StackTracer::Trace CHECK_GT(sample.frames_count, 1); // Stack tracing will start from the first JS function, i.e. "JSFuncDoTrace" CheckRetAddrIsInJSFunction("JSFuncDoTrace", sample.stack[0]); CheckRetAddrIsInJSFunction("JSTrace", sample.stack[1]); } // This test verifies that stack tracing works when called during // execution of JS code. However, as calling StackTracer requires // entering native code, we can only emulate pure JS by erasing // Top::c_entry_fp value. In this case, StackTracer uses passed frame // pointer value as a starting point for stack walking. TEST(PureJSStackTrace) { TickSample sample; InitTraceEnv(&sample); InitializeVM(); v8::HandleScope scope; // Create global function JSFuncDoTrace which calls // extension function js_trace() with the current frame pointer value. CreateTraceCallerFunction("JSFuncDoTrace", "js_trace"); Local<Value> result = CompileRun( "function JSTrace() {" " JSFuncDoTrace();" "};\n" "function OuterJSTrace() {" " JSTrace();" "};\n" "OuterJSTrace();\n" "true;"); CHECK(!result.IsEmpty()); // When stack tracer is invoked, the stack should look as follows: // script [JS] // OuterJSTrace() [JS] // JSTrace() [JS] // JSFuncDoTrace() [JS] [captures EBP value and encodes it as Smi] // js_trace(EBP encoded as Smi) [native (extension)] // DoTraceHideCEntryFPAddress(EBP) [native] // StackTracer::Trace // // The last JS function called. It is only visible through // sample.function, as its return address is above captured EBP value. CHECK_EQ(GetGlobalJSFunction("JSFuncDoTrace")->address(), sample.function); CHECK_GT(sample.frames_count, 1); // Stack sampling will start from the caller of JSFuncDoTrace, i.e. "JSTrace" CheckRetAddrIsInJSFunction("JSTrace", sample.stack[0]); CheckRetAddrIsInJSFunction("OuterJSTrace", sample.stack[1]); } static void CFuncDoTrace(byte dummy_parameter) { Address fp; #ifdef __GNUC__ fp = reinterpret_cast<Address>(__builtin_frame_address(0)); #elif defined _MSC_VER // Approximate a frame pointer address. We compile without base pointers, // so we can't trust ebp/rbp. fp = &dummy_parameter - 2 * sizeof(void*); // NOLINT #else #error Unexpected platform. #endif DoTrace(fp); } static int CFunc(int depth) { if (depth <= 0) { CFuncDoTrace(0); return 0; } else { return CFunc(depth - 1) + 1; } } // This test verifies that stack tracing doesn't crash when called on // pure native code. StackTracer only unrolls JS code, so we can't // get any meaningful info here. TEST(PureCStackTrace) { TickSample sample; InitTraceEnv(&sample); // Check that sampler doesn't crash CHECK_EQ(10, CFunc(10)); } TEST(JsEntrySp) { InitializeVM(); v8::HandleScope scope; CHECK_EQ(0, GetJsEntrySp()); CompileRun("a = 1; b = a + 1;"); CHECK_EQ(0, GetJsEntrySp()); CompileRun("js_entry_sp();"); CHECK_EQ(0, GetJsEntrySp()); CompileRun("js_entry_sp_level2();"); CHECK_EQ(0, GetJsEntrySp()); } #endif // ENABLE_LOGGING_AND_PROFILING <|endoftext|>
<commit_before>#include "common/ceph_crypto.h" #include "gtest/gtest.h" class CryptoEnvironment: public ::testing::Environment { public: void SetUp() { ceph::crypto::init(); } }; ::testing::Environment* const crypto_env = ::testing::AddGlobalTestEnvironment(new CryptoEnvironment); TEST(MD5, DigestSize) { int s = ceph::crypto::MD5::DIGESTSIZE; ASSERT_EQ(16, s); } TEST(MD5, Simple) { ceph::crypto::MD5 h; h.Update((const byte*)"foo", 3); unsigned char digest[ceph::crypto::MD5::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::MD5::DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, ceph::crypto::MD5::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(MD5, MultiUpdate) { ceph::crypto::MD5 h; h.Update((const byte*)"", 0); h.Update((const byte*)"fo", 2); h.Update((const byte*)"", 0); h.Update((const byte*)"o", 1); h.Update((const byte*)"", 0); unsigned char digest[ceph::crypto::MD5::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::MD5::DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, ceph::crypto::MD5::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(MD5, Restart) { ceph::crypto::MD5 h; h.Update((const byte*)"bar", 3); h.Restart(); h.Update((const byte*)"foo", 3); unsigned char digest[ceph::crypto::MD5::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::MD5::DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, ceph::crypto::MD5::DIGESTSIZE); ASSERT_EQ(0, err); } <commit_msg>ceph_crypto: Add unittests for the HMAC-SHA1 compatibility shim.<commit_after>#include "common/ceph_crypto.h" #include "gtest/gtest.h" class CryptoEnvironment: public ::testing::Environment { public: void SetUp() { ceph::crypto::init(); } }; ::testing::Environment* const crypto_env = ::testing::AddGlobalTestEnvironment(new CryptoEnvironment); TEST(MD5, DigestSize) { int s = ceph::crypto::MD5::DIGESTSIZE; ASSERT_EQ(16, s); } TEST(MD5, Simple) { ceph::crypto::MD5 h; h.Update((const byte*)"foo", 3); unsigned char digest[ceph::crypto::MD5::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::MD5::DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, ceph::crypto::MD5::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(MD5, MultiUpdate) { ceph::crypto::MD5 h; h.Update((const byte*)"", 0); h.Update((const byte*)"fo", 2); h.Update((const byte*)"", 0); h.Update((const byte*)"o", 1); h.Update((const byte*)"", 0); unsigned char digest[ceph::crypto::MD5::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::MD5::DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, ceph::crypto::MD5::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(MD5, Restart) { ceph::crypto::MD5 h; h.Update((const byte*)"bar", 3); h.Restart(); h.Update((const byte*)"foo", 3); unsigned char digest[ceph::crypto::MD5::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::MD5::DIGESTSIZE] = { 0xac, 0xbd, 0x18, 0xdb, 0x4c, 0xc2, 0xf8, 0x5c, 0xed, 0xef, 0x65, 0x4f, 0xcc, 0xc4, 0xa4, 0xd8, }; err = memcmp(digest, want_digest, ceph::crypto::MD5::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(HMACSHA1, DigestSize) { int s = ceph::crypto::HMACSHA1::DIGESTSIZE; ASSERT_EQ(20, s); } TEST(HMACSHA1, Simple) { ceph::crypto::HMACSHA1 h((const byte*)"sekrit", 6); h.Update((const byte*)"foo", 3); unsigned char digest[ceph::crypto::HMACSHA1::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::HMACSHA1::DIGESTSIZE] = { 0x04, 0xbc, 0x52, 0x66, 0xb6, 0xff, 0xad, 0xad, 0x9d, 0x57, 0xce, 0x13, 0xea, 0x8c, 0xf5, 0x6b, 0xf9, 0x95, 0x2f, 0xd6, }; err = memcmp(digest, want_digest, ceph::crypto::HMACSHA1::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(HMACSHA1, MultiUpdate) { ceph::crypto::HMACSHA1 h((const byte*)"sekrit", 6); h.Update((const byte*)"", 0); h.Update((const byte*)"fo", 2); h.Update((const byte*)"", 0); h.Update((const byte*)"o", 1); h.Update((const byte*)"", 0); unsigned char digest[ceph::crypto::HMACSHA1::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::HMACSHA1::DIGESTSIZE] = { 0x04, 0xbc, 0x52, 0x66, 0xb6, 0xff, 0xad, 0xad, 0x9d, 0x57, 0xce, 0x13, 0xea, 0x8c, 0xf5, 0x6b, 0xf9, 0x95, 0x2f, 0xd6, }; err = memcmp(digest, want_digest, ceph::crypto::HMACSHA1::DIGESTSIZE); ASSERT_EQ(0, err); } TEST(HMACSHA1, Restart) { ceph::crypto::HMACSHA1 h((const byte*)"sekrit", 6); h.Update((const byte*)"bar", 3); h.Restart(); h.Update((const byte*)"foo", 3); unsigned char digest[ceph::crypto::HMACSHA1::DIGESTSIZE]; h.Final(digest); int err; unsigned char want_digest[ceph::crypto::HMACSHA1::DIGESTSIZE] = { 0x04, 0xbc, 0x52, 0x66, 0xb6, 0xff, 0xad, 0xad, 0x9d, 0x57, 0xce, 0x13, 0xea, 0x8c, 0xf5, 0x6b, 0xf9, 0x95, 0x2f, 0xd6, }; err = memcmp(digest, want_digest, ceph::crypto::HMACSHA1::DIGESTSIZE); ASSERT_EQ(0, err); } <|endoftext|>
<commit_before>#include "JsPlayer.h" #include <string.h> #include <node_buffer.h> #include <nah/NodeHelpers.h> /////////////////////////////////////////////////////////////////////////////// struct JsPlayer::AsyncData { virtual void process( JsPlayer* ) = 0; }; /////////////////////////////////////////////////////////////////////////////// struct JsPlayer::AppSinkEventData : public JsPlayer::AsyncData { AppSinkEventData( GstAppSink* appSink, JsPlayer::AppSinkEvent event ) : appSink( appSink), event( event ) {} void process( JsPlayer* ); GstAppSink* appSink; const JsPlayer::AppSinkEvent event; }; void JsPlayer::AppSinkEventData::process( JsPlayer* player ) { switch( event ) { case JsPlayer::AppSinkEvent::NewPreroll: player->onNewPreroll( appSink ); break; case JsPlayer::AppSinkEvent::NewSample: player->onNewSample( appSink ); break; case JsPlayer::AppSinkEvent::Eos: player->onEos( appSink ); break; } } /////////////////////////////////////////////////////////////////////////////// v8::Persistent<v8::Function> JsPlayer::_jsConstructor; std::set<JsPlayer*> JsPlayer::_instances; void JsPlayer::initJsApi( const v8::Handle<v8::Object>& exports ) { node::AtExit( [] ( void* ) { JsPlayer::closeAll(); } ); gst_init( 0, 0 ); using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New( isolate, jsCreate ); constructorTemplate->SetClassName( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ) ); Local<ObjectTemplate> instanceTemplate = constructorTemplate->InstanceTemplate(); instanceTemplate->SetInternalFieldCount( 1 ); SET_METHOD( instanceTemplate, "parseLaunch", &JsPlayer::parseLaunch ); SET_METHOD( instanceTemplate, "addAppSinkCallback", &JsPlayer::addAppSinkCallback ); SET_METHOD( instanceTemplate, "setState", &JsPlayer::setState ); Local<Function> constructor = constructorTemplate->GetFunction(); _jsConstructor.Reset( isolate, constructor ); exports->Set( String::NewFromUtf8( isolate, "createPlayer", v8::String::kInternalizedString ), constructor ); exports->Set( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ), constructor ); } void JsPlayer::jsCreate( const v8::FunctionCallbackInfo<v8::Value>& args ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<Object> thisObject = args.Holder(); if( args.IsConstructCall() ) { JsPlayer* jsPlayer = new JsPlayer( thisObject ); args.GetReturnValue().Set( jsPlayer->handle() ); } else { Local<Value> argv[] = { args[0] }; Local<Function> constructor = Local<Function>::New( isolate, _jsConstructor ); args.GetReturnValue().Set( constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) ); } } void JsPlayer::closeAll() { for( JsPlayer* p : _instances ) { p->close(); } gst_deinit(); } JsPlayer::JsPlayer( v8::Local<v8::Object>& thisObject ) : _pipeline( nullptr ), _firstSample( true ) { Wrap( thisObject ); _instances.insert( this ); uv_loop_t* loop = uv_default_loop(); uv_async_init( loop, &_async, [] ( uv_async_t* handle ) { if( handle->data ) reinterpret_cast<JsPlayer*>( handle->data )->handleAsync(); } ); _async.data = this; } JsPlayer::~JsPlayer() { close(); _instances.erase( this ); } void JsPlayer::close() { _async.data = nullptr; uv_close( reinterpret_cast<uv_handle_t*>( &_async ), 0 ); } void JsPlayer::handleAsync() { while( !_asyncData.empty() ) { std::deque<std::unique_ptr<AsyncData> > tmpData; _asyncDataGuard.lock(); _asyncData.swap( tmpData ); _asyncDataGuard.unlock(); for( const auto& i: tmpData ) { i->process( this ); } } } GstFlowReturn JsPlayer::onNewPrerollProxy( GstAppSink *appSink, gpointer userData ) { JsPlayer* player = static_cast<JsPlayer*>( userData ); player->_asyncDataGuard.lock(); player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewPreroll ) ); player->_asyncDataGuard.unlock(); uv_async_send( &player->_async ); return GST_FLOW_OK; } GstFlowReturn JsPlayer::onNewSampleProxy( GstAppSink *appSink, gpointer userData ) { JsPlayer* player = static_cast<JsPlayer*>( userData ); player->_appSinks[appSink].waitingSample.clear(); player->_asyncDataGuard.lock(); player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewSample ) ); player->_asyncDataGuard.unlock(); uv_async_send( &player->_async ); return GST_FLOW_OK; } void JsPlayer::onEosProxy( GstAppSink* appSink, gpointer userData ) { JsPlayer* player = static_cast<JsPlayer*>( userData ); player->_asyncDataGuard.lock(); player->_asyncData.emplace_back( new AppSinkEventData( appSink, Eos ) ); player->_asyncDataGuard.unlock(); uv_async_send( &player->_async ); } void JsPlayer::callCallback( GstAppSink* appSink, JsPlayer::AppSinkEvent event, std::initializer_list<v8::Local<v8::Value> > list ) { auto it = _appSinks.find( appSink ); if( _appSinks.end() == it ) return; if( it->second.callback.IsEmpty() ) return; using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<Function> callbackFunc = Local<Function>::New( isolate, _appSinks[appSink].callback ); std::vector<v8::Local<v8::Value> > argList; argList.push_back( Integer::New( isolate, event ) ); argList.insert( argList.end(), list ); callbackFunc->Call( handle(), static_cast<int>( argList.size() ), argList.data() ); } void JsPlayer::onSetup( GstAppSink* appSink, const GstVideoInfo& videoInfo ) { if( !appSink ) return; using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); _firstSample = false; callCallback( appSink, Setup, { String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ), Integer::New( isolate, videoInfo.width ), Integer::New( isolate, videoInfo.height ), Integer::New( isolate, videoInfo.finfo->format ) } ); } void JsPlayer::onNewPreroll( GstAppSink* appSink ) { GstSample* sample = gst_app_sink_pull_preroll( appSink ); onSample( appSink, sample, true ); gst_sample_unref( sample ); } void JsPlayer::onNewSample( GstAppSink* appSink ) { if( _appSinks[appSink].waitingSample.test_and_set() ) return; GstSample* sample = gst_app_sink_pull_sample( appSink ); _appSinks[appSink].waitingSample.test_and_set(); onSample( appSink, sample, false ); gst_sample_unref( sample ); } void JsPlayer::onSample( GstAppSink* appSink, GstSample* sample, bool preroll ) { if( !sample ) return; GstVideoInfo videoInfo; GstCaps* caps = gst_sample_get_caps( sample ); if( !caps || !gst_video_info_from_caps( &videoInfo, caps ) ) return; if( _firstSample ) onSetup( appSink, videoInfo ); GstBuffer* buffer = gst_sample_get_buffer( sample ); if( !buffer ) return; GstMapInfo mapInfo; if( gst_buffer_map( buffer, &mapInfo, GST_MAP_READ ) ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); v8::MaybeLocal<v8::Object> maybeFrame = node::Buffer::New( isolate, reinterpret_cast<char*>( mapInfo.data ), mapInfo.size, [] ( char* data, void* hint ) {}, nullptr ); Local<v8::Object> frame; if( maybeFrame.ToLocal( &frame ) ) { frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormatName", v8::String::kInternalizedString ), String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormat", v8::String::kInternalizedString ), Integer::New( isolate, videoInfo.finfo->format ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); frame->ForceSet( String::NewFromUtf8( isolate, "width", v8::String::kInternalizedString ), Integer::New( isolate, videoInfo.width ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); frame->ForceSet( String::NewFromUtf8( isolate, "height", v8::String::kInternalizedString ), Integer::New( isolate, videoInfo.height ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); Local<Array> planes = Array::New( isolate, videoInfo.finfo->n_planes ); for( guint p = 0; p < videoInfo.finfo->n_planes; ++p ) { planes->Set( p, Integer::New( isolate, videoInfo.offset[p] ) ); } frame->ForceSet( String::NewFromUtf8( isolate, "planes", v8::String::kInternalizedString ), planes, static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); callCallback( appSink, ( preroll ? NewPreroll : NewSample ), { frame } ); } gst_buffer_unmap( buffer, &mapInfo ); } } void JsPlayer::onEos( GstAppSink* appSink ) { callCallback( appSink, Eos ); } bool JsPlayer::parseLaunch( const std::string& pipelineDescription ) { if( _pipeline ) { _appSinks.clear(); gst_object_unref( _pipeline ); _pipeline = nullptr; _firstSample = true; } GError* error = nullptr; _pipeline = gst_parse_launch( pipelineDescription.c_str(), &error ); return ( nullptr != _pipeline ); } bool JsPlayer::addAppSinkCallback( const std::string& appSinkName, v8::Local<v8::Value> value ) { if( !_pipeline || appSinkName.empty() ) return false; GstElement* sink = gst_bin_get_by_name( GST_BIN( _pipeline ), appSinkName.c_str() ); if( !sink ) return false; GstAppSink* appSink = GST_APP_SINK_CAST( sink ); if( !appSink ) return appSink; using namespace v8; Local<Function> callbackFunc = Local<Function>::Cast( value ); if( callbackFunc.IsEmpty() ) return false; auto it = _appSinks.find( appSink ); if( _appSinks.end() == it ) { gst_app_sink_set_drop( appSink, true ); gst_app_sink_set_max_buffers( appSink, 1 ); GstAppSinkCallbacks callbacks = { onEosProxy, onNewPrerollProxy, onNewSampleProxy }; gst_app_sink_set_callbacks( appSink, &callbacks, this, nullptr ); it = _appSinks.emplace( appSink, AppSinkData() ).first; } AppSinkData& sinkData = it->second; sinkData.callback.Reset( Isolate::GetCurrent(), callbackFunc ); sinkData.waitingSample.test_and_set(); } void JsPlayer::setState( unsigned state ) { if( _pipeline ) gst_element_set_state( _pipeline, static_cast<GstState>( state ) ); } <commit_msg>state constants added<commit_after>#include "JsPlayer.h" #include <string.h> #include <node_buffer.h> #include <nah/NodeHelpers.h> /////////////////////////////////////////////////////////////////////////////// struct JsPlayer::AsyncData { virtual void process( JsPlayer* ) = 0; }; /////////////////////////////////////////////////////////////////////////////// struct JsPlayer::AppSinkEventData : public JsPlayer::AsyncData { AppSinkEventData( GstAppSink* appSink, JsPlayer::AppSinkEvent event ) : appSink( appSink), event( event ) {} void process( JsPlayer* ); GstAppSink* appSink; const JsPlayer::AppSinkEvent event; }; void JsPlayer::AppSinkEventData::process( JsPlayer* player ) { switch( event ) { case JsPlayer::AppSinkEvent::NewPreroll: player->onNewPreroll( appSink ); break; case JsPlayer::AppSinkEvent::NewSample: player->onNewSample( appSink ); break; case JsPlayer::AppSinkEvent::Eos: player->onEos( appSink ); break; } } /////////////////////////////////////////////////////////////////////////////// v8::Persistent<v8::Function> JsPlayer::_jsConstructor; std::set<JsPlayer*> JsPlayer::_instances; void JsPlayer::initJsApi( const v8::Handle<v8::Object>& exports ) { node::AtExit( [] ( void* ) { JsPlayer::closeAll(); } ); gst_init( 0, 0 ); using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New( isolate, jsCreate ); constructorTemplate->SetClassName( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ) ); Local<ObjectTemplate> instanceTemplate = constructorTemplate->InstanceTemplate(); instanceTemplate->SetInternalFieldCount( 1 ); instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_VOID_PENDING", v8::String::kInternalizedString ), Integer::New( isolate, GST_STATE_VOID_PENDING ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_NULL", v8::String::kInternalizedString ), Integer::New( isolate, GST_STATE_NULL ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_READY", v8::String::kInternalizedString ), Integer::New( isolate, GST_STATE_READY ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_PAUSED", v8::String::kInternalizedString ), Integer::New( isolate, GST_STATE_PAUSED ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); instanceTemplate->Set( String::NewFromUtf8( isolate, "GST_STATE_PLAYING", v8::String::kInternalizedString ), Integer::New( isolate, GST_STATE_PLAYING ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); SET_METHOD( instanceTemplate, "parseLaunch", &JsPlayer::parseLaunch ); SET_METHOD( instanceTemplate, "addAppSinkCallback", &JsPlayer::addAppSinkCallback ); SET_METHOD( instanceTemplate, "setState", &JsPlayer::setState ); Local<Function> constructor = constructorTemplate->GetFunction(); _jsConstructor.Reset( isolate, constructor ); exports->Set( String::NewFromUtf8( isolate, "createPlayer", v8::String::kInternalizedString ), constructor ); exports->Set( String::NewFromUtf8( isolate, "Player", v8::String::kInternalizedString ), constructor ); } void JsPlayer::jsCreate( const v8::FunctionCallbackInfo<v8::Value>& args ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<Object> thisObject = args.Holder(); if( args.IsConstructCall() ) { JsPlayer* jsPlayer = new JsPlayer( thisObject ); args.GetReturnValue().Set( jsPlayer->handle() ); } else { Local<Value> argv[] = { args[0] }; Local<Function> constructor = Local<Function>::New( isolate, _jsConstructor ); args.GetReturnValue().Set( constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) ); } } void JsPlayer::closeAll() { for( JsPlayer* p : _instances ) { p->close(); } gst_deinit(); } JsPlayer::JsPlayer( v8::Local<v8::Object>& thisObject ) : _pipeline( nullptr ), _firstSample( true ) { Wrap( thisObject ); _instances.insert( this ); uv_loop_t* loop = uv_default_loop(); uv_async_init( loop, &_async, [] ( uv_async_t* handle ) { if( handle->data ) reinterpret_cast<JsPlayer*>( handle->data )->handleAsync(); } ); _async.data = this; } JsPlayer::~JsPlayer() { close(); _instances.erase( this ); } void JsPlayer::close() { _async.data = nullptr; uv_close( reinterpret_cast<uv_handle_t*>( &_async ), 0 ); } void JsPlayer::handleAsync() { while( !_asyncData.empty() ) { std::deque<std::unique_ptr<AsyncData> > tmpData; _asyncDataGuard.lock(); _asyncData.swap( tmpData ); _asyncDataGuard.unlock(); for( const auto& i: tmpData ) { i->process( this ); } } } GstFlowReturn JsPlayer::onNewPrerollProxy( GstAppSink *appSink, gpointer userData ) { JsPlayer* player = static_cast<JsPlayer*>( userData ); player->_asyncDataGuard.lock(); player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewPreroll ) ); player->_asyncDataGuard.unlock(); uv_async_send( &player->_async ); return GST_FLOW_OK; } GstFlowReturn JsPlayer::onNewSampleProxy( GstAppSink *appSink, gpointer userData ) { JsPlayer* player = static_cast<JsPlayer*>( userData ); player->_appSinks[appSink].waitingSample.clear(); player->_asyncDataGuard.lock(); player->_asyncData.emplace_back( new AppSinkEventData( appSink, NewSample ) ); player->_asyncDataGuard.unlock(); uv_async_send( &player->_async ); return GST_FLOW_OK; } void JsPlayer::onEosProxy( GstAppSink* appSink, gpointer userData ) { JsPlayer* player = static_cast<JsPlayer*>( userData ); player->_asyncDataGuard.lock(); player->_asyncData.emplace_back( new AppSinkEventData( appSink, Eos ) ); player->_asyncDataGuard.unlock(); uv_async_send( &player->_async ); } void JsPlayer::callCallback( GstAppSink* appSink, JsPlayer::AppSinkEvent event, std::initializer_list<v8::Local<v8::Value> > list ) { auto it = _appSinks.find( appSink ); if( _appSinks.end() == it ) return; if( it->second.callback.IsEmpty() ) return; using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<Function> callbackFunc = Local<Function>::New( isolate, _appSinks[appSink].callback ); std::vector<v8::Local<v8::Value> > argList; argList.push_back( Integer::New( isolate, event ) ); argList.insert( argList.end(), list ); callbackFunc->Call( handle(), static_cast<int>( argList.size() ), argList.data() ); } void JsPlayer::onSetup( GstAppSink* appSink, const GstVideoInfo& videoInfo ) { if( !appSink ) return; using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); _firstSample = false; callCallback( appSink, Setup, { String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ), Integer::New( isolate, videoInfo.width ), Integer::New( isolate, videoInfo.height ), Integer::New( isolate, videoInfo.finfo->format ) } ); } void JsPlayer::onNewPreroll( GstAppSink* appSink ) { GstSample* sample = gst_app_sink_pull_preroll( appSink ); onSample( appSink, sample, true ); gst_sample_unref( sample ); } void JsPlayer::onNewSample( GstAppSink* appSink ) { if( _appSinks[appSink].waitingSample.test_and_set() ) return; GstSample* sample = gst_app_sink_pull_sample( appSink ); _appSinks[appSink].waitingSample.test_and_set(); onSample( appSink, sample, false ); gst_sample_unref( sample ); } void JsPlayer::onSample( GstAppSink* appSink, GstSample* sample, bool preroll ) { if( !sample ) return; GstVideoInfo videoInfo; GstCaps* caps = gst_sample_get_caps( sample ); if( !caps || !gst_video_info_from_caps( &videoInfo, caps ) ) return; if( _firstSample ) onSetup( appSink, videoInfo ); GstBuffer* buffer = gst_sample_get_buffer( sample ); if( !buffer ) return; GstMapInfo mapInfo; if( gst_buffer_map( buffer, &mapInfo, GST_MAP_READ ) ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); v8::MaybeLocal<v8::Object> maybeFrame = node::Buffer::New( isolate, reinterpret_cast<char*>( mapInfo.data ), mapInfo.size, [] ( char* data, void* hint ) {}, nullptr ); Local<v8::Object> frame; if( maybeFrame.ToLocal( &frame ) ) { frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormatName", v8::String::kInternalizedString ), String::NewFromUtf8( isolate, videoInfo.finfo->name, v8::String::kNormalString ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); frame->ForceSet( String::NewFromUtf8( isolate, "pixelFormat", v8::String::kInternalizedString ), Integer::New( isolate, videoInfo.finfo->format ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); frame->ForceSet( String::NewFromUtf8( isolate, "width", v8::String::kInternalizedString ), Integer::New( isolate, videoInfo.width ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); frame->ForceSet( String::NewFromUtf8( isolate, "height", v8::String::kInternalizedString ), Integer::New( isolate, videoInfo.height ), static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); Local<Array> planes = Array::New( isolate, videoInfo.finfo->n_planes ); for( guint p = 0; p < videoInfo.finfo->n_planes; ++p ) { planes->Set( p, Integer::New( isolate, videoInfo.offset[p] ) ); } frame->ForceSet( String::NewFromUtf8( isolate, "planes", v8::String::kInternalizedString ), planes, static_cast<v8::PropertyAttribute>( ReadOnly | DontDelete ) ); callCallback( appSink, ( preroll ? NewPreroll : NewSample ), { frame } ); } gst_buffer_unmap( buffer, &mapInfo ); } } void JsPlayer::onEos( GstAppSink* appSink ) { callCallback( appSink, Eos ); } bool JsPlayer::parseLaunch( const std::string& pipelineDescription ) { if( _pipeline ) { _appSinks.clear(); gst_object_unref( _pipeline ); _pipeline = nullptr; _firstSample = true; } GError* error = nullptr; _pipeline = gst_parse_launch( pipelineDescription.c_str(), &error ); return ( nullptr != _pipeline ); } bool JsPlayer::addAppSinkCallback( const std::string& appSinkName, v8::Local<v8::Value> value ) { if( !_pipeline || appSinkName.empty() ) return false; GstElement* sink = gst_bin_get_by_name( GST_BIN( _pipeline ), appSinkName.c_str() ); if( !sink ) return false; GstAppSink* appSink = GST_APP_SINK_CAST( sink ); if( !appSink ) return appSink; using namespace v8; Local<Function> callbackFunc = Local<Function>::Cast( value ); if( callbackFunc.IsEmpty() ) return false; auto it = _appSinks.find( appSink ); if( _appSinks.end() == it ) { gst_app_sink_set_drop( appSink, true ); gst_app_sink_set_max_buffers( appSink, 1 ); GstAppSinkCallbacks callbacks = { onEosProxy, onNewPrerollProxy, onNewSampleProxy }; gst_app_sink_set_callbacks( appSink, &callbacks, this, nullptr ); it = _appSinks.emplace( appSink, AppSinkData() ).first; } AppSinkData& sinkData = it->second; sinkData.callback.Reset( Isolate::GetCurrent(), callbackFunc ); sinkData.waitingSample.test_and_set(); } void JsPlayer::setState( unsigned state ) { if( _pipeline ) gst_element_set_state( _pipeline, static_cast<GstState>( state ) ); } <|endoftext|>
<commit_before>/* Generated from orogen/lib/orogen/templates/typekit/typelib/OpaqueType.cpp */ #include "OpaqueConvertions.hpp" #include "Types.hpp" #include <rtt/typelib/OpaqueTypelibMarshaller.hpp> #include "transports/typelib/Registration.hpp" orogen_transports::TypelibMarshallerBase* orogen_typekits::<%= type.method_name %>_TypelibMarshaller(Typelib::Registry const& registry) { return new orogen_transports::OpaqueTypelibMarshaller< <%= intermediate.cxx_name %>, <%= type.cxx_name %>, <%= needs_copy %> >("<%= intermediate.cxx_name %>", "<%= type.name %>", registry); } <commit_msg>fix intermediate type name in typelib's marshaller for opaque types<commit_after>/* Generated from orogen/lib/orogen/templates/typekit/typelib/OpaqueType.cpp */ #include "OpaqueConvertions.hpp" #include "Types.hpp" #include <rtt/typelib/OpaqueTypelibMarshaller.hpp> #include "transports/typelib/Registration.hpp" orogen_transports::TypelibMarshallerBase* orogen_typekits::<%= type.method_name %>_TypelibMarshaller(Typelib::Registry const& registry) { return new orogen_transports::OpaqueTypelibMarshaller< <%= intermediate.cxx_name %>, <%= type.cxx_name %>, <%= needs_copy %> >("<%= intermediate.name %>", "<%= type.name %>", registry); } <|endoftext|>
<commit_before>#include "kernel.h" #include "raster.h" #include "rastercoverage.h" #include "pixeliterator.h" #include "connectorinterface.h" #include "symboltable.h" #include "domainitem.h" #include "itemdomain.h" #include "numericitem.h" #include "numericitemrange.h" #include "ilwisoperation.h" quint64 Ilwis::GridBlockInternal::_blockid = 0; using namespace Ilwis; RasterCoverage::RasterCoverage() { } RasterCoverage::RasterCoverage(const Resource& res) : Coverage(res){ } RasterCoverage::~RasterCoverage() { } const IGeoReference& RasterCoverage::georeference() const { return _georef; } void RasterCoverage::georeference(const IGeoReference &grf) { _georef = grf; if ( _grid.isNull() == false) { // remove the current grid, all has become uncertain _grid.reset(0); } if ( _georef.isValid()) { _georef->compute(); setCoordinateSystem(grf->coordinateSystem()); // mandatory } } IlwisTypes RasterCoverage::ilwisType() const { return itRASTER; } RasterCoverage *RasterCoverage::copy() { RasterCoverage *gc = new RasterCoverage(); copyTo(gc); return gc; } void RasterCoverage::copyBinary(const IRasterCoverage& gc, int index) { IRasterCoverage gcNew; gcNew.set(this); Size inputSize = gc->size(); Size sz(inputSize.xsize(),inputSize.ysize(), 1); gcNew->georeference()->size(sz); PixelIterator iterIn(gc, Box3D<>(Voxel(0,0,index), Voxel(inputSize.xsize(), inputSize.ysize(), index + 1))); PixelIterator iterOut(gcNew, Box3D<>(Size(inputSize.xsize(), inputSize.ysize(), 1))); for_each(iterOut, iterOut.end(), [&](double& v){ v = *iterIn; ++iterIn; }); } //IRasterCoverage RasterCoverage::get(quint32 index1, quint32 index2) //{ // IRasterCoverage gcovParent; // gcovParent.set(this); // IRasterCoverage gcov = OperationHelperRaster::initialize(gcovParent,itRASTER, itDOMAIN | itCOORDSYSTEM | itGEOREF); // gcov->size(Size(size().xsize(), size().ysize())); // gcov->_grid.reset(gcov->_grid->clone(index1, index2)); // return gcov; //} Grid *RasterCoverage::grid() { Locker lock(_mutex); if ( _georef->isValid() && !connector().isNull()) { if ( _grid.isNull()) { _grid.reset(connector()->loadGridData(this)); if (_grid.isNull()) return 0; } Grid *grd = _grid.data(); return grd; } return 0; } void RasterCoverage::copyTo(IlwisObject *obj) { Locker lock(_mutex); Coverage::copyTo(obj); RasterCoverage *gc = static_cast<RasterCoverage *>(obj); gc->_georef = _georef; if ( _grid) { gc->_grid.reset(_grid->clone()); } } Resource RasterCoverage::resource(int mode) const { Resource res = Coverage::resource(mode); if ( mode & IlwisObject::cmEXTENDED) { res["georeference()"] = georeference()->id(); res.setExtendedType( res.extendedType() | itGEOREF); } return res; } Size RasterCoverage::size() const { if (_size.isValid() && !_size.isNull()) return _size; if (!_grid.isNull()) const_cast<RasterCoverage *>(this)->_size = _grid->size(); else if ( _georef.isValid()) const_cast<RasterCoverage *>(this)->_size = _georef->size(); return _size; } void RasterCoverage::unloadBinary() { if (!_grid == NULL) { return _grid->unload(); } } void RasterCoverage::size(const Size &sz) { // size must always be positive or undefined if (sz.xsize() > 0 && sz.ysize() > 0) { _size = sz; if (!_grid.isNull()) _grid->setSize(sz); if (_georef.isValid()) _georef->size(sz); } } <commit_msg>readability<commit_after>#include "kernel.h" #include "raster.h" #include "rastercoverage.h" #include "pixeliterator.h" #include "connectorinterface.h" #include "symboltable.h" #include "domainitem.h" #include "itemdomain.h" #include "numericitem.h" #include "numericitemrange.h" #include "ilwisoperation.h" quint64 Ilwis::GridBlockInternal::_blockid = 0; using namespace Ilwis; RasterCoverage::RasterCoverage() { } RasterCoverage::RasterCoverage(const Resource& res) : Coverage(res){ } RasterCoverage::~RasterCoverage() { } const IGeoReference& RasterCoverage::georeference() const { return _georef; } void RasterCoverage::georeference(const IGeoReference &grf) { _georef = grf; if ( _grid.isNull() == false) { // remove the current grid, all has become uncertain _grid.reset(0); } if ( _georef.isValid()) { _georef->compute(); setCoordinateSystem(grf->coordinateSystem()); // mandatory } } IlwisTypes RasterCoverage::ilwisType() const { return itRASTER; } RasterCoverage *RasterCoverage::copy() { RasterCoverage *gc = new RasterCoverage(); copyTo(gc); return gc; } void RasterCoverage::copyBinary(const IRasterCoverage& gc, int index) { IRasterCoverage gcNew; gcNew.set(this); Size inputSize = gc->size(); Size sz(inputSize.xsize(),inputSize.ysize(), 1); gcNew->georeference()->size(sz); PixelIterator iterIn(gc, Box3D<>(Voxel(0,0,index), Voxel(inputSize.xsize(), inputSize.ysize(), index + 1))); PixelIterator iterOut(gcNew, Box3D<>(Size(inputSize.xsize(), inputSize.ysize(), 1))); for_each(iterOut, iterOut.end(), [&](double& v){ v = *iterIn; ++iterIn; }); } //IRasterCoverage RasterCoverage::get(quint32 index1, quint32 index2) //{ // IRasterCoverage gcovParent; // gcovParent.set(this); // IRasterCoverage gcov = OperationHelperRaster::initialize(gcovParent,itRASTER, itDOMAIN | itCOORDSYSTEM | itGEOREF); // gcov->size(Size(size().xsize(), size().ysize())); // gcov->_grid.reset(gcov->_grid->clone(index1, index2)); // return gcov; //} Grid *RasterCoverage::grid() { Locker lock(_mutex); if ( _georef->isValid() && !connector().isNull()) { if ( _grid.isNull()) { _grid.reset(connector()->loadGridData(this)); if (_grid.isNull()) return 0; } Grid *grd = _grid.data(); return grd; } return 0; } void RasterCoverage::copyTo(IlwisObject *obj) { Locker lock(_mutex); Coverage::copyTo(obj); RasterCoverage *gc = static_cast<RasterCoverage *>(obj); gc->_georef = _georef; if ( _grid) { gc->_grid.reset(_grid->clone()); } } Resource RasterCoverage::resource(int mode) const { Resource res = Coverage::resource(mode); if ( mode & IlwisObject::cmEXTENDED) { res["georeference()"] = georeference()->id(); res.setExtendedType( res.extendedType() | itGEOREF); } return res; } Size RasterCoverage::size() const { if (_size.isValid() && !_size.isNull()) return _size; if (!_grid.isNull()) const_cast<RasterCoverage *>(this)->_size = _grid->size(); else if ( _georef.isValid()) const_cast<RasterCoverage *>(this)->_size = _georef->size(); return _size; } void RasterCoverage::unloadBinary() { if (_grid != 0) { return _grid->unload(); } } void RasterCoverage::size(const Size &sz) { // size must always be positive or undefined if (sz.xsize() > 0 && sz.ysize() > 0) { _size = sz; if (!_grid.isNull()) _grid->setSize(sz); if (_georef.isValid()) _georef->size(sz); } } <|endoftext|>
<commit_before>// // SRTerrain class : a subclass of vtDynTerrainGeom which encapsulates // Stefan Roettger's CLOD algorithm. // // utilizes: Roettger's MINI library implementation // http://wwwvis.informatik.uni-stuttgart.de/~roettger // // Copyright (c) 2002-2005 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "SRTerrain.h" #include "vtdata/vtLog.h" #if VTLIB_NI // stub SRTerrain::SRTerrain() {} SRTerrain::~SRTerrain() {} float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { return 0; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const {} void SRTerrain::DoCulling(const vtCamera *pCam) {} void SRTerrain::DoRender() {} void SRTerrain::SetVerticalExag(float fExag) {} DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { return DTErr_NOMEM; } #else #include "mini.h" #include "ministub.hpp" using namespace mini; #ifdef _MSC_VER #pragma comment( lib, "libMini.lib" ) #endif ///////////////////////////////////////////////////////////////////////////// // // Constructor/destructor // SRTerrain::SRTerrain() : vtDynTerrainGeom() { m_fResolution = 10000.0f; m_fHResolution = 20000.0f; m_fLResolution = 0.0f; m_pMini = NULL; } SRTerrain::~SRTerrain() { if (m_pMini) { delete m_pMini; m_pMini = NULL; } } ///////////////////////////////////////////////////////////////////////////// // // Unfortunately the following statics are required because libMini only // supports some functionality by callback, and the callback is only a // simple C function which has no context to tell us which terrain. // static const vtElevationGrid *s_pGrid; static SRTerrain *s_pSRTerrain; static int myfancnt, myvtxcnt; static int s_iRows; void beginfan_vtp() { if (myfancnt++>0) glEnd(); glBegin(GL_TRIANGLE_FAN); myvtxcnt-=2; // 2 vertices are needed to start each fan } void fanvertex_vtp(float x, float y, float z) { glVertex3f(x,y,z); myvtxcnt++; } void notify_vtp(int i, int j, int size) { // check to see if we need to switch texture if (s_pSRTerrain->m_iTPatchDim > 1 && size == s_pSRTerrain->m_iBlockSize) { int a = i / size; int b = j / size; s_pSRTerrain->LoadBlockMaterial(a, b); } } short int getelevation_vtp1(int i, int j, int size, void *data_unused) { return s_pGrid->GetValue(i, s_iRows-1-j); } float getelevation_vtp2(int i, int j, int size, void *data_unused) { return s_pGrid->GetFValue(i, s_iRows-1-j); } // // Initialize the terrain data // fZScale converts from height values (meters) to world coordinates // DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { // Initializes necessary field of the parent class DTErr err = BasicInit(pGrid); if (err != DTErr_OK) return err; if (m_iColumns != m_iRows) return DTErr_NOTSQUARE; // compute n (log2 of grid size) // ensure that the grid is size (1 << n) + 1 int n = vt_log2(m_iColumns - 1); int required_size = (1<<n) + 1; if (m_iColumns != required_size || m_iRows != required_size) return DTErr_NOTPOWER2; int size = m_iColumns; float dim = m_fXStep; float cellaspect = m_fZStep / m_fXStep; s_pGrid = pGrid; s_iRows = m_iRows; #if 0 // NOTE: the following workaround is no longer needed with libMini 5.02 // // Totally strange but repeatable behavior: runtime exit in Release-mode // libMini with values over a certain level. Workaround here! // Exit happens if (scale * maximum_height / dim > 967) // // scale * maximum_height / dim > 967 // scale > dim * 967 / maximum_height // float fMin, fMax; pGrid->GetHeightExtents(fMin, fMax); // Avoid trouble with fMax small or zero if (fMax < 10) fMax = 10; // compute the largest supported value for MaxScale float fMaxMax = dim * 960 / fMax; // values greater than 10 are unnecessarily large if (fMaxMax > 10) fMaxMax = 10; m_fMaximumScale = fMaxMax; #else // This maxiumum scale is a reasonable tradeoff between the exaggeration // that the user is likely to need, and numerical precision issues. m_fMaximumScale = 10; #endif m_fHeightScale = fZScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; if (pGrid->IsFloatMode()) { float *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, 0.0f, 0.0f, 0.0f, // grid center beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp2); } else { short *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, 0.0f, 0.0f, 0.0f, // grid center beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp1); } m_iDrawnTriangles = -1; m_iBlockSize = m_iColumns / 4; return DTErr_OK; } void SRTerrain::SetVerticalExag(float fExag) { m_fHeightScale = fExag; // safety check if (m_fHeightScale > m_fMaximumScale) m_fHeightScale = m_fMaximumScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; } // // This will be called once per frame, during the culling pass. // // However, libMini does not allow you to call the culling pass // independently of the rendering pass, so we cannot do culling here. // Instead, just store the values for later use. // void SRTerrain::DoCulling(const vtCamera *pCam) { // Grab necessary values from the VTP Scene framework, store for later m_eyepos_ogl = pCam->GetTrans(); m_window_size = vtGetScene()->GetWindowSize(); m_fAspect = (float)m_window_size.x / m_window_size.y; m_fNear = pCam->GetHither(); m_fFar = pCam->GetYon(); // Get up vector and direction vector from camera matrix FMatrix4 mat; pCam->GetTransform1(mat); FPoint3 up(0.0f, 1.0f, 0.0f); mat.TransformVector(up, eye_up); FPoint3 forward(0.0f, 0.0f, -1.0f); mat.TransformVector(forward, eye_forward); if (pCam->IsOrtho()) { // libMini supports orthographic viewing as of libMini 5.0. // A negative FOV value indicates to the library that the FOV is // actually the orthographic height of the camera. m_fFOVY = pCam->GetWidth() / m_fAspect; m_fFOVY = -m_fFOVY; } else { float fov = pCam->GetFOV(); float fov_y2 = atan(tan (fov/2) / m_fAspect); m_fFOVY = fov_y2 * 2.0f * 180 / PIf; } } void SRTerrain::DoRender() { // Prepare the render state for our OpenGL usage PreRender(); // Render the triangles RenderSurface(); // Clean up PostRender(); } void SRTerrain::LoadSingleMaterial() { // single texture for the whole terrain vtMaterial *pMat = GetMaterial(0); if (pMat) { pMat->Apply(); SetupTexGen(1.0f); } } void SRTerrain::LoadBlockMaterial(int a, int b) { // we can't change the texture between glBegin/glEnd if (myfancnt++>0) glEnd(); // each block has it's own texture map int matidx = a*m_iTPatchDim + (m_iTPatchDim-1-b); vtMaterial *pMat = GetMaterial(matidx); if (pMat) { pMat->Apply(); SetupBlockTexGen(a, b); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } glBegin(GL_TRIANGLE_FAN); } void SRTerrain::RenderSurface() { s_pSRTerrain = this; if (m_iTPatchDim == 1) LoadSingleMaterial(); RenderPass(); // how to do a second rendering pass if (m_bDetailTexture) { // once again, with the detail texture material m_pDetailMat->Apply(); // the uv tiling is different (usually highly repetitive) SetupTexGen(m_fDetailTiling); // draw the second pass glPolygonOffset(-1.0f, -1.0f); glEnable(GL_POLYGON_OFFSET_FILL); RenderPass(); glDisable(GL_POLYGON_OFFSET_FILL); } DisableTexGen(); } void SRTerrain::RenderPass() { float ex = m_eyepos_ogl.x; float ey = m_eyepos_ogl.y; float ez = m_eyepos_ogl.z; float fov = m_fFOVY; float ux = eye_up.x; float uy = eye_up.y; float uz = eye_up.z; float dx = eye_forward.x; float dy = eye_forward.y; float dz = eye_forward.z; myfancnt = myvtxcnt = 0; // Convert the eye location to the unusual coordinate scheme of libMini. ex -= (m_iColumns/2)*m_fXStep; ez += (m_iRows/2)*m_fZStep; m_pMini->draw(m_fResolution, ex, ey, ez, dx, dy, dz, ux, uy, uz, fov, m_fAspect, m_fNear, m_fFar, m_fDrawScale); if (myfancnt>0) glEnd(); // We are drawing fans, so the number of triangles is roughly equal to // number of vertices m_iDrawnTriangles = myvtxcnt; // adaptively adjust resolution threshold up or down to attain // the desired polygon (vertex) count target int diff = m_iDrawnTriangles - m_iPolygonTarget; int iRange = m_iPolygonTarget / 10; // ensure within 10% // If we aren't within the triangle count range adjust the input resolution // like a binary search if (diff < -iRange || diff > iRange) { // VTLOG("diff %d, ", diff); if (diff < -iRange) { m_fLResolution = m_fResolution; // if the high end isn't high enough, double it if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("increase HRes, "); m_fHResolution *= 10; } } else { m_fHResolution = m_fResolution; if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("decrease LRes, "); m_fLResolution = 0; } } m_fResolution = m_fLResolution + (m_fHResolution - m_fLResolution) / 2; // VTLOG("rez: [%.1f, %.1f, %.1f] (%d/%d)\n", m_fLResolution, m_fResolution, m_fHResolution, m_iDrawnTriangles, m_iPolygonTarget); // keep the error within reasonable bounds if (m_fResolution < 5.0f) m_fResolution = 5.0f; if (m_fResolution > 4E7) m_fResolution = 4E7; } } // // These methods are called when the framework needs to know the surface // position of the terrain at a given grid point. Supply the height // value from our own data structures. // float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { float height = m_pMini->getheight(iX, iZ); if (iX<0 || iX>m_iColumns-1 || iZ<0 || iZ>m_iRows-1) return 0.0f; if (bTrue) // convert stored value to true value return height / m_fMaximumScale; else // convert stored value to drawn value return height * m_fDrawScale; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const { float height = m_pMini->getheight(i, j); if (bTrue) // convert stored value to true value height /= m_fMaximumScale; else // convert stored value to drawn value height *= m_fDrawScale; p.Set(m_fXLookup[i], height, m_fZLookup[j]); } void SRTerrain::SetPolygonCount(int iPolygonCount) { vtDynTerrainGeom::SetPolygonCount(iPolygonCount); m_fResolution = iPolygonCount * 5; m_fHResolution = 2 * m_fResolution; m_fLResolution = 0; } #endif // VTLIB_NI <commit_msg>optional linking with libMinid.lib for core development<commit_after>// // SRTerrain class : a subclass of vtDynTerrainGeom which encapsulates // Stefan Roettger's CLOD algorithm. // // utilizes: Roettger's MINI library implementation // http://wwwvis.informatik.uni-stuttgart.de/~roettger // // Copyright (c) 2002-2005 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "SRTerrain.h" #include "vtdata/vtLog.h" #if VTLIB_NI // stub SRTerrain::SRTerrain() {} SRTerrain::~SRTerrain() {} float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { return 0; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const {} void SRTerrain::DoCulling(const vtCamera *pCam) {} void SRTerrain::DoRender() {} void SRTerrain::SetVerticalExag(float fExag) {} DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { return DTErr_NOMEM; } #else #include "mini.h" #include "ministub.hpp" using namespace mini; #ifdef _MSC_VER // Set the following "1" to "0" before each code release, because non-core // developers don't need to debug into the libMini library, so they won't // need the *d version. #if _DEBUG && 0 #pragma message( "Adding link with libMinid.lib" ) #pragma comment( lib, "libMinid.lib" ) #else #pragma message( "Adding link with libMini.lib" ) #pragma comment( lib, "libMini.lib" ) #endif #endif ///////////////////////////////////////////////////////////////////////////// // // Constructor/destructor // SRTerrain::SRTerrain() : vtDynTerrainGeom() { m_fResolution = 10000.0f; m_fHResolution = 20000.0f; m_fLResolution = 0.0f; m_pMini = NULL; } SRTerrain::~SRTerrain() { if (m_pMini) { delete m_pMini; m_pMini = NULL; } } ///////////////////////////////////////////////////////////////////////////// // // Unfortunately the following statics are required because libMini only // supports some functionality by callback, and the callback is only a // simple C function which has no context to tell us which terrain. // static const vtElevationGrid *s_pGrid; static SRTerrain *s_pSRTerrain; static int myfancnt, myvtxcnt; static int s_iRows; void beginfan_vtp() { if (myfancnt++>0) glEnd(); glBegin(GL_TRIANGLE_FAN); myvtxcnt-=2; // 2 vertices are needed to start each fan } void fanvertex_vtp(float x, float y, float z) { glVertex3f(x,y,z); myvtxcnt++; } void notify_vtp(int i, int j, int size) { // check to see if we need to switch texture if (s_pSRTerrain->m_iTPatchDim > 1 && size == s_pSRTerrain->m_iBlockSize) { int a = i / size; int b = j / size; s_pSRTerrain->LoadBlockMaterial(a, b); } } short int getelevation_vtp1(int i, int j, int size, void *data_unused) { return s_pGrid->GetValue(i, s_iRows-1-j); } float getelevation_vtp2(int i, int j, int size, void *data_unused) { return s_pGrid->GetFValue(i, s_iRows-1-j); } // // Initialize the terrain data // fZScale converts from height values (meters) to world coordinates // DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { // Initializes necessary field of the parent class DTErr err = BasicInit(pGrid); if (err != DTErr_OK) return err; if (m_iColumns != m_iRows) return DTErr_NOTSQUARE; // compute n (log2 of grid size) // ensure that the grid is size (1 << n) + 1 int n = vt_log2(m_iColumns - 1); int required_size = (1<<n) + 1; if (m_iColumns != required_size || m_iRows != required_size) return DTErr_NOTPOWER2; int size = m_iColumns; float dim = m_fXStep; float cellaspect = m_fZStep / m_fXStep; s_pGrid = pGrid; s_iRows = m_iRows; #if 0 // NOTE: the following workaround is no longer needed with libMini 5.02 // // Totally strange but repeatable behavior: runtime exit in Release-mode // libMini with values over a certain level. Workaround here! // Exit happens if (scale * maximum_height / dim > 967) // // scale * maximum_height / dim > 967 // scale > dim * 967 / maximum_height // float fMin, fMax; pGrid->GetHeightExtents(fMin, fMax); // Avoid trouble with fMax small or zero if (fMax < 10) fMax = 10; // compute the largest supported value for MaxScale float fMaxMax = dim * 960 / fMax; // values greater than 10 are unnecessarily large if (fMaxMax > 10) fMaxMax = 10; m_fMaximumScale = fMaxMax; #else // This maxiumum scale is a reasonable tradeoff between the exaggeration // that the user is likely to need, and numerical precision issues. m_fMaximumScale = 10; #endif m_fHeightScale = fZScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; if (pGrid->IsFloatMode()) { float *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, 0.0f, 0.0f, 0.0f, // grid center beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp2); } else { short *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, 0.0f, 0.0f, 0.0f, // grid center beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp1); } m_iDrawnTriangles = -1; m_iBlockSize = m_iColumns / 4; return DTErr_OK; } void SRTerrain::SetVerticalExag(float fExag) { m_fHeightScale = fExag; // safety check if (m_fHeightScale > m_fMaximumScale) m_fHeightScale = m_fMaximumScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; } // // This will be called once per frame, during the culling pass. // // However, libMini does not allow you to call the culling pass // independently of the rendering pass, so we cannot do culling here. // Instead, just store the values for later use. // void SRTerrain::DoCulling(const vtCamera *pCam) { // Grab necessary values from the VTP Scene framework, store for later m_eyepos_ogl = pCam->GetTrans(); m_window_size = vtGetScene()->GetWindowSize(); m_fAspect = (float)m_window_size.x / m_window_size.y; m_fNear = pCam->GetHither(); m_fFar = pCam->GetYon(); // Get up vector and direction vector from camera matrix FMatrix4 mat; pCam->GetTransform1(mat); FPoint3 up(0.0f, 1.0f, 0.0f); mat.TransformVector(up, eye_up); FPoint3 forward(0.0f, 0.0f, -1.0f); mat.TransformVector(forward, eye_forward); if (pCam->IsOrtho()) { // libMini supports orthographic viewing as of libMini 5.0. // A negative FOV value indicates to the library that the FOV is // actually the orthographic height of the camera. m_fFOVY = pCam->GetWidth() / m_fAspect; m_fFOVY = -m_fFOVY; } else { float fov = pCam->GetFOV(); float fov_y2 = atan(tan (fov/2) / m_fAspect); m_fFOVY = fov_y2 * 2.0f * 180 / PIf; } } void SRTerrain::DoRender() { // Prepare the render state for our OpenGL usage PreRender(); // Render the triangles RenderSurface(); // Clean up PostRender(); } void SRTerrain::LoadSingleMaterial() { // single texture for the whole terrain vtMaterial *pMat = GetMaterial(0); if (pMat) { pMat->Apply(); SetupTexGen(1.0f); } } void SRTerrain::LoadBlockMaterial(int a, int b) { // we can't change the texture between glBegin/glEnd if (myfancnt++>0) glEnd(); // each block has it's own texture map int matidx = a*m_iTPatchDim + (m_iTPatchDim-1-b); vtMaterial *pMat = GetMaterial(matidx); if (pMat) { pMat->Apply(); SetupBlockTexGen(a, b); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } glBegin(GL_TRIANGLE_FAN); } void SRTerrain::RenderSurface() { s_pSRTerrain = this; if (m_iTPatchDim == 1) LoadSingleMaterial(); RenderPass(); // how to do a second rendering pass if (m_bDetailTexture) { // once again, with the detail texture material m_pDetailMat->Apply(); // the uv tiling is different (usually highly repetitive) SetupTexGen(m_fDetailTiling); // draw the second pass glPolygonOffset(-1.0f, -1.0f); glEnable(GL_POLYGON_OFFSET_FILL); RenderPass(); glDisable(GL_POLYGON_OFFSET_FILL); } DisableTexGen(); } void SRTerrain::RenderPass() { float ex = m_eyepos_ogl.x; float ey = m_eyepos_ogl.y; float ez = m_eyepos_ogl.z; float fov = m_fFOVY; float ux = eye_up.x; float uy = eye_up.y; float uz = eye_up.z; float dx = eye_forward.x; float dy = eye_forward.y; float dz = eye_forward.z; myfancnt = myvtxcnt = 0; // Convert the eye location to the unusual coordinate scheme of libMini. ex -= (m_iColumns/2)*m_fXStep; ez += (m_iRows/2)*m_fZStep; m_pMini->draw(m_fResolution, ex, ey, ez, dx, dy, dz, ux, uy, uz, fov, m_fAspect, m_fNear, m_fFar, m_fDrawScale); if (myfancnt>0) glEnd(); // We are drawing fans, so the number of triangles is roughly equal to // number of vertices m_iDrawnTriangles = myvtxcnt; // adaptively adjust resolution threshold up or down to attain // the desired polygon (vertex) count target int diff = m_iDrawnTriangles - m_iPolygonTarget; int iRange = m_iPolygonTarget / 10; // ensure within 10% // If we aren't within the triangle count range adjust the input resolution // like a binary search if (diff < -iRange || diff > iRange) { // VTLOG("diff %d, ", diff); if (diff < -iRange) { m_fLResolution = m_fResolution; // if the high end isn't high enough, double it if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("increase HRes, "); m_fHResolution *= 10; } } else { m_fHResolution = m_fResolution; if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("decrease LRes, "); m_fLResolution = 0; } } m_fResolution = m_fLResolution + (m_fHResolution - m_fLResolution) / 2; // VTLOG("rez: [%.1f, %.1f, %.1f] (%d/%d)\n", m_fLResolution, m_fResolution, m_fHResolution, m_iDrawnTriangles, m_iPolygonTarget); // keep the error within reasonable bounds if (m_fResolution < 5.0f) m_fResolution = 5.0f; if (m_fResolution > 4E7) m_fResolution = 4E7; } } // // These methods are called when the framework needs to know the surface // position of the terrain at a given grid point. Supply the height // value from our own data structures. // float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { float height = m_pMini->getheight(iX, iZ); if (iX<0 || iX>m_iColumns-1 || iZ<0 || iZ>m_iRows-1) return 0.0f; if (bTrue) // convert stored value to true value return height / m_fMaximumScale; else // convert stored value to drawn value return height * m_fDrawScale; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const { float height = m_pMini->getheight(i, j); if (bTrue) // convert stored value to true value height /= m_fMaximumScale; else // convert stored value to drawn value height *= m_fDrawScale; p.Set(m_fXLookup[i], height, m_fZLookup[j]); } void SRTerrain::SetPolygonCount(int iPolygonCount) { vtDynTerrainGeom::SetPolygonCount(iPolygonCount); m_fResolution = iPolygonCount * 5; m_fHResolution = 2 * m_fResolution; m_fLResolution = 0; } #endif // VTLIB_NI <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "acpica.hpp" #include "acpi.hpp" #include "kernel_utils.hpp" #include "timer.hpp" #include "paging.hpp" #include "console.hpp" #include "logging.hpp" #include "scheduler.hpp" #include "arch.hpp" namespace { // This is copied from acexcep.h // This could be used with ACPI_DEFINE_EXCEPTION_TABLE but this // generates too many warnings and errors static const ACPI_EXCEPTION_INFO AcpiGbl_ExceptionNames_Env[] = { EXCEP_TXT ("AE_OK", "No error"), EXCEP_TXT ("AE_ERROR", "Unspecified error"), EXCEP_TXT ("AE_NO_ACPI_TABLES", "ACPI tables could not be found"), EXCEP_TXT ("AE_NO_NAMESPACE", "A namespace has not been loaded"), EXCEP_TXT ("AE_NO_MEMORY", "Insufficient dynamic memory"), EXCEP_TXT ("AE_NOT_FOUND", "A requested entity is not found"), EXCEP_TXT ("AE_NOT_EXIST", "A required entity does not exist"), EXCEP_TXT ("AE_ALREADY_EXISTS", "An entity already exists"), EXCEP_TXT ("AE_TYPE", "The object type is incorrect"), EXCEP_TXT ("AE_NULL_OBJECT", "A required object was missing"), EXCEP_TXT ("AE_NULL_ENTRY", "The requested object does not exist"), EXCEP_TXT ("AE_BUFFER_OVERFLOW", "The buffer provided is too small"), EXCEP_TXT ("AE_STACK_OVERFLOW", "An internal stack overflowed"), EXCEP_TXT ("AE_STACK_UNDERFLOW", "An internal stack underflowed"), EXCEP_TXT ("AE_NOT_IMPLEMENTED", "The feature is not implemented"), EXCEP_TXT ("AE_SUPPORT", "The feature is not supported"), EXCEP_TXT ("AE_LIMIT", "A predefined limit was exceeded"), EXCEP_TXT ("AE_TIME", "A time limit or timeout expired"), EXCEP_TXT ("AE_ACQUIRE_DEADLOCK", "Internal error, attempt was made to acquire a mutex in improper order"), EXCEP_TXT ("AE_RELEASE_DEADLOCK", "Internal error, attempt was made to release a mutex in improper order"), EXCEP_TXT ("AE_NOT_ACQUIRED", "An attempt to release a mutex or Global Lock without a previous acquire"), EXCEP_TXT ("AE_ALREADY_ACQUIRED", "Internal error, attempt was made to acquire a mutex twice"), EXCEP_TXT ("AE_NO_HARDWARE_RESPONSE", "Hardware did not respond after an I/O operation"), EXCEP_TXT ("AE_NO_GLOBAL_LOCK", "There is no FACS Global Lock"), EXCEP_TXT ("AE_ABORT_METHOD", "A control method was aborted"), EXCEP_TXT ("AE_SAME_HANDLER", "Attempt was made to install the same handler that is already installed"), EXCEP_TXT ("AE_NO_HANDLER", "A handler for the operation is not installed"), EXCEP_TXT ("AE_OWNER_ID_LIMIT", "There are no more Owner IDs available for ACPI tables or control methods"), EXCEP_TXT ("AE_NOT_CONFIGURED", "The interface is not part of the current subsystem configuration"), EXCEP_TXT ("AE_ACCESS", "Permission denied for the requested operation"), EXCEP_TXT ("AE_IO_ERROR", "An I/O error occurred") }; volatile bool acpi_initialized = false; void initialize_acpica(){ logging::logf(logging::log_level::DEBUG, "acpi:: Started initialization of ACPICA\n"); /* Initialize the ACPICA subsystem */ auto status = AcpiInitializeSubsystem(); if(ACPI_FAILURE(status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to initialize subsystem: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Initialize the ACPICA Table Manager and get all ACPI tables */ status = AcpiInitializeTables(nullptr, 16, FALSE); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to initialize tables: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Create the ACPI namespace from ACPI tables */ status = AcpiLoadTables (); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to load tables: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Initialize the ACPI hardware */ status = AcpiEnableSubsystem (ACPI_FULL_INITIALIZATION); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to enable subsystem: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Complete the ACPI namespace object initialization */ status = AcpiInitializeObjects (ACPI_FULL_INITIALIZATION); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to initialize objects: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } acpi_initialized = true; logging::logf(logging::log_level::DEBUG, "acpi:: Finished initialization of ACPICA\n"); } } //end of anonymous namespace void acpi::init(){ // ACPICA needs scheduling to be started scheduler::queue_async_init_task(initialize_acpica); } void acpi::shutdown(){ auto status = AcpiEnterSleepStatePrep(5); if(ACPI_FAILURE(status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to prepare sleep state: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } size_t rflags; arch::disable_hwint(rflags); status = AcpiEnterSleepState(5); if(ACPI_FAILURE(status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to enter sleep state: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } k_print_line("acpi poweroff failed."); arch::enable_hwint(rflags); } bool acpi::initialized(){ return acpi_initialized; } <commit_msg>Allow resizing of ACPI tables<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "acpica.hpp" #include "acpi.hpp" #include "kernel_utils.hpp" #include "timer.hpp" #include "paging.hpp" #include "console.hpp" #include "logging.hpp" #include "scheduler.hpp" #include "arch.hpp" namespace { // This is copied from acexcep.h // This could be used with ACPI_DEFINE_EXCEPTION_TABLE but this // generates too many warnings and errors static const ACPI_EXCEPTION_INFO AcpiGbl_ExceptionNames_Env[] = { EXCEP_TXT ("AE_OK", "No error"), EXCEP_TXT ("AE_ERROR", "Unspecified error"), EXCEP_TXT ("AE_NO_ACPI_TABLES", "ACPI tables could not be found"), EXCEP_TXT ("AE_NO_NAMESPACE", "A namespace has not been loaded"), EXCEP_TXT ("AE_NO_MEMORY", "Insufficient dynamic memory"), EXCEP_TXT ("AE_NOT_FOUND", "A requested entity is not found"), EXCEP_TXT ("AE_NOT_EXIST", "A required entity does not exist"), EXCEP_TXT ("AE_ALREADY_EXISTS", "An entity already exists"), EXCEP_TXT ("AE_TYPE", "The object type is incorrect"), EXCEP_TXT ("AE_NULL_OBJECT", "A required object was missing"), EXCEP_TXT ("AE_NULL_ENTRY", "The requested object does not exist"), EXCEP_TXT ("AE_BUFFER_OVERFLOW", "The buffer provided is too small"), EXCEP_TXT ("AE_STACK_OVERFLOW", "An internal stack overflowed"), EXCEP_TXT ("AE_STACK_UNDERFLOW", "An internal stack underflowed"), EXCEP_TXT ("AE_NOT_IMPLEMENTED", "The feature is not implemented"), EXCEP_TXT ("AE_SUPPORT", "The feature is not supported"), EXCEP_TXT ("AE_LIMIT", "A predefined limit was exceeded"), EXCEP_TXT ("AE_TIME", "A time limit or timeout expired"), EXCEP_TXT ("AE_ACQUIRE_DEADLOCK", "Internal error, attempt was made to acquire a mutex in improper order"), EXCEP_TXT ("AE_RELEASE_DEADLOCK", "Internal error, attempt was made to release a mutex in improper order"), EXCEP_TXT ("AE_NOT_ACQUIRED", "An attempt to release a mutex or Global Lock without a previous acquire"), EXCEP_TXT ("AE_ALREADY_ACQUIRED", "Internal error, attempt was made to acquire a mutex twice"), EXCEP_TXT ("AE_NO_HARDWARE_RESPONSE", "Hardware did not respond after an I/O operation"), EXCEP_TXT ("AE_NO_GLOBAL_LOCK", "There is no FACS Global Lock"), EXCEP_TXT ("AE_ABORT_METHOD", "A control method was aborted"), EXCEP_TXT ("AE_SAME_HANDLER", "Attempt was made to install the same handler that is already installed"), EXCEP_TXT ("AE_NO_HANDLER", "A handler for the operation is not installed"), EXCEP_TXT ("AE_OWNER_ID_LIMIT", "There are no more Owner IDs available for ACPI tables or control methods"), EXCEP_TXT ("AE_NOT_CONFIGURED", "The interface is not part of the current subsystem configuration"), EXCEP_TXT ("AE_ACCESS", "Permission denied for the requested operation"), EXCEP_TXT ("AE_IO_ERROR", "An I/O error occurred") }; volatile bool acpi_initialized = false; void initialize_acpica(){ logging::logf(logging::log_level::DEBUG, "acpi:: Started initialization of ACPICA\n"); /* Initialize the ACPICA subsystem */ auto status = AcpiInitializeSubsystem(); if(ACPI_FAILURE(status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to initialize subsystem: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Initialize the ACPICA Table Manager and get all ACPI tables */ status = AcpiInitializeTables(nullptr, 16, true); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to initialize tables: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Create the ACPI namespace from ACPI tables */ status = AcpiLoadTables (); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to load tables: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Initialize the ACPI hardware */ status = AcpiEnableSubsystem (ACPI_FULL_INITIALIZATION); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to enable subsystem: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } /* Complete the ACPI namespace object initialization */ status = AcpiInitializeObjects (ACPI_FULL_INITIALIZATION); if (ACPI_FAILURE (status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to initialize objects: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } acpi_initialized = true; logging::logf(logging::log_level::DEBUG, "acpi:: Finished initialization of ACPICA\n"); } } //end of anonymous namespace void acpi::init(){ // ACPICA needs scheduling to be started scheduler::queue_async_init_task(initialize_acpica); } void acpi::shutdown(){ auto status = AcpiEnterSleepStatePrep(5); if(ACPI_FAILURE(status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to prepare sleep state: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } size_t rflags; arch::disable_hwint(rflags); status = AcpiEnterSleepState(5); if(ACPI_FAILURE(status)){ logging::logf(logging::log_level::ERROR, "acpica: Impossible to enter sleep state: error: %s\n", AcpiGbl_ExceptionNames_Env[status].Name); return; } k_print_line("acpi poweroff failed."); arch::enable_hwint(rflags); } bool acpi::initialized(){ return acpi_initialized; } <|endoftext|>
<commit_before>/* Copyright 2019 Andrei Khodko * * 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 "utilities.h" #include "QsLog.h" QImage Utilities::imageFromBytes(const QVector<int32_t> &array, int width, int height, const QString &format){ auto fmt = QImage::Format_RGB32; auto *rawData = static_cast<const uchar *>(static_cast<const void *>(array.data())); // Reserve maximum possible size to avoid reallocation auto formattedData = new uchar[(width + 3) * (height + 3) * 3 + 3]; static auto cleanUp = [](void *p) { if (p) delete [](static_cast<decltype (formattedData)>(p)); }; void *cleanUpInfo = nullptr; // QImage requires 32-bit aligned scan lines // Helper function to convert data auto copyAligned = [&](int perLine){ auto scanLineSize = static_cast<int>((static_cast<unsigned>(perLine + 3)) & 0xFFFFFFFC); auto dst = formattedData; for (auto src = array.begin(); src < array.end(); src += perLine) { dst = std::copy(src, src + perLine, dst); dst += scanLineSize - perLine; } rawData = formattedData; cleanUpInfo = formattedData; }; if (!format.compare("rgb32", Qt::CaseInsensitive)) { /* do nothing */ } else if (!format.compare("rgb888", Qt::CaseInsensitive)) { fmt = QImage::Format_RGB888; copyAligned(3 * width); } else if (format == "grayscale8") { fmt = QImage::Format_Grayscale8; copyAligned(width); } else { QLOG_ERROR() << "Unsupported format " << format; return QImage(); } return QImage(rawData, width, height, fmt, cleanUp, cleanUpInfo); } <commit_msg>Fix showing uninialized data from failed getPhoto()<commit_after>/* Copyright 2019 Andrei Khodko * * 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 "utilities.h" #include "QsLog.h" QImage Utilities::imageFromBytes(const QVector<int32_t> &array, int width, int height, const QString &format){ if (array.empty()) { return QImage(); } auto fmt = QImage::Format_RGB32; auto *rawData = static_cast<const uchar *>(static_cast<const void *>(array.data())); // Reserve maximum possible size to avoid reallocation auto formattedData = new uchar[(width + 3) * (height + 3) * 3 + 3]; static auto cleanUp = [](void *p) { if (p) delete [](static_cast<decltype (formattedData)>(p)); }; void *cleanUpInfo = nullptr; // QImage requires 32-bit aligned scan lines // Helper function to convert data auto copyAligned = [&](int perLine){ auto scanLineSize = static_cast<int>((static_cast<unsigned>(perLine + 3)) & 0xFFFFFFFC); auto dst = formattedData; for (auto src = array.begin(); src < array.end(); src += perLine) { dst = std::copy(src, src + perLine, dst); dst += scanLineSize - perLine; } rawData = formattedData; cleanUpInfo = formattedData; }; if (!format.compare("rgb32", Qt::CaseInsensitive)) { /* do nothing */ } else if (!format.compare("rgb888", Qt::CaseInsensitive)) { fmt = QImage::Format_RGB888; copyAligned(3 * width); } else if (format == "grayscale8") { fmt = QImage::Format_Grayscale8; copyAligned(width); } else { QLOG_ERROR() << "Unsupported format " << format; return QImage(); } return QImage(rawData, width, height, fmt, cleanUp, cleanUpInfo); } <|endoftext|>
<commit_before>/* Arduino.cpp - Mocks for common Arduino APIs Copyright © 2016 Ivan Grokhotkov 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. */ #include <sys/time.h> #include "Arduino.h" #include <unistd.h> extern "C" unsigned long millis() { timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000) + (time.tv_usec / 1000); } extern "C" unsigned long micros() { timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000000) + time.tv_usec; } extern "C" void yield() { } extern "C" bool can_yield() { return true; } extern "C" void optimistic_yield (uint32_t interval_us) { usleep(interval_us); } extern "C" void esp_yield() { } extern "C" void __panic_func(const char* file, int line, const char* func) { (void)file; (void)line; (void)func; abort(); } extern "C" void delay(unsigned long ms) { usleep(ms * 1000); } extern "C" void delayMicroseconds(unsigned int us) { usleep(us); } #include "cont.h" cont_t* g_pcont = NULL; extern "C" void cont_yield(cont_t*) { } <commit_msg>host build: optimistic_yield() wrongly delays() instead of avoiding excessive yields (#6802)<commit_after>/* Arduino.cpp - Mocks for common Arduino APIs Copyright © 2016 Ivan Grokhotkov 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. */ #include <sys/time.h> #include "Arduino.h" #include <unistd.h> extern "C" unsigned long millis() { timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000) + (time.tv_usec / 1000); } extern "C" unsigned long micros() { timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000000) + time.tv_usec; } extern "C" void yield() { } extern "C" bool can_yield() { return true; } extern "C" void optimistic_yield (uint32_t interval_us) { (void)interval_us; } extern "C" void esp_yield() { } extern "C" void __panic_func(const char* file, int line, const char* func) { (void)file; (void)line; (void)func; abort(); } extern "C" void delay(unsigned long ms) { usleep(ms * 1000); } extern "C" void delayMicroseconds(unsigned int us) { usleep(us); } #include "cont.h" cont_t* g_pcont = NULL; extern "C" void cont_yield(cont_t*) { } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file KeyWords.cxx ** Colourise for particular languages. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" LexerModule *LexerModule::base = 0; int LexerModule::nextLanguage = SCLEX_AUTOMATIC+1; LexerModule::LexerModule(int language_, LexerFunction fnLexer_, const char *languageName_, LexerFunction fnFolder_) : language(language_), languageName(languageName_), fnLexer(fnLexer_), fnFolder(fnFolder_) { next = base; base = this; if (language == SCLEX_AUTOMATIC) { language = nextLanguage; nextLanguage++; } } LexerModule *LexerModule::Find(int language) { LexerModule *lm = base; while (lm) { if (lm->language == language) { return lm; } lm = lm->next; } return 0; } LexerModule *LexerModule::Find(const char *languageName) { if (languageName) { LexerModule *lm = base; while (lm) { if (lm->languageName && 0 == strcmp(lm->languageName, languageName)) { return lm; } lm = lm->next; } } return 0; } void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) { if (fnLexer) fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler); } void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) { if (fnFolder) { int lineCurrent = styler.GetLine(startPos); // Move back one line in case deletion wrecked current line fold state if (lineCurrent > 0) { lineCurrent--; int newStartPos = styler.LineStart(lineCurrent); lengthDoc += startPos - newStartPos; startPos = newStartPos; initStyle = 0; if (startPos > 0) { initStyle = styler.StyleAt(startPos - 1); } } fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler); } } static void ColouriseNullDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { // Null language means all style bytes are 0 so just mark the end - no need to fill in. if (length > 0) { styler.StartAt(startPos + length - 1); styler.StartSegment(startPos + length - 1); styler.ColourTo(startPos + length - 1, 0); } } LexerModule lmNull(SCLEX_NULL, ColouriseNullDoc, "null"); #ifdef __vms // The following code forces a reference to all of the Scintilla lexers. // If we don't do something like this, then the linker tends to "optimize" // them away. (eric@sourcegear.com) // Taken from wxWindow's stc.cpp. Walter. int wxForceScintillaLexers(void) { extern LexerModule lmAda; extern LexerModule lmAVE; extern LexerModule lmBaan; extern LexerModule lmBatch; extern LexerModule lmConf; extern LexerModule lmCPP; extern LexerModule lmDiff; extern LexerModule lmEiffel; extern LexerModule lmEiffelkw; extern LexerModule lmErrorList; extern LexerModule lmHTML; extern LexerModule lmLatex; extern LexerModule lmLISP; extern LexerModule lmLua; extern LexerModule lmMake; extern LexerModule lmPascal; extern LexerModule lmPerl; extern LexerModule lmProps; extern LexerModule lmPython; extern LexerModule lmRuby; extern LexerModule lmSQL; extern LexerModule lmVB; extern LexerModule lmXML; extern LexerModule lmBullant; if ( &lmAda && &lmAVE && &lmBaan && &lmConf && &lmDiff && &lmLatex && &lmPascal && &lmCPP && &lmHTML && &lmXML && &lmProps && &lmErrorList && &lmMake && &lmBatch && &lmPerl && &lmPython && &lmSQL && &lmVB && &lmRuby && &lmEiffel && &lmEiffelkw && &lmLISP && &lmLua && &lmNull && &lmBullant ) { return 1; } else { return 0; } } #endif <commit_msg>Changed preprocessor switch for compiling in lexer linking code to be LINK_LEXERS and if __vms is defined then LINK_LEXERS is defined. Scintilla_LinkLexers is a new name for wxForceScintillaLexers although the old name is still available.<commit_after>// Scintilla source code edit control /** @file KeyWords.cxx ** Colourise for particular languages. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" LexerModule *LexerModule::base = 0; int LexerModule::nextLanguage = SCLEX_AUTOMATIC+1; LexerModule::LexerModule(int language_, LexerFunction fnLexer_, const char *languageName_, LexerFunction fnFolder_) : language(language_), languageName(languageName_), fnLexer(fnLexer_), fnFolder(fnFolder_) { next = base; base = this; if (language == SCLEX_AUTOMATIC) { language = nextLanguage; nextLanguage++; } } LexerModule *LexerModule::Find(int language) { LexerModule *lm = base; while (lm) { if (lm->language == language) { return lm; } lm = lm->next; } return 0; } LexerModule *LexerModule::Find(const char *languageName) { if (languageName) { LexerModule *lm = base; while (lm) { if (lm->languageName && 0 == strcmp(lm->languageName, languageName)) { return lm; } lm = lm->next; } } return 0; } void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) { if (fnLexer) fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler); } void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) { if (fnFolder) { int lineCurrent = styler.GetLine(startPos); // Move back one line in case deletion wrecked current line fold state if (lineCurrent > 0) { lineCurrent--; int newStartPos = styler.LineStart(lineCurrent); lengthDoc += startPos - newStartPos; startPos = newStartPos; initStyle = 0; if (startPos > 0) { initStyle = styler.StyleAt(startPos - 1); } } fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler); } } static void ColouriseNullDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { // Null language means all style bytes are 0 so just mark the end - no need to fill in. if (length > 0) { styler.StartAt(startPos + length - 1); styler.StartSegment(startPos + length - 1); styler.ColourTo(startPos + length - 1, 0); } } LexerModule lmNull(SCLEX_NULL, ColouriseNullDoc, "null"); #ifdef __vms #define LINK_LEXERS #endif #ifdef LINK_LEXERS // The following code forces a reference to all of the Scintilla lexers. // If we don't do something like this, then the linker tends to "optimize" // them away. (eric@sourcegear.com) // Taken from wxWindow's stc.cpp. Walter. int wxForceScintillaLexers(void) { Scintilla_LinkLexers(); } int Scintilla_LinkLexers() { extern LexerModule lmAda; extern LexerModule lmAVE; extern LexerModule lmBaan; extern LexerModule lmBatch; extern LexerModule lmConf; extern LexerModule lmCPP; extern LexerModule lmDiff; extern LexerModule lmEiffel; extern LexerModule lmEiffelkw; extern LexerModule lmErrorList; extern LexerModule lmHTML; extern LexerModule lmLatex; extern LexerModule lmLISP; extern LexerModule lmLua; extern LexerModule lmMake; extern LexerModule lmPascal; extern LexerModule lmPerl; extern LexerModule lmProps; extern LexerModule lmPython; extern LexerModule lmRuby; extern LexerModule lmSQL; extern LexerModule lmVB; extern LexerModule lmXML; extern LexerModule lmBullant; if ( &lmAda && &lmAVE && &lmBaan && &lmConf && &lmDiff && &lmLatex && &lmPascal && &lmCPP && &lmHTML && &lmXML && &lmProps && &lmErrorList && &lmMake && &lmBatch && &lmPerl && &lmPython && &lmSQL && &lmVB && &lmRuby && &lmEiffel && &lmEiffelkw && &lmLISP && &lmLua && &lmNull && &lmBullant ) { return 1; } else { return 0; } } #endif <|endoftext|>
<commit_before>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void exTestFixture::setUp() { m_File = new exFile("test.h"); m_FileName = new exFileName("test.h"); m_FileNameStatistics = new exFileNameStatistics("test.h"); m_Lexer = new exLexer(); m_RCS = new exRCS(); m_Stat = new exStat("test.h"); m_Statistics = new exStatistics<long>(); m_Tool = new exTool(ID_TOOL_REPORT_COUNT); } void exTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void exTestFixture::testMethods() { // test exFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() == "test.h"); // test exFileName CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); // test exLexer m_Lexer->SetLexerFromText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers // test exRCS CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test exStat CPPUNIT_ASSERT(m_Stat->IsOk()); // test exStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); // test exTool CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0); } void exTestFixture::testTiming() { exFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { wxString* buffer = file.Read(); CPPUNIT_ASSERT(buffer ! NULL); delete buffer; } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "exFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void exTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const exFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void exTestFixture::tearDown() { } void exAppTestFixture::setUp() { } void exAppTestFixture::testConstructors() { m_App = new exApp(); m_Dir = new exDir("./"); m_SVN = new exSVN(SVN_STAT, "test.h"); } void exAppTestFixture::testMethods() { // test exApp m_App->OnInit(); CPPUNIT_ASSERT(m_App->GetConfig() != NULL); CPPUNIT_ASSERT(m_App->GetLexers() != NULL); CPPUNIT_ASSERT(m_App->GetPrinter() != NULL); // test exDir CPPUNIT_ASSERT(m_Dir->GetFiles().GetCount() > 0); // test exSVN m_SVN->Get(); } void exAppTestFixture::testTimingConfig() { } void exAppTestFixture::tearDown() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { exApp::GetConfig("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { exApp::GetConfig()->Read("test", 0l); } const long config = sw.Time(); printf( "exConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } } exTestSuite::exTestSuite() : CppUnit::TestSuite("wxextension test suite") { // Add the tests. addTest(new CppUnit::TestCaller<exTestFixture>( "testConstructors", &exTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exTestFixture>( "testMethods", &exTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTiming", &exTestFixture::testTiming)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingAttrib", &exTestFixture::testTimingAttrib)); /* TODO: the exApp or wxApp not yet okay without normal wxApp initialization addTest(new CppUnit::TestCaller<exAppTestFixture>( "testConstructors", &exAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testMethods", &exAppTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testTimingConfig", &exAppTestFixture::testTimingConfig)); */ } <commit_msg>fixed error<commit_after>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void exTestFixture::setUp() { m_File = new exFile("test.h"); m_FileName = new exFileName("test.h"); m_FileNameStatistics = new exFileNameStatistics("test.h"); m_Lexer = new exLexer(); m_RCS = new exRCS(); m_Stat = new exStat("test.h"); m_Statistics = new exStatistics<long>(); m_Tool = new exTool(ID_TOOL_REPORT_COUNT); } void exTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void exTestFixture::testMethods() { // test exFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() == "test.h"); // test exFileName CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); // test exLexer m_Lexer->SetLexerFromText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers // test exRCS CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test exStat CPPUNIT_ASSERT(m_Stat->IsOk()); // test exStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test exTool CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0); } void exTestFixture::testTiming() { exFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { wxString* buffer = file.Read(); CPPUNIT_ASSERT(buffer != NULL); delete buffer; } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "exFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void exTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const exFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void exTestFixture::tearDown() { } void exAppTestFixture::setUp() { } void exAppTestFixture::testConstructors() { m_App = new exApp(); m_Dir = new exDir("./"); m_SVN = new exSVN(SVN_STAT, "test.h"); } void exAppTestFixture::testMethods() { // test exApp m_App->OnInit(); CPPUNIT_ASSERT(m_App->GetConfig() != NULL); CPPUNIT_ASSERT(m_App->GetLexers() != NULL); CPPUNIT_ASSERT(m_App->GetPrinter() != NULL); // test exDir CPPUNIT_ASSERT(m_Dir->GetFiles().GetCount() > 0); // test exSVN m_SVN->Get(); } void exAppTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { exApp::GetConfig("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { exApp::GetConfig()->Read("test", 0l); } const long config = sw.Time(); printf( "exConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void exAppTestFixture::tearDown() { } exTestSuite::exTestSuite() : CppUnit::TestSuite("wxextension test suite") { // Add the tests. addTest(new CppUnit::TestCaller<exTestFixture>( "testConstructors", &exTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exTestFixture>( "testMethods", &exTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTiming", &exTestFixture::testTiming)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingAttrib", &exTestFixture::testTimingAttrib)); /* TODO: the exApp or wxApp not yet okay without normal wxApp initialization addTest(new CppUnit::TestCaller<exAppTestFixture>( "testConstructors", &exAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testMethods", &exAppTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testTimingConfig", &exAppTestFixture::testTimingConfig)); */ } <|endoftext|>
<commit_before>// // generateSimulatedData.cpp // cPWP // // Created by Evan McCartney-Melstad on 12/31/14. // Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved. // #include "generateSimulatedData.h" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string baseErrorRate, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string numReadPairs, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) { /*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00). */ std::ofstream bamsFile; bamsFile.open("bamlist.txt", std::ios::out | std::ios::app); std::cout << "**********\nChecking if processor is available to run wgsim..."; if (system(NULL)) puts ("Ok"); else exit (EXIT_FAILURE); std::vector<std::string> wgsimCommands; int step = 0; while(step <= numIndividuals) { double mutRate = step * mutationRateStepSize; // Covert the mutation rate into a string for the system command std::ostringstream mutStrs; mutStrs << mutRate; std::string mutRateString = mutStrs.str(); std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n"; // Get the number of the individual as a string std::ostringstream stepString; stepString << step; std::string ind = stepString.str(); // Generate the output file names as strings std::string R1out = "ind" + ind + "_R1.fastq"; std::string R2out = "ind" + ind + "_R2.fastq"; std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt"; // Generate the wgsim command and then run it using a system call std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize + " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates if (system((wgsimCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n"; } // Generate the bwa mem command and then run it using a system call std::string bamOut = "ind" + ind + ".bam"; std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -"; if (system((bwaCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n"; } bamsFile << bamOut << std::endl; step++; // Move on to the next individual } bamsFile.close(); return 0; } /* /home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1 */ /* wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt /home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 & */ /* Usage: wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq> Options: -e FLOAT base error rate [0.000] -d INT outer distance between the two ends [500] -s INT standard deviation [50] -N INT number of read pairs [1000000] -1 INT length of the first read [70] -2 INT length of the second read [70] -r FLOAT rate of mutations [0.0010] -R FLOAT fraction of indels [0.15] -X FLOAT probability an indel is extended [0.30] -S INT seed for random generator [-1] -h haplotype mode */ <commit_msg>Switched to pirs instead of wgsim<commit_after>// // generateSimulatedData.cpp // cPWP // // Created by Evan McCartney-Melstad on 12/31/14. // Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved. // #include "generateSimulatedData.h" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string baseErrorRate, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) { /*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00). */ std::ofstream bamsFile; bamsFile.open("bamlist.txt", std::ios::out | std::ios::app); std::cout << "**********\nChecking if processor is available to run pirs..."; if (system(NULL)) puts ("OK"); else exit (EXIT_FAILURE); int pirsInd = 0; while(pirsInd < numIndividuals) { double mutRate = pirsInd * mutationRateStepSize; // Covert the mutation rate into a string for the system command std::ostringstream mutStr; mutStr << mutRate; std::string mutRateString = mutStr.str(); std::cout << "**********\nGenerating reference genome for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n"; // Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names std::ostringstream pirsIndSS; pirsIndSS << "ind" + pirsInd; std::string indName = pirsIndSS.str(); std::string pirsGenomeSTDOUT = indName + "_genome.stdout"; std::string pirsGenomeSTDERR = indName + "_genome.stderr"; // Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize std::string pirsCommandToRun = "pirs diploid -s " + mutStr + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR; if (system((pirsCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n"; } // The following file is output by the pirs diploid command: std::string mutatedChromosome = indName + ".snp.fa"; // After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the std::string pirsSimSTDOUT = indName + "_reads.stdout"; std::string pirsSimSTDERR = indName + "_reads.stderr"; std::string indReadsPrefix = indName + "_reads"; std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " << readLengths << " -x " << depth << " -m " << libFragmentSize << " -v " << stdevLibFragmentSize << " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR; if (system((pirsSimulateCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n"; } // Generate the bwa mem command and then run it using a system call std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq"; std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq"; std::string bamOut = "ind" + ind + ".bam"; std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -"; if (system((bwaCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n"; } bamsFile << bamOut << std::endl; pirsInd++; // Move on to the next individual } /* Implementation with wgsim std::cout << "**********\nChecking if processor is available to run wgsim..."; if (system(NULL)) puts ("Ok"); else exit (EXIT_FAILURE); int step = 0; while(step <= numIndividuals) { double mutRate = step * mutationRateStepSize; // Covert the mutation rate into a string for the system command std::ostringstream mutStrs; mutStrs << mutRate; std::string mutRateString = mutStrs.str(); std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n"; // Get the number of the individual as a string std::ostringstream stepString; stepString << step; std::string ind = stepString.str(); // Generate the output file names as strings std::string R1out = "ind" + ind + "_R1.fastq"; std::string R2out = "ind" + ind + "_R2.fastq"; std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt"; // Generate the wgsim command and then run it using a system call std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize + " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates if (system((wgsimCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n"; } // Generate the bwa mem command and then run it using a system call std::string bamOut = "ind" + ind + ".bam"; std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -"; if (system((bwaCommandToRun).c_str()) != 0) { std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n"; exit(EXIT_FAILURE); } else { std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n"; } bamsFile << bamOut << std::endl; step++; // Move on to the next individual } */ bamsFile.close(); return 0; } /* /home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1 */ /* wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt /home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 & */ /* Usage: wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq> Options: -e FLOAT base error rate [0.000] -d INT outer distance between the two ends [500] -s INT standard deviation [50] -N INT number of read pairs [1000000] -1 INT length of the first read [70] -2 INT length of the second read [70] -r FLOAT rate of mutations [0.0010] -R FLOAT fraction of indels [0.15] -X FLOAT probability an indel is extended [0.30] -S INT seed for random generator [-1] -h haplotype mode */ <|endoftext|>
<commit_before>#include <pip/context.hpp> #include <pip/decl.hpp> #include <pip/translator.hpp> #include <pip/resolver.hpp> #include <pip/evaluator.hpp> #include <pip/type_checker.hpp> #include <pip/pcap.hpp> #include <pip/decode.hpp> #include <sexpr/syntax.hpp> #include <sexpr/context.hpp> #include <sexpr/parser.hpp> #include <cc/input.hpp> #include <cc/output.hpp> #include <cc/diagnostics.hpp> #include <iostream> #include <cstring> #include <cstdint> #include <netinet/in.h> #include <climits> #include <bitset> template <typename R> static constexpr R bitmask(unsigned int const onecount) { return static_cast<R>(-(onecount != 0)) & (static_cast<R>(-1) >> ((sizeof(R) * CHAR_BIT) - onecount)); } template<typename R> static constexpr R bitfieldmask(unsigned int const a, unsigned int const b) { return ((static_cast<R>(-1) >> (((sizeof(R) * CHAR_BIT) - 1) - (b))) & ~((1 << (a)) - 1)); } int main(int argc, char* argv[]) { /// The file use for writing errors. cc::output_device error = std::cerr; /// Manages error diagnostics. cc::diagnostic_manager diags; /// Manages in the input source. cc::input_manager inputs; /// A set of unique symbols. cc::symbol_table syms; /// The program translation context. pip::context cxt(diags, inputs, syms); if (argc < 3) { std::cerr << "usage: pip <pip-program> <pcap-file>\n"; return 1; } // Parse the input file as a pip program. There are a number of // stages of translation: pip::decl* prog; try { // Stage 1. Accept the input file. const cc::file& input = inputs.add_file(argv[1]); // Stage 2: Parse the program as an uninterpreted s-expression. sexpr::context sexpr(diags, inputs, syms); sexpr::parser parse(sexpr, input); sexpr::expr* e = parse(); e->dump(); // Stage 3: Match the s-expression into a pip program. pip::translator trans(cxt); prog = trans(e); prog->dump(); std::cout << "End translation\n"; // Stage 4: Name lookup. Match identifiers to declarations. pip::resolver resolve(cxt); resolve(prog); // Stage 5: Type checking. Assign a type to each expression. pip::type_checker types(cxt, static_cast<pip::program_decl*>(prog)); types.check(); // Stage K: Other static analysis? // ... // Stage K + N: Evaluate the program. // // TODO: Build a packet stream evaluator that encapsulates this // functionality. int partial = 0; pip::cap::file in(argv[2]); pip::cap::packet pkt; while (in.get(pkt)) { std::cout << "PKT:\n"; uint8_t* vec = new uint8_t[pkt.size()]; for(int i = 0; i < pkt.size(); ++i) { uint8_t n; std::memcpy(&n, pkt.data() + i, 1); vec[i] = n; std::cout << std::hex << (unsigned)vec[i] << '\t'; if(i > 1 && i % 8 == 0) std::cout << '\n'; } // pip::cap::eth_header eth(pkt); // const pip::cap::eth_header* eth; // eth = (pip::cap::eth_header*)(pkt.data()); pip::cap::eth_header eth(pkt); // eth.print(); std::cout << "\nETH:\n"; eth.print(std::cout); std::cout << "\nIP:\n"; pip::cap::ipv4_header ipv4(eth); ipv4.print(std::cout); std::cout << "\nTCP:\n"; pip::cap::tcp_header tcp(ipv4); tcp.print(std::cout); // int bitwidth = 7; // uint64_t field = 0; // uint64_t value = 94; // int field_width = 16; // int enjamb = (field_width - (field_width % 8)) / 8; // uint64_t mask = bitmask<uint32_t>(bitwidth); // // We can enjamb a value into the beginning of an integer // // by creating a mask and ORing // if(bitwidth < sizeof(value) * 8) // { // mask << ((sizeof(value) * 8) - bitwidth); // field = (field & ~mask) | (value << (sizeof(value) * 8) - bitwidth); // uint8_t* exploded_field = new uint8_t[8]; // std::memcpy(exploded_field, &field, 8); // std::bitset<64> x(field); // std::cout << "Enjambed number: " << x << '\n'; // std::cout << "Enjambed array: "; // for(int i = 0; i < enjamb; ++i) // { // std::cout << exploded_field[i] << " "; // } // std::cout << '\n'; // } // std::cout << "\nNEW BUF\n"; // for(int i = 0; i < pkt.size(); ++i) // { // std::cout << std::hex << (unsigned)vec[i] << '\t'; // if(i > 1 && i % 8 == 0) // std::cout << '\n'; // } delete[] vec; // for(int i = 0; i < 6; ++i) // std::cout << std::hex << (unsigned)eth->dst_mac[i] << '\t'; // std::cout << '\n'; // for(int i = 0; i < 6; ++i) // std::cout << std::hex << (unsigned)eth->src_mac[i] << '\t'; // std::cout << '\n'; // std::cout << std::hex << (unsigned)eth->ethertype << '\t'; // for(int i = 0; i < sizeof(eth->payload); ++i) { // if(i > 1 && i % 8 == 0) // std::cout << '\n'; // std::cout << std::hex << (unsigned)eth->payload[i] << '\t'; // } // Ignore incomplete packets. if(!pkt.is_complete()) { ++partial; continue; } pip::evaluator eval(cxt, nullptr, pkt); // TODO: This is where we could turn this into a debugger. Simply // allowing the user to invoke the step command would enable them // to step through the execution of the packet in the pipeline. // eval.run(); } std::cout << "partial packets: " << partial << '\n'; } catch (cc::diagnosable_error& err) { diags.emit(err); } // Emit any errors. if (diags.error_count()) print(diags.get_diagnostics(), inputs, error); } <commit_msg>Command line argument for number of physical ports.<commit_after>#include <pip/context.hpp> #include <pip/decl.hpp> #include <pip/translator.hpp> #include <pip/resolver.hpp> #include <pip/evaluator.hpp> #include <pip/type_checker.hpp> #include <pip/pcap.hpp> #include <pip/decode.hpp> #include <pip/codegen.hpp> #include <sexpr/syntax.hpp> #include <sexpr/context.hpp> #include <sexpr/parser.hpp> #include <cc/input.hpp> #include <cc/output.hpp> #include <cc/diagnostics.hpp> #include <iostream> #include <fstream> #include <cstring> #include <cstdint> #include <netinet/in.h> #include <climits> #include <algorithm> int main(int argc, char* argv[]) { /// The file use for writing errors. cc::output_device error = std::cerr; /// Manages error diagnostics. cc::diagnostic_manager diags; /// Manages in the input source. cc::input_manager inputs; /// A set of unique symbols. cc::symbol_table syms; /// The program translation context. pip::context cxt(diags, inputs, syms); if (argc < 3) { std::cerr << "usage: pip <pip-program> <pcap-file>\n"; return 1; } // Parse the input file as a pip program. There are a number of // stages of translation: pip::decl* prog; try { // Stage 1. Accept the input file. const cc::file& input = inputs.add_file(argv[1]); // If the amount of physical is not defined, it is the maximum 32-bit uinteger. std::uint32_t physical_ports = (std::uint32_t)(~0); std::vector<std::string> arguments; arguments.assign(argv, argv + argc); // Otherwise, restrict the set if it is in range. auto port_arg_it = std::find(arguments.begin(), arguments.end(), "-p"); if(port_arg_it == arguments.end()) port_arg_it = std::find(arguments.begin(), arguments.end(), "--ports"); if(port_arg_it != arguments.end()) { std::string amount_string = *(port_arg_it + 1); std::size_t size; int amount = std::stoi(amount_string, &size); if(amount_string.size() != size) throw std::runtime_error("Invalid amount of physical ports."); if(amount < 1 || amount > physical_ports) throw std::runtime_error("Invalid amount of physical ports."); physical_ports = amount; } // Stage 2: Parse the program as an uninterpreted s-expression. sexpr::context sexpr(diags, inputs, syms); sexpr::parser parse(sexpr, input); sexpr::expr* e = parse(); e->dump(); // Stage 3: Match the s-expression into a pip program. pip::translator trans(cxt); prog = trans(e); prog->dump(); auto program = static_cast<pip::program_decl*>(prog); std::cout << "End translation\n"; std::ofstream outfile("out.pip"); pip::generator gen(dynamic_cast<pip::program_decl*>(prog)); outfile << gen.generate(); outfile.close(); // Stage 4: Name lookup. Match identifiers to declarations. pip::resolver resolve(cxt); resolve(prog); // // Stage 5: Type checking. Assign a type to each expression. // pip::type_checker types(cxt, program); // types.check(); // Stage K: Other static analysis? // ... // Stage K + N: Evaluate the program. // // TODO: Build a packet stream evaluator that encapsulates this // functionality. int partial = 0; pip::cap::file in(argv[2]); pip::cap::packet pkt; while (in.get(pkt)) { for(auto d : program->decls) { if(auto t = dynamic_cast<pip::table_decl*>(d)) { for(auto r : t->rules) if(auto i = dynamic_cast<pip::int_expr*>(r->key)) std::cout << "rule key: " << i->val << '\n'; } } pip::evaluator eval(cxt, program, pkt); eval.run(); } // TODO: This is where we could turn this into a debugger. Simply // allowing the user to invoke the step command would enable them // to step through the execution of the packet in the pipeline. // eval.run(); std::cout << "partial packets: " << partial << '\n'; } catch (cc::diagnosable_error& err) { diags.emit(err); } // Emit any errors. if (diags.error_count()) print(diags.get_diagnostics(), inputs, error); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitk_ImageToDiffusionImageSource_txx #define __mitk_ImageToDiffusionImageSource_txx #include "mitkImageToDiffusionImageSource.h" #include <itkComposeImageFilter.h> #include <itkExtractImageFilter.h> #include "mitkImageTimeSelector.h" #include <itkVectorImage.h> #include <itkImage.h> #include "mitkImageCast.h" #include "mitkException.h" template< typename TPixelType> mitk::ImageToDiffusionImageSource<TPixelType>::ImageToDiffusionImageSource() : m_SourceImage(0), m_GradientDirections(0) { } template< typename TPixelType> void mitk::ImageToDiffusionImageSource<TPixelType> ::GenerateOutputInformation() { // sanity checks ( input not null, timesteps corresponds to number of directions specified ) if( m_GradientDirections->empty() ) { mitkThrow() << "No gradient directions were set. Cannot proceed."; } if( m_SourceImage.IsNull() ) { mitkThrow() << "No input image was set. Cannot proceed."; } if( m_GradientDirections->size() != m_SourceImage->GetTimeSteps() ) { mitkThrow() << "Size mismatch between container size " << m_GradientDirections->size() << "and image volumes."<< m_SourceImage->GetTimeSteps() <<" Cannot proceed."; } // already pass in the meta-data typename OutputType::Pointer metaImage = OutputType::New(); // set directions and bvalue metaImage->SetDirections(this->m_GradientDirections); metaImage->SetB_Value(this->m_BValue); // set identity as measurement frame vnl_matrix_fixed< double, 3, 3 > measurement_frame; measurement_frame.set_identity(); metaImage->SetMeasurementFrame( measurement_frame ); m_OutputCache = metaImage; m_CacheTime.Modified(); } template< typename TPixelType> void mitk::ImageToDiffusionImageSource<TPixelType> ::GenerateData() { if ( ( ! m_OutputCache ) || ( this->GetMTime( ) > m_CacheTime.GetMTime( ) ) ) { this->GenerateOutputInformation(); itkWarningMacro("Cache regenerated!"); } // now cast the mitk image to the vector image and pass in as volume typedef itk::Image< TPixelType, 4 > InputItkType; typedef itk::Image< TPixelType, 3> SingleVolumeType; typedef itk::VectorImage< TPixelType, 3> VectorImageType; typedef itk::ComposeImageFilter< SingleVolumeType > ComposeFilterType; typename ComposeFilterType::Pointer vec_composer = ComposeFilterType::New(); mitk::ImageTimeSelector::Pointer t_selector = mitk::ImageTimeSelector::New(); t_selector->SetInput( m_SourceImage ); for( unsigned int i=0; i< m_SourceImage->GetTimeSteps(); i++) { t_selector->SetTimeNr(i); t_selector->Update(); typename SingleVolumeType::Pointer singleImageItk; mitk::CastToItkImage( t_selector->GetOutput(), singleImageItk ); vec_composer->SetInput( i, singleImageItk ); } try { vec_composer->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Caugt exception while updating compose filter: " << e.what(); } m_OutputCache->SetVectorImage( vec_composer->GetOutput() ); // transfer to the output image static_cast<OutputType*>(this->GetOutput()) ->SetVectorImage(m_OutputCache->GetVectorImage()); static_cast<OutputType*>(this->GetOutput()) ->SetB_Value(m_OutputCache->GetB_Value()); static_cast<OutputType*>(this->GetOutput()) ->SetDirections(m_OutputCache->GetDirections()); static_cast<OutputType*>(this->GetOutput()) ->SetMeasurementFrame(m_OutputCache->GetMeasurementFrame()); static_cast<OutputType*>(this->GetOutput()) ->InitializeFromVectorImage(); } #endif //__mitk_ImageToDiffusionImageSource_txx <commit_msg>Fixed sanity checks<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitk_ImageToDiffusionImageSource_txx #define __mitk_ImageToDiffusionImageSource_txx #include "mitkImageToDiffusionImageSource.h" #include <itkComposeImageFilter.h> #include <itkExtractImageFilter.h> #include "mitkImageTimeSelector.h" #include <itkVectorImage.h> #include <itkImage.h> #include "mitkImageCast.h" #include "mitkException.h" template< typename TPixelType> mitk::ImageToDiffusionImageSource<TPixelType>::ImageToDiffusionImageSource() : m_SourceImage(0), m_GradientDirections(0) { } template< typename TPixelType> void mitk::ImageToDiffusionImageSource<TPixelType> ::GenerateOutputInformation() { // sanity checks ( input not null, timesteps corresponds to number of directions specified ) if( m_GradientDirections.IsNull() || m_GradientDirections->empty() ) { mitkThrow() << "No gradient directions were set. Cannot proceed."; } if( m_SourceImage.IsNull() ) { mitkThrow() << "No input image was set. Cannot proceed."; } if( m_GradientDirections->size() != m_SourceImage->GetTimeSteps() ) { mitkThrow() << "Size mismatch between container size " << m_GradientDirections->size() << "and image volumes."<< m_SourceImage->GetTimeSteps() <<" Cannot proceed."; } // already pass in the meta-data typename OutputType::Pointer metaImage = OutputType::New(); // set directions and bvalue metaImage->SetDirections(this->m_GradientDirections); metaImage->SetB_Value(this->m_BValue); // set identity as measurement frame vnl_matrix_fixed< double, 3, 3 > measurement_frame; measurement_frame.set_identity(); metaImage->SetMeasurementFrame( measurement_frame ); m_OutputCache = metaImage; m_CacheTime.Modified(); } template< typename TPixelType> void mitk::ImageToDiffusionImageSource<TPixelType> ::GenerateData() { if ( ( ! m_OutputCache ) || ( this->GetMTime( ) > m_CacheTime.GetMTime( ) ) ) { this->GenerateOutputInformation(); itkWarningMacro("Cache regenerated!"); } // now cast the mitk image to the vector image and pass in as volume typedef itk::Image< TPixelType, 4 > InputItkType; typedef itk::Image< TPixelType, 3> SingleVolumeType; typedef itk::VectorImage< TPixelType, 3> VectorImageType; typedef itk::ComposeImageFilter< SingleVolumeType > ComposeFilterType; typename ComposeFilterType::Pointer vec_composer = ComposeFilterType::New(); mitk::ImageTimeSelector::Pointer t_selector = mitk::ImageTimeSelector::New(); t_selector->SetInput( m_SourceImage ); for( unsigned int i=0; i< m_SourceImage->GetTimeSteps(); i++) { t_selector->SetTimeNr(i); t_selector->Update(); typename SingleVolumeType::Pointer singleImageItk; mitk::CastToItkImage( t_selector->GetOutput(), singleImageItk ); vec_composer->SetInput( i, singleImageItk ); } try { vec_composer->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Caugt exception while updating compose filter: " << e.what(); } m_OutputCache->SetVectorImage( vec_composer->GetOutput() ); // transfer to the output image static_cast<OutputType*>(this->GetOutput()) ->SetVectorImage(m_OutputCache->GetVectorImage()); static_cast<OutputType*>(this->GetOutput()) ->SetB_Value(m_OutputCache->GetB_Value()); static_cast<OutputType*>(this->GetOutput()) ->SetDirections(m_OutputCache->GetDirections()); static_cast<OutputType*>(this->GetOutput()) ->SetMeasurementFrame(m_OutputCache->GetMeasurementFrame()); static_cast<OutputType*>(this->GetOutput()) ->InitializeFromVectorImage(); } #endif //__mitk_ImageToDiffusionImageSource_txx <|endoftext|>
<commit_before>#include <sstream> #include <stdexcept> #include "File.h" #include "KeyValueFile.h" #include "String.h" #include "StringView.h" #include "../debug/Debug.h" void KeyValueFile::Section::init(std::string &&name) { this->name = std::move(name); } const std::string &KeyValueFile::Section::getName() const { return this->name; } int KeyValueFile::Section::getPairCount() const { return static_cast<int>(this->pairs.size()); } const std::pair<std::string, std::string> &KeyValueFile::Section::getPair(int index) const { DebugAssertIndex(this->pairs, index); return this->pairs[index]; } bool KeyValueFile::Section::tryGetValue(const std::string &key, std::string_view &value) const { const std::pair<std::string, std::string> searchPair(key, std::string()); const auto iter = std::lower_bound(this->pairs.begin(), this->pairs.end(), searchPair, [](const auto &pairA, const auto &pairB) { return pairA.first < pairB.first; }); if (iter != this->pairs.end()) { value = iter->second; return true; } else { return false; } } bool KeyValueFile::Section::tryGetBoolean(const std::string &key, bool &value) const { std::string_view str; if (!this->tryGetValue(key, str)) { return false; } else { // Convert to lowercase for easier comparison. const std::string lowerStr = String::toLowercase(std::string(str)); if (lowerStr == "true") { value = true; return true; } else if (lowerStr == "false") { value = false; return true; } else { return false; } } } bool KeyValueFile::Section::tryGetInteger(const std::string &key, int &value) const { std::string_view str; if (!this->tryGetValue(key, str)) { return false; } else { try { size_t index = 0; value = std::stoi(std::string(str), &index); return index == str.size(); } catch (std::exception) { return false; } } } bool KeyValueFile::Section::tryGetDouble(const std::string &key, double &value) const { std::string_view str; if (!this->tryGetValue(key, str)) { return false; } else { try { size_t index = 0; value = std::stod(std::string(str), &index); return index == str.size(); } catch (std::exception) { return false; } } } bool KeyValueFile::Section::tryGetString(const std::string &key, std::string_view &value) const { return this->tryGetValue(key, value); } void KeyValueFile::Section::add(std::string &&key, std::string &&value) { this->pairs.push_back(std::make_pair(std::move(key), std::move(value))); std::sort(this->pairs.begin(), this->pairs.end(), [](const auto &pairA, const auto &pairB) { const std::string &strA = pairA.first; const std::string &strB = pairB.first; return strA < strB; }); } void KeyValueFile::Section::clear() { this->pairs.clear(); } const char KeyValueFile::COMMENT = '#'; const char KeyValueFile::PAIR_SEPARATOR = '='; const char KeyValueFile::SECTION_FRONT = '['; const char KeyValueFile::SECTION_BACK = ']'; bool KeyValueFile::init(const char *filename) { const std::string text = File::readAllText(filename); std::istringstream iss(text); // Check each line for a valid section or key-value pair. Start the line numbers at 1 // since most users aren't programmers. std::string line; Section *activeSection = nullptr; for (int lineNumber = 1; std::getline(iss, line); lineNumber++) { // Get a filtered version of the current line so it can be parsed. If the filtered // string is empty, then skip to the next line. const std::string_view filteredLine = [&line]() { std::string_view str = line; // Skip empty strings. if ((str.size() == 0) || ((str.size() == 1) && (str.front() == '\r'))) { return std::string_view(); } // Remove carriage return at the end (if any). if (str.back() == '\r') { str.remove_suffix(1); } // Extract left-most comment (if any). const size_t commentIndex = str.find(KeyValueFile::COMMENT); if (commentIndex == 0) { // Comment covers the entire line. return std::string_view(); } else if (commentIndex != std::string_view::npos) { // Comment is somewhere in the line, so only work with the left substring. str = str.substr(0, commentIndex); } // Trim leading and trailing whitespace (i.e., in case the key has whitespace // before it, or a comment had whitespace before it). return StringView::trimFront(StringView::trimBack(str)); }(); if (filteredLine.empty()) { // It became an empty string after whitespace was removed. continue; } else if (filteredLine.size() < 3) { // Not long enough to be a section or key-value pair. DebugLogError("Syntax error \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } // See if it's a section line or key-value pair line. const size_t sectionFrontIndex = filteredLine.find(KeyValueFile::SECTION_FRONT); if (sectionFrontIndex != std::string_view::npos) { // Section line. There must be a closing character with enough space between it // and the front character for at least one section character. const size_t sectionBackIndex = filteredLine.find( KeyValueFile::SECTION_BACK, sectionFrontIndex); if ((sectionBackIndex != std::string_view::npos) && (sectionBackIndex > (sectionFrontIndex + 1))) { // Get the string that's between the section characters and trim any // leading or trailing whitespace. std::string_view sectionName = filteredLine.substr( sectionFrontIndex + 1, sectionBackIndex - sectionFrontIndex - 1); sectionName = StringView::trimFront(StringView::trimBack(sectionName)); const auto sectionIter = std::find_if(this->sections.begin(), this->sections.end(), [&sectionName](const Section &section) { return section.getName() == sectionName; }); // If the section is new, add it to the section maps. if (sectionIter == this->sections.end()) { Section section; section.init(std::string(sectionName)); this->sections.push_back(std::move(section)); activeSection = &this->sections.back(); } else { DebugLogError("Section \"" + std::string(sectionName) + "\" (line " + std::to_string(lineNumber) + ") already defined in " + filename + "."); return false; } } else { DebugLogError("Invalid section \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } } else if (filteredLine.find(KeyValueFile::PAIR_SEPARATOR) != std::string::npos) { // Key-value pair line. There must be two tokens: key and value. std::array<std::string_view, 2> tokens; if (!StringView::splitExpected(filteredLine, KeyValueFile::PAIR_SEPARATOR, tokens)) { DebugLogError("Invalid pair \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } // Trim trailing whitespace from the key and leading whitespace from the value. const std::string_view &key = StringView::trimBack(tokens[0]); const std::string_view &value = StringView::trimFront(tokens[1]); if (key.size() == 0) { DebugLogError("Empty key in \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } // Add the key-value pair to the active section map. if (activeSection != nullptr) { activeSection->add(std::string(key), std::string(value)); } else { // If no active section map, print a warning and ignore the current pair. // All key-value pairs must be in a section. DebugLogWarning("Ignoring \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + "), no active section in " + filename); } } else { // Filtered line is not a section or key-value pair. DebugLogError("Invalid line \"" + line + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } } // Sort for binary search. std::sort(this->sections.begin(), this->sections.end(), [](const Section &sectionA, const Section &sectionB) { return sectionA.getName() < sectionB.getName(); }); return true; } int KeyValueFile::getSectionCount() const { return static_cast<int>(this->sections.size()); } const KeyValueFile::Section &KeyValueFile::getSection(int index) const { DebugAssertIndex(this->sections, index); return this->sections[index]; } const KeyValueFile::Section *KeyValueFile::getSectionByName(const std::string &name) const { const auto iter = std::lower_bound(this->sections.begin(), this->sections.end(), name, [](const Section &section, const std::string &str) { return section.getName() < str; }); return (iter != this->sections.end()) ? &(*iter) : nullptr; } <commit_msg>Fixed GCC compile error.<commit_after>#include <algorithm> #include <sstream> #include <stdexcept> #include "File.h" #include "KeyValueFile.h" #include "String.h" #include "StringView.h" #include "../debug/Debug.h" void KeyValueFile::Section::init(std::string &&name) { this->name = std::move(name); } const std::string &KeyValueFile::Section::getName() const { return this->name; } int KeyValueFile::Section::getPairCount() const { return static_cast<int>(this->pairs.size()); } const std::pair<std::string, std::string> &KeyValueFile::Section::getPair(int index) const { DebugAssertIndex(this->pairs, index); return this->pairs[index]; } bool KeyValueFile::Section::tryGetValue(const std::string &key, std::string_view &value) const { const std::pair<std::string, std::string> searchPair(key, std::string()); const auto iter = std::lower_bound(this->pairs.begin(), this->pairs.end(), searchPair, [](const auto &pairA, const auto &pairB) { return pairA.first < pairB.first; }); if (iter != this->pairs.end()) { value = iter->second; return true; } else { return false; } } bool KeyValueFile::Section::tryGetBoolean(const std::string &key, bool &value) const { std::string_view str; if (!this->tryGetValue(key, str)) { return false; } else { // Convert to lowercase for easier comparison. const std::string lowerStr = String::toLowercase(std::string(str)); if (lowerStr == "true") { value = true; return true; } else if (lowerStr == "false") { value = false; return true; } else { return false; } } } bool KeyValueFile::Section::tryGetInteger(const std::string &key, int &value) const { std::string_view str; if (!this->tryGetValue(key, str)) { return false; } else { try { size_t index = 0; value = std::stoi(std::string(str), &index); return index == str.size(); } catch (std::exception) { return false; } } } bool KeyValueFile::Section::tryGetDouble(const std::string &key, double &value) const { std::string_view str; if (!this->tryGetValue(key, str)) { return false; } else { try { size_t index = 0; value = std::stod(std::string(str), &index); return index == str.size(); } catch (std::exception) { return false; } } } bool KeyValueFile::Section::tryGetString(const std::string &key, std::string_view &value) const { return this->tryGetValue(key, value); } void KeyValueFile::Section::add(std::string &&key, std::string &&value) { this->pairs.push_back(std::make_pair(std::move(key), std::move(value))); std::sort(this->pairs.begin(), this->pairs.end(), [](const auto &pairA, const auto &pairB) { const std::string &strA = pairA.first; const std::string &strB = pairB.first; return strA < strB; }); } void KeyValueFile::Section::clear() { this->pairs.clear(); } const char KeyValueFile::COMMENT = '#'; const char KeyValueFile::PAIR_SEPARATOR = '='; const char KeyValueFile::SECTION_FRONT = '['; const char KeyValueFile::SECTION_BACK = ']'; bool KeyValueFile::init(const char *filename) { const std::string text = File::readAllText(filename); std::istringstream iss(text); // Check each line for a valid section or key-value pair. Start the line numbers at 1 // since most users aren't programmers. std::string line; Section *activeSection = nullptr; for (int lineNumber = 1; std::getline(iss, line); lineNumber++) { // Get a filtered version of the current line so it can be parsed. If the filtered // string is empty, then skip to the next line. const std::string_view filteredLine = [&line]() { std::string_view str = line; // Skip empty strings. if ((str.size() == 0) || ((str.size() == 1) && (str.front() == '\r'))) { return std::string_view(); } // Remove carriage return at the end (if any). if (str.back() == '\r') { str.remove_suffix(1); } // Extract left-most comment (if any). const size_t commentIndex = str.find(KeyValueFile::COMMENT); if (commentIndex == 0) { // Comment covers the entire line. return std::string_view(); } else if (commentIndex != std::string_view::npos) { // Comment is somewhere in the line, so only work with the left substring. str = str.substr(0, commentIndex); } // Trim leading and trailing whitespace (i.e., in case the key has whitespace // before it, or a comment had whitespace before it). return StringView::trimFront(StringView::trimBack(str)); }(); if (filteredLine.empty()) { // It became an empty string after whitespace was removed. continue; } else if (filteredLine.size() < 3) { // Not long enough to be a section or key-value pair. DebugLogError("Syntax error \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } // See if it's a section line or key-value pair line. const size_t sectionFrontIndex = filteredLine.find(KeyValueFile::SECTION_FRONT); if (sectionFrontIndex != std::string_view::npos) { // Section line. There must be a closing character with enough space between it // and the front character for at least one section character. const size_t sectionBackIndex = filteredLine.find( KeyValueFile::SECTION_BACK, sectionFrontIndex); if ((sectionBackIndex != std::string_view::npos) && (sectionBackIndex > (sectionFrontIndex + 1))) { // Get the string that's between the section characters and trim any // leading or trailing whitespace. std::string_view sectionName = filteredLine.substr( sectionFrontIndex + 1, sectionBackIndex - sectionFrontIndex - 1); sectionName = StringView::trimFront(StringView::trimBack(sectionName)); const auto sectionIter = std::find_if(this->sections.begin(), this->sections.end(), [&sectionName](const Section &section) { return section.getName() == sectionName; }); // If the section is new, add it to the section maps. if (sectionIter == this->sections.end()) { Section section; section.init(std::string(sectionName)); this->sections.push_back(std::move(section)); activeSection = &this->sections.back(); } else { DebugLogError("Section \"" + std::string(sectionName) + "\" (line " + std::to_string(lineNumber) + ") already defined in " + filename + "."); return false; } } else { DebugLogError("Invalid section \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } } else if (filteredLine.find(KeyValueFile::PAIR_SEPARATOR) != std::string::npos) { // Key-value pair line. There must be two tokens: key and value. std::array<std::string_view, 2> tokens; if (!StringView::splitExpected(filteredLine, KeyValueFile::PAIR_SEPARATOR, tokens)) { DebugLogError("Invalid pair \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } // Trim trailing whitespace from the key and leading whitespace from the value. const std::string_view &key = StringView::trimBack(tokens[0]); const std::string_view &value = StringView::trimFront(tokens[1]); if (key.size() == 0) { DebugLogError("Empty key in \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } // Add the key-value pair to the active section map. if (activeSection != nullptr) { activeSection->add(std::string(key), std::string(value)); } else { // If no active section map, print a warning and ignore the current pair. // All key-value pairs must be in a section. DebugLogWarning("Ignoring \"" + std::string(filteredLine) + "\" (line " + std::to_string(lineNumber) + "), no active section in " + filename); } } else { // Filtered line is not a section or key-value pair. DebugLogError("Invalid line \"" + line + "\" (line " + std::to_string(lineNumber) + ") in " + filename + "."); return false; } } // Sort for binary search. std::sort(this->sections.begin(), this->sections.end(), [](const Section &sectionA, const Section &sectionB) { return sectionA.getName() < sectionB.getName(); }); return true; } int KeyValueFile::getSectionCount() const { return static_cast<int>(this->sections.size()); } const KeyValueFile::Section &KeyValueFile::getSection(int index) const { DebugAssertIndex(this->sections, index); return this->sections[index]; } const KeyValueFile::Section *KeyValueFile::getSectionByName(const std::string &name) const { const auto iter = std::lower_bound(this->sections.begin(), this->sections.end(), name, [](const Section &section, const std::string &str) { return section.getName() < str; }); return (iter != this->sections.end()) ? &(*iter) : nullptr; } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF 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 "yosystab.h" #include <QGridLayout> #include <QMessageBox> NEXTPNR_NAMESPACE_BEGIN YosysTab::YosysTab(QString folder, QWidget *parent) : QWidget(parent) { QFont f("unexistent"); f.setStyleHint(QFont::Monospace); console = new QPlainTextEdit(); console->setMinimumHeight(100); console->setReadOnly(true); console->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); console->setFont(f); console->setContextMenuPolicy(Qt::CustomContextMenu); QAction *clearAction = new QAction("Clear &buffer", this); clearAction->setStatusTip("Clears display buffer"); connect(clearAction, SIGNAL(triggered()), this, SLOT(clearBuffer())); contextMenu = console->createStandardContextMenu(); contextMenu->addSeparator(); contextMenu->addAction(clearAction); connect(console, SIGNAL(customContextMenuRequested(const QPoint)), this, SLOT(showContextMenu(const QPoint))); lineEdit = new YosysLineEditor(); lineEdit->setMinimumHeight(30); lineEdit->setMaximumHeight(30); lineEdit->setFont(f); lineEdit->setFocus(); lineEdit->setEnabled(false); lineEdit->setPlaceholderText("yosys>"); connect(lineEdit, SIGNAL(textLineInserted(QString)), this, SLOT(editLineReturnPressed(QString))); QGridLayout *mainLayout = new QGridLayout(); mainLayout->addWidget(console, 0, 0); mainLayout->addWidget(lineEdit, 1, 0); setLayout(mainLayout); process = new QProcess(); connect(process, SIGNAL(readyReadStandardError()), this, SLOT(onReadyReadStandardError())); connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStandardOutput())); connect(process, &QProcess::started, this, [this] { lineEdit->setEnabled(true); }); /* #if QT_VERSION < QT_VERSION_CHECK(5, 6, 0) connect(process, &QProcess::error, this, [this](QProcess::ProcessError error) { #else connect(process, &QProcess::errorOccurred, this, [this](QProcess::ProcessError error) { #endif if (error == QProcess::FailedToStart) { QMessageBox::critical( this, QString::fromUtf8("Yosys cannot be started!"), QString::fromUtf8("<p>Please make sure you have Yosys installed and available in path</p>")); Q_EMIT deleteLater(); } }); */ process->setWorkingDirectory(folder); process->start("yosys"); } YosysTab::~YosysTab() { process->terminate(); process->waitForFinished(1000); // in ms process->kill(); process->close(); } void YosysTab::displayString(QString text) { QTextCursor cursor = console->textCursor(); cursor.movePosition(QTextCursor::End); cursor.insertText(text); cursor.movePosition(QTextCursor::End); console->setTextCursor(cursor); } void YosysTab::onReadyReadStandardOutput() { displayString(process->readAllStandardOutput()); } void YosysTab::onReadyReadStandardError() { displayString(process->readAllStandardError()); } void YosysTab::editLineReturnPressed(QString text) { process->write(text.toLatin1() + "\n"); } void YosysTab::showContextMenu(const QPoint &pt) { contextMenu->exec(mapToGlobal(pt)); } void YosysTab::clearBuffer() { console->clear(); } NEXTPNR_NAMESPACE_END <commit_msg>proper fix<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF 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 "yosystab.h" #include <QGridLayout> #include <QMessageBox> NEXTPNR_NAMESPACE_BEGIN YosysTab::YosysTab(QString folder, QWidget *parent) : QWidget(parent) { QFont f("unexistent"); f.setStyleHint(QFont::Monospace); console = new QPlainTextEdit(); console->setMinimumHeight(100); console->setReadOnly(true); console->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); console->setFont(f); console->setContextMenuPolicy(Qt::CustomContextMenu); QAction *clearAction = new QAction("Clear &buffer", this); clearAction->setStatusTip("Clears display buffer"); connect(clearAction, SIGNAL(triggered()), this, SLOT(clearBuffer())); contextMenu = console->createStandardContextMenu(); contextMenu->addSeparator(); contextMenu->addAction(clearAction); connect(console, SIGNAL(customContextMenuRequested(const QPoint)), this, SLOT(showContextMenu(const QPoint))); lineEdit = new YosysLineEditor(); lineEdit->setMinimumHeight(30); lineEdit->setMaximumHeight(30); lineEdit->setFont(f); lineEdit->setFocus(); lineEdit->setEnabled(false); lineEdit->setPlaceholderText("yosys>"); connect(lineEdit, SIGNAL(textLineInserted(QString)), this, SLOT(editLineReturnPressed(QString))); QGridLayout *mainLayout = new QGridLayout(); mainLayout->addWidget(console, 0, 0); mainLayout->addWidget(lineEdit, 1, 0); setLayout(mainLayout); process = new QProcess(); connect(process, SIGNAL(readyReadStandardError()), this, SLOT(onReadyReadStandardError())); connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadyReadStandardOutput())); connect(process, &QProcess::started, this, [this] { lineEdit->setEnabled(true); }); #if QT_VERSION < QT_VERSION_CHECK(5, 6, 0) connect(process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error), this, [this](QProcess::ProcessError error) { #else connect(process, &QProcess::errorOccurred, this, [this](QProcess::ProcessError error) { #endif if (error == QProcess::FailedToStart) { QMessageBox::critical( this, QString::fromUtf8("Yosys cannot be started!"), QString::fromUtf8("<p>Please make sure you have Yosys installed and available in path</p>")); Q_EMIT deleteLater(); } }); process->setWorkingDirectory(folder); process->start("yosys"); } YosysTab::~YosysTab() { process->terminate(); process->waitForFinished(1000); // in ms process->kill(); process->close(); } void YosysTab::displayString(QString text) { QTextCursor cursor = console->textCursor(); cursor.movePosition(QTextCursor::End); cursor.insertText(text); cursor.movePosition(QTextCursor::End); console->setTextCursor(cursor); } void YosysTab::onReadyReadStandardOutput() { displayString(process->readAllStandardOutput()); } void YosysTab::onReadyReadStandardError() { displayString(process->readAllStandardError()); } void YosysTab::editLineReturnPressed(QString text) { process->write(text.toLatin1() + "\n"); } void YosysTab::showContextMenu(const QPoint &pt) { contextMenu->exec(mapToGlobal(pt)); } void YosysTab::clearBuffer() { console->clear(); } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/logging.h" #include "base/debug.h" #include "base/system_time.h" #include "base/strings/unicode.h" #include <fstream> #include <iomanip> #include <mutex> #include <ostream> #include <thread> #if defined(OS_WIN) #include <Windows.h> #include <Psapi.h> #endif // defined(OS_WIN) #if defined(OS_LINUX) #include <linux/limits.h> #include <unistd.h> #endif // defined(OS_LINUX) #if defined(OS_MAC) #include <mach-o/dyld.h> #include <sys/syslimits.h> #endif // defined(OS_MAC) namespace base { namespace { LoggingSeverity g_min_log_level = LS_INFO; LoggingDestination g_logging_destination = LOG_DEFAULT; std::filesystem::path g_log_file_path; std::ofstream g_log_file; std::mutex g_log_file_lock; const char* severityName(LoggingSeverity severity) { static const char* const kLogSeverityNames[] = { "INFO", "WARNING", "ERROR", "FATAL" }; static_assert(LS_NUMBER == std::size(kLogSeverityNames)); if (severity >= 0 && severity < LS_NUMBER) return kLogSeverityNames[severity]; return "UNKNOWN"; } void removeOldFiles(const std::filesystem::path& path, const std::filesystem::file_time_type& current_time, int max_file_age) { std::filesystem::file_time_type time = current_time - std::chrono::hours(24 * max_file_age); std::error_code ignored_code; for (const auto& item : std::filesystem::directory_iterator(path, ignored_code)) { if (item.is_directory()) continue; if (item.last_write_time() < time) std::filesystem::remove(item.path(), ignored_code); } } std::filesystem::path defaultLogFileDir() { std::error_code error_code; std::filesystem::path path = std::filesystem::temp_directory_path(error_code); if (error_code) return std::filesystem::path(); path.append("aspia"); return path; } bool initLoggingImpl(const LoggingSettings& settings, const std::filesystem::path& file_name) { std::scoped_lock lock(g_log_file_lock); g_log_file.close(); g_logging_destination = settings.destination; if (!(g_logging_destination & LOG_TO_FILE)) return true; std::filesystem::path file_dir = settings.log_dir; if (file_dir.empty()) file_dir = defaultLogFileDir(); if (file_dir.empty()) return false; std::error_code error_code; if (!std::filesystem::exists(file_dir, error_code)) { if (error_code) return false; if (!std::filesystem::create_directories(file_dir, error_code)) return false; } SystemTime time = SystemTime::now(); std::ostringstream file_name_stream; file_name_stream << file_name.c_str() << '-' << std::setfill('0') << std::setw(4) << time.year() << std::setw(2) << time.month() << std::setw(2) << time.day() << '-' << std::setw(2) << time.hour() << std::setw(2) << time.minute() << std::setw(2) << time.second() << '.' << std::setw(3) << time.millisecond() << ".log"; std::filesystem::path file_path(file_dir); file_path.append(file_name_stream.str()); g_log_file.open(file_path); if (!g_log_file.is_open()) return false; std::filesystem::file_time_type file_time = std::filesystem::last_write_time(file_path, error_code); if (!error_code) removeOldFiles(file_dir, file_time, settings.max_log_age); g_log_file_path = std::move(file_path); return true; } } // namespace // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have // an object of the correct type on the LHS of the unused part of the ternary // operator. std::ostream* g_swallow_stream; LoggingSettings::LoggingSettings() : destination(LOG_DEFAULT), min_log_level(LS_INFO), max_log_age(7) { // Nothing } bool initLogging(const LoggingSettings& settings) { std::filesystem::path exec_file_path; #if defined(OS_WIN) wchar_t buffer[MAX_PATH] = { 0 }; GetModuleFileNameExW(GetCurrentProcess(), nullptr, buffer, std::size(buffer)); exec_file_path = buffer; #elif defined(OS_LINUX) char buffer[PATH_MAX] = { 0 }; readlink("/proc/self/exe", buffer, std::size(buffer)); exec_file_path = buffer; #elif defined(OS_MAC) char buffer[PATH_MAX] = { 0 }; uint32_t buffer_size = std::size(buffer); _NSGetExecutablePath(buffer, &buffer_size); exec_file_path = buffer; #else #error Not implemented #endif std::filesystem::path file_name = exec_file_path.filename(); file_name.replace_extension(); if (!initLoggingImpl(settings, file_name)) return false; LOG(LS_INFO) << "Executable file: " << exec_file_path.c_str(); LOG(LS_INFO) << "Logging file: " << g_log_file_path; LOG(LS_INFO) << "Debugger present: " << (isDebuggerPresent() ? "Yes" : "No"); #if defined(NDEBUG) LOG(LS_INFO) << "Debug build: No"; #else LOG(LS_INFO) << "Debug build: Yes"; #endif // defined(NDEBUG) LOG(LS_INFO) << "Logging started"; return true; } void shutdownLogging() { LOG(LS_INFO) << "Logging finished"; std::scoped_lock lock(g_log_file_lock); g_log_file.close(); } bool shouldCreateLogMessage(LoggingSeverity severity) { if (severity < g_min_log_level) return false; // Return true here unless we know ~LogMessage won't do anything. Note that // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even // when g_logging_destination is LOG_NONE. return g_logging_destination != LOG_NONE || severity >= LS_ERROR; } void makeCheckOpValueString(std::ostream* os, std::nullptr_t /* p */) { (*os) << "nullptr"; } std::string* makeCheckOpString(const int& v1, const int& v2, const char* names) { return makeCheckOpString<int, int>(v1, v2, names); } std::string* makeCheckOpString(const unsigned long& v1, const unsigned long& v2, const char* names) { return makeCheckOpString<unsigned long, unsigned long>(v1, v2, names); } std::string* makeCheckOpString(const unsigned int& v1, const unsigned int& v2, const char* names) { return makeCheckOpString<unsigned int, unsigned int>(v1, v2, names); } std::string* makeCheckOpString(const unsigned long long& v1, const unsigned long long& v2, const char* names) { return makeCheckOpString<unsigned long long, unsigned long long>(v1, v2, names); } std::string* makeCheckOpString(const unsigned long& v1, const unsigned int& v2, const char* names) { return makeCheckOpString<unsigned long, int>(v1, v2, names); } std::string* makeCheckOpString(const unsigned int& v1, const unsigned long& v2, const char* names) { return makeCheckOpString<unsigned int, unsigned long>(v1, v2, names); } std::string* makeCheckOpString(const std::string& v1, const std::string& v2, const char* names) { return makeCheckOpString<std::string, std::string>(v1, v2, names); } LogMessage::LogMessage(std::string_view file, int line, LoggingSeverity severity) : severity_(severity) { init(file, line); } LogMessage::LogMessage(std::string_view file, int line, const char* condition) : severity_(LS_FATAL) { init(file, line); stream_ << "Check failed: " << condition << ". "; } LogMessage::LogMessage(std::string_view file, int line, std::string* result) : severity_(LS_FATAL) { std::unique_ptr<std::string> result_deleter(result); init(file, line); stream_ << "Check failed: " << *result; } LogMessage::LogMessage(std::string_view file, int line, LoggingSeverity severity, std::string* result) : severity_(severity) { std::unique_ptr<std::string> result_deleter(result); init(file, line); stream_ << "Check failed: " << *result; } LogMessage::~LogMessage() { stream_ << std::endl; std::string message(stream_.str()); if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) { debugPrint(message.data()); fwrite(message.data(), message.size(), 1, stderr); fflush(stderr); } else if (severity_ >= LS_ERROR) { // When we're only outputting to a log file, above a certain log level, we // should still output to stderr so that we can better detect and diagnose // problems with unit tests, especially on the buildbots. fwrite(message.data(), message.size(), 1, stderr); fflush(stderr); } // Write to log file. if ((g_logging_destination & LOG_TO_FILE) != 0) { std::scoped_lock lock(g_log_file_lock); g_log_file.write(message.c_str(), message.size()); g_log_file.flush(); } if (severity_ == LS_FATAL) { // Crash the process. debugBreak(); } } // Writes the common header info to the stream. void LogMessage::init(std::string_view file, int line) { size_t last_slash_pos = file.find_last_of("\\/"); if (last_slash_pos != std::string_view::npos) file.remove_prefix(last_slash_pos + 1); SystemTime time = SystemTime::now(); stream_ << std::setfill('0') << std::setw(2) << time.hour() << ':' << std::setw(2) << time.minute() << ':' << std::setw(2) << time.second() << '.' << std::setw(3) << time.millisecond() << ' ' << std::this_thread::get_id() << ' ' << severityName(severity_) << ' ' << file.data() << ":" << line << "] "; message_start_ = stream_.str().length(); } ErrorLogMessage::ErrorLogMessage(std::string_view file, int line, LoggingSeverity severity, SystemError error) : error_(error), log_message_(file, line, severity) { // Nothing } ErrorLogMessage::~ErrorLogMessage() { stream() << ": " << error_.toString(); } void logErrorNotReached(const char* file, int line) { LogMessage(file, line, LS_ERROR).stream() << "NOTREACHED() hit."; } } // namespace base namespace std { #if defined(OS_WIN) std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) { return out << base::utf8FromWide(wstr); } std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) { return out << (wstr ? base::utf8FromWide(wstr) : "nullptr"); } #endif // defined(OS_WIN) std::ostream& operator<<(std::ostream& out, const char16_t* ustr) { return out << (ustr ? base::utf8FromUtf16(ustr) : "nullptr"); } std::ostream& operator<<(std::ostream& out, const std::u16string& ustr) { return out << base::utf8FromUtf16(ustr); } } // namespace std <commit_msg>Added endian info to log.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/logging.h" #include "base/debug.h" #include "base/endian_util.h" #include "base/system_time.h" #include "base/strings/unicode.h" #include <fstream> #include <iomanip> #include <mutex> #include <ostream> #include <thread> #if defined(OS_WIN) #include <Windows.h> #include <Psapi.h> #endif // defined(OS_WIN) #if defined(OS_LINUX) #include <linux/limits.h> #include <unistd.h> #endif // defined(OS_LINUX) #if defined(OS_MAC) #include <mach-o/dyld.h> #include <sys/syslimits.h> #endif // defined(OS_MAC) namespace base { namespace { LoggingSeverity g_min_log_level = LS_INFO; LoggingDestination g_logging_destination = LOG_DEFAULT; std::filesystem::path g_log_file_path; std::ofstream g_log_file; std::mutex g_log_file_lock; const char* severityName(LoggingSeverity severity) { static const char* const kLogSeverityNames[] = { "INFO", "WARNING", "ERROR", "FATAL" }; static_assert(LS_NUMBER == std::size(kLogSeverityNames)); if (severity >= 0 && severity < LS_NUMBER) return kLogSeverityNames[severity]; return "UNKNOWN"; } void removeOldFiles(const std::filesystem::path& path, const std::filesystem::file_time_type& current_time, int max_file_age) { std::filesystem::file_time_type time = current_time - std::chrono::hours(24 * max_file_age); std::error_code ignored_code; for (const auto& item : std::filesystem::directory_iterator(path, ignored_code)) { if (item.is_directory()) continue; if (item.last_write_time() < time) std::filesystem::remove(item.path(), ignored_code); } } std::filesystem::path defaultLogFileDir() { std::error_code error_code; std::filesystem::path path = std::filesystem::temp_directory_path(error_code); if (error_code) return std::filesystem::path(); path.append("aspia"); return path; } bool initLoggingImpl(const LoggingSettings& settings, const std::filesystem::path& file_name) { std::scoped_lock lock(g_log_file_lock); g_log_file.close(); g_logging_destination = settings.destination; if (!(g_logging_destination & LOG_TO_FILE)) return true; std::filesystem::path file_dir = settings.log_dir; if (file_dir.empty()) file_dir = defaultLogFileDir(); if (file_dir.empty()) return false; std::error_code error_code; if (!std::filesystem::exists(file_dir, error_code)) { if (error_code) return false; if (!std::filesystem::create_directories(file_dir, error_code)) return false; } SystemTime time = SystemTime::now(); std::ostringstream file_name_stream; file_name_stream << file_name.c_str() << '-' << std::setfill('0') << std::setw(4) << time.year() << std::setw(2) << time.month() << std::setw(2) << time.day() << '-' << std::setw(2) << time.hour() << std::setw(2) << time.minute() << std::setw(2) << time.second() << '.' << std::setw(3) << time.millisecond() << ".log"; std::filesystem::path file_path(file_dir); file_path.append(file_name_stream.str()); g_log_file.open(file_path); if (!g_log_file.is_open()) return false; std::filesystem::file_time_type file_time = std::filesystem::last_write_time(file_path, error_code); if (!error_code) removeOldFiles(file_dir, file_time, settings.max_log_age); g_log_file_path = std::move(file_path); return true; } } // namespace // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have // an object of the correct type on the LHS of the unused part of the ternary // operator. std::ostream* g_swallow_stream; LoggingSettings::LoggingSettings() : destination(LOG_DEFAULT), min_log_level(LS_INFO), max_log_age(7) { // Nothing } bool initLogging(const LoggingSettings& settings) { std::filesystem::path exec_file_path; #if defined(OS_WIN) wchar_t buffer[MAX_PATH] = { 0 }; GetModuleFileNameExW(GetCurrentProcess(), nullptr, buffer, std::size(buffer)); exec_file_path = buffer; #elif defined(OS_LINUX) char buffer[PATH_MAX] = { 0 }; readlink("/proc/self/exe", buffer, std::size(buffer)); exec_file_path = buffer; #elif defined(OS_MAC) char buffer[PATH_MAX] = { 0 }; uint32_t buffer_size = std::size(buffer); _NSGetExecutablePath(buffer, &buffer_size); exec_file_path = buffer; #else #error Not implemented #endif std::filesystem::path file_name = exec_file_path.filename(); file_name.replace_extension(); if (!initLoggingImpl(settings, file_name)) return false; LOG(LS_INFO) << "Executable file: " << exec_file_path.c_str(); LOG(LS_INFO) << "Logging file: " << g_log_file_path; LOG(LS_INFO) << "Debugger present: " << (isDebuggerPresent() ? "Yes" : "No"); #if defined(NDEBUG) LOG(LS_INFO) << "Debug build: No"; #else LOG(LS_INFO) << "Debug build: Yes"; #endif // defined(NDEBUG) LOG(LS_INFO) << "Little endian: " << (EndianUtil::isLittle() ? "Yes" : "No"); LOG(LS_INFO) << "Logging started"; return true; } void shutdownLogging() { LOG(LS_INFO) << "Logging finished"; std::scoped_lock lock(g_log_file_lock); g_log_file.close(); } bool shouldCreateLogMessage(LoggingSeverity severity) { if (severity < g_min_log_level) return false; // Return true here unless we know ~LogMessage won't do anything. Note that // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even // when g_logging_destination is LOG_NONE. return g_logging_destination != LOG_NONE || severity >= LS_ERROR; } void makeCheckOpValueString(std::ostream* os, std::nullptr_t /* p */) { (*os) << "nullptr"; } std::string* makeCheckOpString(const int& v1, const int& v2, const char* names) { return makeCheckOpString<int, int>(v1, v2, names); } std::string* makeCheckOpString(const unsigned long& v1, const unsigned long& v2, const char* names) { return makeCheckOpString<unsigned long, unsigned long>(v1, v2, names); } std::string* makeCheckOpString(const unsigned int& v1, const unsigned int& v2, const char* names) { return makeCheckOpString<unsigned int, unsigned int>(v1, v2, names); } std::string* makeCheckOpString(const unsigned long long& v1, const unsigned long long& v2, const char* names) { return makeCheckOpString<unsigned long long, unsigned long long>(v1, v2, names); } std::string* makeCheckOpString(const unsigned long& v1, const unsigned int& v2, const char* names) { return makeCheckOpString<unsigned long, int>(v1, v2, names); } std::string* makeCheckOpString(const unsigned int& v1, const unsigned long& v2, const char* names) { return makeCheckOpString<unsigned int, unsigned long>(v1, v2, names); } std::string* makeCheckOpString(const std::string& v1, const std::string& v2, const char* names) { return makeCheckOpString<std::string, std::string>(v1, v2, names); } LogMessage::LogMessage(std::string_view file, int line, LoggingSeverity severity) : severity_(severity) { init(file, line); } LogMessage::LogMessage(std::string_view file, int line, const char* condition) : severity_(LS_FATAL) { init(file, line); stream_ << "Check failed: " << condition << ". "; } LogMessage::LogMessage(std::string_view file, int line, std::string* result) : severity_(LS_FATAL) { std::unique_ptr<std::string> result_deleter(result); init(file, line); stream_ << "Check failed: " << *result; } LogMessage::LogMessage(std::string_view file, int line, LoggingSeverity severity, std::string* result) : severity_(severity) { std::unique_ptr<std::string> result_deleter(result); init(file, line); stream_ << "Check failed: " << *result; } LogMessage::~LogMessage() { stream_ << std::endl; std::string message(stream_.str()); if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) { debugPrint(message.data()); fwrite(message.data(), message.size(), 1, stderr); fflush(stderr); } else if (severity_ >= LS_ERROR) { // When we're only outputting to a log file, above a certain log level, we // should still output to stderr so that we can better detect and diagnose // problems with unit tests, especially on the buildbots. fwrite(message.data(), message.size(), 1, stderr); fflush(stderr); } // Write to log file. if ((g_logging_destination & LOG_TO_FILE) != 0) { std::scoped_lock lock(g_log_file_lock); g_log_file.write(message.c_str(), message.size()); g_log_file.flush(); } if (severity_ == LS_FATAL) { // Crash the process. debugBreak(); } } // Writes the common header info to the stream. void LogMessage::init(std::string_view file, int line) { size_t last_slash_pos = file.find_last_of("\\/"); if (last_slash_pos != std::string_view::npos) file.remove_prefix(last_slash_pos + 1); SystemTime time = SystemTime::now(); stream_ << std::setfill('0') << std::setw(2) << time.hour() << ':' << std::setw(2) << time.minute() << ':' << std::setw(2) << time.second() << '.' << std::setw(3) << time.millisecond() << ' ' << std::this_thread::get_id() << ' ' << severityName(severity_) << ' ' << file.data() << ":" << line << "] "; message_start_ = stream_.str().length(); } ErrorLogMessage::ErrorLogMessage(std::string_view file, int line, LoggingSeverity severity, SystemError error) : error_(error), log_message_(file, line, severity) { // Nothing } ErrorLogMessage::~ErrorLogMessage() { stream() << ": " << error_.toString(); } void logErrorNotReached(const char* file, int line) { LogMessage(file, line, LS_ERROR).stream() << "NOTREACHED() hit."; } } // namespace base namespace std { #if defined(OS_WIN) std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) { return out << base::utf8FromWide(wstr); } std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) { return out << (wstr ? base::utf8FromWide(wstr) : "nullptr"); } #endif // defined(OS_WIN) std::ostream& operator<<(std::ostream& out, const char16_t* ustr) { return out << (ustr ? base::utf8FromUtf16(ustr) : "nullptr"); } std::ostream& operator<<(std::ostream& out, const std::u16string& ustr) { return out << base::utf8FromUtf16(ustr); } } // namespace std <|endoftext|>
<commit_before>// // CompositeTileImageProvider.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/23/14. // // #include "CompositeTileImageProvider.hpp" #include "TileImageListener.hpp" #include "Tile.hpp" #include "CompositeTileImageContribution.hpp" #include "IFactory.hpp" #include "ICanvas.hpp" #include "IImage.hpp" #include "FrameTasksExecutor.hpp" CompositeTileImageProvider::~CompositeTileImageProvider() { for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; child->_release(); } #ifdef JAVA_CODE super.dispose(); #endif } const TileImageContribution* CompositeTileImageProvider::contribution(const Tile* tile) { std::vector<const CompositeTileImageContribution::ChildContribution*> childrenContributions; for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; const TileImageContribution* childContribution = child->contribution(tile); if (childContribution != NULL) { // ignore previous contributions, they are covered by the current fullCoverage & Opaque contribution. const int childrenContributionsSize = childrenContributions.size(); if ((childrenContributionsSize > 0) && childContribution->isFullCoverageAndOpaque()) { for (int j = 0; j < childrenContributionsSize; j++) { const CompositeTileImageContribution::ChildContribution* previousContribution = childrenContributions[j]; #ifdef C_CODE delete previousContribution; #endif #ifdef JAVA_CODE previousContribution.dispose(); #endif } childrenContributions.clear(); } childrenContributions.push_back( new CompositeTileImageContribution::ChildContribution(i, childContribution) ); } } return CompositeTileImageContribution::create(childrenContributions); } CompositeTileImageProvider::ChildResult::ChildResult(const bool isError, const bool isCanceled, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const std::string& error) : _isError(isError), _isCanceled(isCanceled), _image(image), _imageId(imageId), _contribution(contribution), _error(error) { // TileImageContribution::retainContribution(_contribution); } CompositeTileImageProvider::ChildResult::~ChildResult() { delete _image; #warning DEBUG MEMORY TileImageContribution::releaseContribution(_contribution); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::image(const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { return new CompositeTileImageProvider::ChildResult(false , // isError false, // isCanceled image, imageId, contribution, "" // error ); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::error(const std::string& error) { return new CompositeTileImageProvider::ChildResult(true, // isError false, // isCanceled NULL, // image "", // imageId NULL, // contribution error); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::cancelation() { return new CompositeTileImageProvider::ChildResult(false, // isError true, // isCanceled NULL, // image "", // imageId NULL, // contribution "" // error ); } CompositeTileImageProvider::Composer::Composer(int width, int height, CompositeTileImageProvider* compositeTileImageProvider, const std::string& tileId, const Sector& tileSector, TileImageListener* listener, bool deleteListener, const CompositeTileImageContribution* compositeContribution, FrameTasksExecutor* frameTasksExecutor) : _width(width), _height(height), _compositeTileImageProvider(compositeTileImageProvider), _tileId(tileId), _listener(listener), _deleteListener(deleteListener), _compositeContribution(compositeContribution), _contributionsSize( compositeContribution->size() ), _frameTasksExecutor(frameTasksExecutor), _stepsDone(0), _anyError(false), _anyCancelation(false), _canceled(false), _tileSector(tileSector) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(_compositeContribution); for (int i = 0; i < _contributionsSize; i++) { _results.push_back( NULL ); } } CompositeTileImageProvider::Composer::~Composer() { for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; delete result; } TileImageContribution::releaseContribution(_compositeContribution); #ifdef JAVA_CODE super.dispose(); #endif } void CompositeTileImageProvider::Composer::cleanUp() { if (_deleteListener) { delete _listener; _listener = NULL; } _compositeTileImageProvider->composerDone(this); } void CompositeTileImageProvider::Composer::done() { if (_canceled) { cleanUp(); return; } if (_contributionsSize == 1) { const ChildResult* singleResult = _results[0]; if (singleResult->_isError) { _listener->imageCreationError(_tileId, singleResult->_error); } else if (singleResult->_isCanceled) { _listener->imageCreationCanceled(_tileId); } else { #warning MEMORY // singleResult->_contribution->_retain(); _listener->imageCreated(singleResult->_imageId, singleResult->_image->shallowCopy(), singleResult->_imageId, singleResult->_contribution); } cleanUp(); } else { if (_anyError) { std::string composedError = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* childResult = _results[i]; if (childResult->_isError) { composedError += childResult->_error + " "; } } _listener->imageCreationError(_tileId, composedError); cleanUp(); } else if (_anyCancelation) { _listener->imageCreationCanceled(_tileId); cleanUp(); } else { _frameTasksExecutor->addPreRenderTask(new ComposerFrameTask(this)); } } } RectangleF* CompositeTileImageProvider::Composer::getInnerRectangle(int wholeSectorWidth, int wholeSectorHeight, const Sector& wholeSector, const Sector& innerSector) const { if (wholeSector.isEquals(innerSector)){ return new RectangleF(0, 0, wholeSectorWidth, wholeSectorHeight); } const double widthFactor = innerSector._deltaLongitude.div(wholeSector._deltaLongitude); const double heightFactor = innerSector._deltaLatitude.div(wholeSector._deltaLatitude); const Vector2D lowerUV = wholeSector.getUVCoordinates(innerSector.getNW()); return new RectangleF((float) (lowerUV._x * wholeSectorWidth), (float) (lowerUV._y * wholeSectorHeight), (float) (widthFactor * wholeSectorWidth), (float) (heightFactor * wholeSectorHeight)); } void CompositeTileImageProvider::Composer::mixResult() { if (_canceled) { cleanUp(); return; } ICanvas* canvas = IFactory::instance()->createCanvas(); canvas->initialize(_width, _height); std::string imageId = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; imageId += result->_imageId + "|"; #warning //For now, we consider the whole image will appear on the tile (no source rect needed) const IImage* image = result->_image; const float alpha = result->_contribution->_alpha; if (result->_contribution->isFullCoverageAndOpaque()) { canvas->drawImage(image, 0, 0); } else { if (result->_contribution->isFullCoverage()) { canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT 0, 0, _width, _height, alpha); } else { const Sector* imageSector = result->_contribution->getSector(); const RectangleF* destRect = getInnerRectangle(_width, _height, _tileSector, *imageSector); //TEST MADRID // if (_tileSector.contains(Angle::fromDegrees(40.41677540051771), Angle::fromDegrees(-3.7037901976145804))){ // printf("TS: %s\nIS: %s\nR: %s\n",_tileSector.description().c_str(), // imageSector->description().c_str(), // rect->description().c_str()); // } canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT destRect->_x, destRect->_y, destRect->_width, destRect->_height, alpha); delete destRect; } } #warning MEMORY // result->_contribution->_release(); } _imageId = imageId; canvas->createImage(new ComposerImageListener(this), true); delete canvas; } bool CompositeTileImageProvider::ComposerFrameTask::isCanceled(const G3MRenderContext* rc) { return false; } void CompositeTileImageProvider::ComposerFrameTask::execute(const G3MRenderContext* rc) { _composer->mixResult(); } void CompositeTileImageProvider::Composer::imageCreated(const IImage* image) { const CompositeTileImageContribution* compositeContribution = _compositeContribution; _compositeContribution = NULL; // the _compositeContribution ownership moved to the listener _listener->imageCreated(_tileId, image, _imageId, compositeContribution); cleanUp(); } void CompositeTileImageProvider::Composer::stepDone() { _stepsDone++; if (_stepsDone == _contributionsSize) { done(); } } void CompositeTileImageProvider::Composer::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const int index) { #warning DEBUG MEMORY - DIEGO AT WORK -> moves to ChildResult::image() TileImageContribution::retainContribution(contribution); _results[index] = ChildResult::image(image, imageId, contribution); stepDone(); } void CompositeTileImageProvider::Composer::imageCreationError(const std::string& error, const int index) { _results[index] = ChildResult::error(error); _anyError = true; stepDone(); } void CompositeTileImageProvider::Composer::imageCreationCanceled(const int index) { _results[index] = ChildResult::cancelation(); _anyCancelation = true; stepDone(); } void CompositeTileImageProvider::Composer::cancel(const std::string& tileId) { _canceled = true; _compositeTileImageProvider->cancelChildren(tileId, _compositeContribution); } void CompositeTileImageProvider::ChildTileImageListener::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { _composer->imageCreated(tileId, image, imageId, contribution, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationError(const std::string& tileId, const std::string& error) { _composer->imageCreationError(error, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationCanceled(const std::string& tileId) { _composer->imageCreationCanceled(_index); } void CompositeTileImageProvider::create(const Tile* tile, const TileImageContribution* contribution, const Vector2I& resolution, long long tileDownloadPriority, bool logDownloadActivity, TileImageListener* listener, bool deleteListener, FrameTasksExecutor* frameTasksExecutor) { const CompositeTileImageContribution* compositeContribution = (const CompositeTileImageContribution*) contribution; const std::string tileId = tile->_id; Composer* composer = new Composer(resolution._x, resolution._y, this, tileId, tile->_sector, listener, deleteListener, compositeContribution, frameTasksExecutor); _composers[ tileId ] = composer; const int contributionsSize = compositeContribution->size(); for (int i = 0; i < contributionsSize; i++) { const CompositeTileImageContribution::ChildContribution* childContribution = compositeContribution->get(i); TileImageProvider* child = _children[ childContribution->_childIndex ]; #warning DEBUG MEMORY childContribution->_contribution->_retain(); child->create(tile, childContribution->_contribution, resolution, tileDownloadPriority, logDownloadActivity, new ChildTileImageListener(composer, i), true, frameTasksExecutor); } } void CompositeTileImageProvider::cancel(const std::string& tileId) { #ifdef C_CODE if (_composers.find(tileId) != _composers.end()) { Composer* composer = _composers[tileId]; composer->cancel(tileId); _composers.erase(tileId); } #endif #ifdef JAVA_CODE final Composer composer = _composers.remove(tileId); if (composer != null) { composer.cancel(tileId); } #endif } void CompositeTileImageProvider::composerDone(Composer* composer) { _composers.erase( composer->_tileId ); composer->_release(); } void CompositeTileImageProvider::cancelChildren(const std::string& tileId, const CompositeTileImageContribution* compositeContribution) { const int contributionsSize = compositeContribution->size(); // store all the indexes before calling child->cancel(). // child->cancel() can force the deletion of the builder (and in order the deletion of compositeContribution) int* indexes = new int[contributionsSize]; for (int i = 0; i < contributionsSize; i++) { indexes[i] = compositeContribution->get(i)->_childIndex; } for (int i = 0; i < contributionsSize; i++) { TileImageProvider* child = _children[ indexes[i] ]; child->cancel(tileId); } delete [] indexes; } <commit_msg>Tile's image creation refactoring - NOT YET USABLE<commit_after>// // CompositeTileImageProvider.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/23/14. // // #include "CompositeTileImageProvider.hpp" #include "TileImageListener.hpp" #include "Tile.hpp" #include "CompositeTileImageContribution.hpp" #include "IFactory.hpp" #include "ICanvas.hpp" #include "IImage.hpp" #include "FrameTasksExecutor.hpp" CompositeTileImageProvider::~CompositeTileImageProvider() { for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; child->_release(); } #ifdef JAVA_CODE super.dispose(); #endif } const TileImageContribution* CompositeTileImageProvider::contribution(const Tile* tile) { std::vector<const CompositeTileImageContribution::ChildContribution*> childrenContributions; for (int i = 0; i < _childrenSize; i++) { TileImageProvider* child = _children[i]; const TileImageContribution* childContribution = child->contribution(tile); if (childContribution != NULL) { // ignore previous contributions, they are covered by the current fullCoverage & Opaque contribution. const int childrenContributionsSize = childrenContributions.size(); if ((childrenContributionsSize > 0) && childContribution->isFullCoverageAndOpaque()) { for (int j = 0; j < childrenContributionsSize; j++) { const CompositeTileImageContribution::ChildContribution* previousContribution = childrenContributions[j]; #ifdef C_CODE delete previousContribution; #endif #ifdef JAVA_CODE previousContribution.dispose(); #endif } childrenContributions.clear(); } childrenContributions.push_back( new CompositeTileImageContribution::ChildContribution(i, childContribution) ); } } return CompositeTileImageContribution::create(childrenContributions); } CompositeTileImageProvider::ChildResult::ChildResult(const bool isError, const bool isCanceled, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const std::string& error) : _isError(isError), _isCanceled(isCanceled), _image(image), _imageId(imageId), _contribution(contribution), _error(error) { // TileImageContribution::retainContribution(_contribution); } CompositeTileImageProvider::ChildResult::~ChildResult() { delete _image; #warning DEBUG MEMORY TileImageContribution::releaseContribution(_contribution); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::image(const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { return new CompositeTileImageProvider::ChildResult(false , // isError false, // isCanceled image, imageId, contribution, "" // error ); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::error(const std::string& error) { return new CompositeTileImageProvider::ChildResult(true, // isError false, // isCanceled NULL, // image "", // imageId NULL, // contribution error); } const CompositeTileImageProvider::ChildResult* CompositeTileImageProvider::ChildResult::cancelation() { return new CompositeTileImageProvider::ChildResult(false, // isError true, // isCanceled NULL, // image "", // imageId NULL, // contribution "" // error ); } CompositeTileImageProvider::Composer::Composer(int width, int height, CompositeTileImageProvider* compositeTileImageProvider, const std::string& tileId, const Sector& tileSector, TileImageListener* listener, bool deleteListener, const CompositeTileImageContribution* compositeContribution, FrameTasksExecutor* frameTasksExecutor) : _width(width), _height(height), _compositeTileImageProvider(compositeTileImageProvider), _tileId(tileId), _listener(listener), _deleteListener(deleteListener), _compositeContribution(compositeContribution), _contributionsSize( compositeContribution->size() ), _frameTasksExecutor(frameTasksExecutor), _stepsDone(0), _anyError(false), _anyCancelation(false), _canceled(false), _tileSector(tileSector) { #warning DEBUG MEMORY // TileImageContribution::retainContribution(_compositeContribution); for (int i = 0; i < _contributionsSize; i++) { _results.push_back( NULL ); } } CompositeTileImageProvider::Composer::~Composer() { for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; delete result; } TileImageContribution::releaseContribution(_compositeContribution); #ifdef JAVA_CODE super.dispose(); #endif } void CompositeTileImageProvider::Composer::cleanUp() { if (_deleteListener) { delete _listener; _listener = NULL; } _compositeTileImageProvider->composerDone(this); } void CompositeTileImageProvider::Composer::done() { if (_canceled) { cleanUp(); return; } if (_contributionsSize == 1) { const ChildResult* singleResult = _results[0]; if (singleResult->_isError) { _listener->imageCreationError(_tileId, singleResult->_error); } else if (singleResult->_isCanceled) { _listener->imageCreationCanceled(_tileId); } else { #warning MEMORY // singleResult->_contribution->_retain(); _listener->imageCreated(singleResult->_imageId, singleResult->_image->shallowCopy(), singleResult->_imageId, singleResult->_contribution); } cleanUp(); } else { if (_anyError) { std::string composedError = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* childResult = _results[i]; if (childResult->_isError) { composedError += childResult->_error + " "; } } _listener->imageCreationError(_tileId, composedError); cleanUp(); } else if (_anyCancelation) { _listener->imageCreationCanceled(_tileId); cleanUp(); } else { _frameTasksExecutor->addPreRenderTask(new ComposerFrameTask(this)); } } } RectangleF* CompositeTileImageProvider::Composer::getInnerRectangle(int wholeSectorWidth, int wholeSectorHeight, const Sector& wholeSector, const Sector& innerSector) const { if (wholeSector.isEquals(innerSector)){ return new RectangleF(0, 0, wholeSectorWidth, wholeSectorHeight); } const double widthFactor = innerSector._deltaLongitude.div(wholeSector._deltaLongitude); const double heightFactor = innerSector._deltaLatitude.div(wholeSector._deltaLatitude); const Vector2D lowerUV = wholeSector.getUVCoordinates(innerSector.getNW()); return new RectangleF((float) (lowerUV._x * wholeSectorWidth), (float) (lowerUV._y * wholeSectorHeight), (float) (widthFactor * wholeSectorWidth), (float) (heightFactor * wholeSectorHeight)); } void CompositeTileImageProvider::Composer::mixResult() { if (_canceled) { cleanUp(); return; } ICanvas* canvas = IFactory::instance()->createCanvas(); canvas->initialize(_width, _height); std::string imageId = ""; for (int i = 0; i < _contributionsSize; i++) { const ChildResult* result = _results[i]; imageId += result->_imageId + "|"; #warning //For now, we consider the whole image will appear on the tile (no source rect needed) const IImage* image = result->_image; const float alpha = result->_contribution->_alpha; if (result->_contribution->isFullCoverageAndOpaque()) { canvas->drawImage(image, 0, 0); } else { if (result->_contribution->isFullCoverage()) { canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT 0, 0, _width, _height, alpha); } else { const Sector* imageSector = result->_contribution->getSector(); const RectangleF* destRect = getInnerRectangle(_width, _height, _tileSector, *imageSector); //TEST MADRID // if (_tileSector.contains(Angle::fromDegrees(40.41677540051771), Angle::fromDegrees(-3.7037901976145804))){ // printf("TS: %s\nIS: %s\nR: %s\n",_tileSector.description().c_str(), // imageSector->description().c_str(), // rect->description().c_str()); // } canvas->drawImage(image, //SRC RECT 0,0, image->getWidth(), image->getHeight(), //DEST RECT destRect->_x, destRect->_y, destRect->_width, destRect->_height, alpha); delete destRect; } } #warning MEMORY // result->_contribution->_release(); } _imageId = imageId; canvas->createImage(new ComposerImageListener(this), true); delete canvas; } bool CompositeTileImageProvider::ComposerFrameTask::isCanceled(const G3MRenderContext* rc) { return false; } void CompositeTileImageProvider::ComposerFrameTask::execute(const G3MRenderContext* rc) { _composer->mixResult(); } void CompositeTileImageProvider::Composer::imageCreated(const IImage* image) { const CompositeTileImageContribution* compositeContribution = _compositeContribution; _compositeContribution = NULL; // the _compositeContribution ownership moved to the listener _listener->imageCreated(_tileId, image, _imageId, compositeContribution); cleanUp(); } void CompositeTileImageProvider::Composer::stepDone() { _stepsDone++; if (_stepsDone == _contributionsSize) { done(); } } void CompositeTileImageProvider::Composer::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution, const int index) { #warning DEBUG MEMORY - DIEGO AT WORK -> moves to ChildResult::image() // TileImageContribution::retainContribution(contribution); _results[index] = ChildResult::image(image, imageId, contribution); stepDone(); } void CompositeTileImageProvider::Composer::imageCreationError(const std::string& error, const int index) { _results[index] = ChildResult::error(error); _anyError = true; stepDone(); } void CompositeTileImageProvider::Composer::imageCreationCanceled(const int index) { _results[index] = ChildResult::cancelation(); _anyCancelation = true; stepDone(); } void CompositeTileImageProvider::Composer::cancel(const std::string& tileId) { _canceled = true; _compositeTileImageProvider->cancelChildren(tileId, _compositeContribution); } void CompositeTileImageProvider::ChildTileImageListener::imageCreated(const std::string& tileId, const IImage* image, const std::string& imageId, const TileImageContribution* contribution) { _composer->imageCreated(tileId, image, imageId, contribution, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationError(const std::string& tileId, const std::string& error) { _composer->imageCreationError(error, _index); } void CompositeTileImageProvider::ChildTileImageListener::imageCreationCanceled(const std::string& tileId) { _composer->imageCreationCanceled(_index); } void CompositeTileImageProvider::create(const Tile* tile, const TileImageContribution* contribution, const Vector2I& resolution, long long tileDownloadPriority, bool logDownloadActivity, TileImageListener* listener, bool deleteListener, FrameTasksExecutor* frameTasksExecutor) { const CompositeTileImageContribution* compositeContribution = (const CompositeTileImageContribution*) contribution; const std::string tileId = tile->_id; Composer* composer = new Composer(resolution._x, resolution._y, this, tileId, tile->_sector, listener, deleteListener, compositeContribution, frameTasksExecutor); _composers[ tileId ] = composer; const int contributionsSize = compositeContribution->size(); for (int i = 0; i < contributionsSize; i++) { const CompositeTileImageContribution::ChildContribution* childContribution = compositeContribution->get(i); TileImageProvider* child = _children[ childContribution->_childIndex ]; #warning DEBUG MEMORY childContribution->_contribution->_retain(); child->create(tile, childContribution->_contribution, resolution, tileDownloadPriority, logDownloadActivity, new ChildTileImageListener(composer, i), true, frameTasksExecutor); } } void CompositeTileImageProvider::cancel(const std::string& tileId) { #ifdef C_CODE if (_composers.find(tileId) != _composers.end()) { Composer* composer = _composers[tileId]; composer->cancel(tileId); _composers.erase(tileId); } #endif #ifdef JAVA_CODE final Composer composer = _composers.remove(tileId); if (composer != null) { composer.cancel(tileId); } #endif } void CompositeTileImageProvider::composerDone(Composer* composer) { _composers.erase( composer->_tileId ); composer->_release(); } void CompositeTileImageProvider::cancelChildren(const std::string& tileId, const CompositeTileImageContribution* compositeContribution) { const int contributionsSize = compositeContribution->size(); // store all the indexes before calling child->cancel(). // child->cancel() can force the deletion of the builder (and in order the deletion of compositeContribution) int* indexes = new int[contributionsSize]; for (int i = 0; i < contributionsSize; i++) { indexes[i] = compositeContribution->get(i)->_childIndex; } for (int i = 0; i < contributionsSize; i++) { TileImageProvider* child = _children[ indexes[i] ]; child->cancel(tileId); } delete [] indexes; } <|endoftext|>
<commit_before>#include "xchainer/backprop_mode.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/constant.h" #include "xchainer/context.h" #include "xchainer/graph.h" namespace xchainer { namespace backprop_mode_detail { thread_local BackpropModeStack* t_backprop_mode_stack{nullptr}; template <bool kModeFlag> void BackpropModeScope<kModeFlag>::BackpropModeScopeImpl(nonstd::optional<std::vector<GraphId>> graph_ids, Context& context) { // The outer-most scope creates an instance of BackpropModeStack. if (t_backprop_mode_stack == nullptr) { t_backprop_mode_stack = new BackpropModeStack{}; is_outermost_ = true; } if (graph_ids.has_value()) { n_ = graph_ids->size(); for (GraphId& graph_id : *graph_ids) { t_backprop_mode_stack->emplace_back(context, std::move(graph_id), kModeFlag); } } else { n_ = 1; t_backprop_mode_stack->emplace_back(context, nonstd::nullopt, kModeFlag); } } template <bool kModeFlag> BackpropModeScope<kModeFlag>::~BackpropModeScope() { assert(t_backprop_mode_stack != nullptr); assert(t_backprop_mode_stack->size() >= n_); // Recover thread local variable to nullptr on exiting from the outer-most scope. if (is_outermost_) { assert(t_backprop_mode_stack->size() == n_); delete t_backprop_mode_stack; t_backprop_mode_stack = nullptr; } else { t_backprop_mode_stack->erase(t_backprop_mode_stack->end() - n_, t_backprop_mode_stack->end()); } } } // namespace backprop_mode_detail bool IsBackpropRequired(const GraphId& graph_id, Context& context) { backprop_mode_detail::BackpropModeStack* bms = backprop_mode_detail::t_backprop_mode_stack; if (bms == nullptr) { // No backprop scopes have been created and backprop is thus always required, per default. return true; } auto it = std::find_if(bms->rbegin(), bms->rend(), [&graph_id, &context](const internal::BackpropMode& bm) { return &context == &bm.context() && (!bm.graph_id().has_value() || graph_id == *bm.graph_id()); }); if (it != bms->rend()) { return it->backprop(); } return true; // Per default. } bool IsBackpropRequired(const Array& array, const GraphId& graph_id) { if (graph_id == kAnyGraphId) { const std::vector<std::shared_ptr<ArrayNode>>& array_nodes = array.nodes(); return std::any_of(array_nodes.begin(), array_nodes.end(), [&array](const std::shared_ptr<const ArrayNode>& array_node) { return IsBackpropRequired(array_node->graph_id(), array.device().context()); }); } else if (internal::HasArrayNode(array, graph_id)) { return IsBackpropRequired(graph_id, array.device().context()); } return false; } } // namespace xchainer <commit_msg>Only lambda-capture what is necessary<commit_after>#include "xchainer/backprop_mode.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/constant.h" #include "xchainer/context.h" #include "xchainer/graph.h" namespace xchainer { namespace backprop_mode_detail { thread_local BackpropModeStack* t_backprop_mode_stack{nullptr}; template <bool kModeFlag> void BackpropModeScope<kModeFlag>::BackpropModeScopeImpl(nonstd::optional<std::vector<GraphId>> graph_ids, Context& context) { // The outer-most scope creates an instance of BackpropModeStack. if (t_backprop_mode_stack == nullptr) { t_backprop_mode_stack = new BackpropModeStack{}; is_outermost_ = true; } if (graph_ids.has_value()) { n_ = graph_ids->size(); for (GraphId& graph_id : *graph_ids) { t_backprop_mode_stack->emplace_back(context, std::move(graph_id), kModeFlag); } } else { n_ = 1; t_backprop_mode_stack->emplace_back(context, nonstd::nullopt, kModeFlag); } } template <bool kModeFlag> BackpropModeScope<kModeFlag>::~BackpropModeScope() { assert(t_backprop_mode_stack != nullptr); assert(t_backprop_mode_stack->size() >= n_); // Recover thread local variable to nullptr on exiting from the outer-most scope. if (is_outermost_) { assert(t_backprop_mode_stack->size() == n_); delete t_backprop_mode_stack; t_backprop_mode_stack = nullptr; } else { t_backprop_mode_stack->erase(t_backprop_mode_stack->end() - n_, t_backprop_mode_stack->end()); } } } // namespace backprop_mode_detail bool IsBackpropRequired(const GraphId& graph_id, Context& context) { backprop_mode_detail::BackpropModeStack* bms = backprop_mode_detail::t_backprop_mode_stack; if (bms == nullptr) { // No backprop scopes have been created and backprop is thus always required, per default. return true; } auto it = std::find_if(bms->rbegin(), bms->rend(), [&graph_id, &context](const internal::BackpropMode& bm) { return &context == &bm.context() && (!bm.graph_id().has_value() || graph_id == *bm.graph_id()); }); if (it != bms->rend()) { return it->backprop(); } return true; // Per default. } bool IsBackpropRequired(const Array& array, const GraphId& graph_id) { if (graph_id == kAnyGraphId) { Context& context = array.device().context(); const std::vector<std::shared_ptr<ArrayNode>>& array_nodes = array.nodes(); return std::any_of(array_nodes.begin(), array_nodes.end(), [&context](const std::shared_ptr<const ArrayNode>& array_node) { return IsBackpropRequired(array_node->graph_id(), context); }); } else if (internal::HasArrayNode(array, graph_id)) { return IsBackpropRequired(graph_id, array.device().context()); } return false; } } // namespace xchainer <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/language_order_table_model.h" #include "app/l10n_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" LanguageOrderTableModel::LanguageOrderTableModel() : observer_(NULL) { } void LanguageOrderTableModel::SetAcceptLanguagesString( const std::string& language_list) { std::vector<std::string> languages_vector; ListToVector(language_list, &languages_vector); for (int i = 0; i < static_cast<int>(languages_vector.size()); i++) { Add(languages_vector.at(i)); } } void LanguageOrderTableModel::SetObserver(TableModelObserver* observer) { observer_ = observer; } std::wstring LanguageOrderTableModel::GetText(int row, int column_id) { DCHECK(row >= 0 && row < RowCount()); const std::string app_locale = g_browser_process->GetApplicationLocale(); return UTF16ToWide(l10n_util::GetDisplayNameForLocale(languages_.at(row), app_locale, true)); } bool LanguageOrderTableModel::Add(const std::string& language) { if (language.empty()) return false; // Check for selecting duplicated language. for (std::vector<std::string>::const_iterator cit = languages_.begin(); cit != languages_.end(); ++cit) if (*cit == language) return false; languages_.push_back(language); if (observer_) observer_->OnItemsAdded(RowCount() - 1, 1); return true; } void LanguageOrderTableModel::Remove(int index) { DCHECK(index >= 0 && index < RowCount()); languages_.erase(languages_.begin() + index); if (observer_) observer_->OnItemsRemoved(index, 1); } int LanguageOrderTableModel::GetIndex(const std::string& language) { if (language.empty()) return -1; int index = 0; for (std::vector<std::string>::const_iterator cit = languages_.begin(); cit != languages_.end(); ++cit) { if (*cit == language) return index; index++; } return -1; } void LanguageOrderTableModel::MoveDown(int index) { if (index < 0 || index >= RowCount() - 1) return; std::string item = languages_.at(index); languages_.erase(languages_.begin() + index); if (index == RowCount() - 1) languages_.push_back(item); else languages_.insert(languages_.begin() + index + 1, item); if (observer_) observer_->OnItemsChanged(0, RowCount()); } void LanguageOrderTableModel::MoveUp(int index) { if (index <= 0 || index >= static_cast<int>(languages_.size())) return; std::string item = languages_.at(index); languages_.erase(languages_.begin() + index); languages_.insert(languages_.begin() + index - 1, item); if (observer_) observer_->OnItemsChanged(0, RowCount()); } int LanguageOrderTableModel::RowCount() { return static_cast<int>(languages_.size()); } void LanguageOrderTableModel::ListToVector(const std::string& list, std::vector<std::string>* vector) { SplitString(list, ',', vector); } std::string LanguageOrderTableModel::VectorToList( const std::vector<std::string>& vector) { std::string list; for (int i = 0 ; i < static_cast<int>(vector.size()) ; i++) { list += vector.at(i); if (i != static_cast<int>(vector.size()) - 1) list += ','; } return list; } <commit_msg>Enable live update of language list The old way this was written was trying to re-use the Add() method to "merge" the new langauge string with the existing list. But in the case when a syncd browser sends a re-ordering or delete change, this would not detect the change and never fire the observer. I changed this to simply make SetAcceptLanguagesString replace the current langages_ list.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/language_order_table_model.h" #include <set> #include "app/l10n_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" LanguageOrderTableModel::LanguageOrderTableModel() : observer_(NULL) { } void LanguageOrderTableModel::SetAcceptLanguagesString( const std::string& language_list) { std::vector<std::string> languages_vector; ListToVector(language_list, &languages_vector); languages_.clear(); std::set<std::string> added; for (int i = 0; i < static_cast<int>(languages_vector.size()); i++) { const std::string& language(languages_vector.at(i)); if (!language.empty() && added.count(language) == 0) { languages_.push_back(language); added.insert(language); } } if (observer_) observer_->OnModelChanged(); } void LanguageOrderTableModel::SetObserver(TableModelObserver* observer) { observer_ = observer; } std::wstring LanguageOrderTableModel::GetText(int row, int column_id) { DCHECK(row >= 0 && row < RowCount()); const std::string app_locale = g_browser_process->GetApplicationLocale(); return UTF16ToWide(l10n_util::GetDisplayNameForLocale(languages_.at(row), app_locale, true)); } bool LanguageOrderTableModel::Add(const std::string& language) { if (language.empty()) return false; // Check for selecting duplicated language. for (std::vector<std::string>::const_iterator cit = languages_.begin(); cit != languages_.end(); ++cit) if (*cit == language) return false; languages_.push_back(language); if (observer_) observer_->OnItemsAdded(RowCount() - 1, 1); return true; } void LanguageOrderTableModel::Remove(int index) { DCHECK(index >= 0 && index < RowCount()); languages_.erase(languages_.begin() + index); if (observer_) observer_->OnItemsRemoved(index, 1); } int LanguageOrderTableModel::GetIndex(const std::string& language) { if (language.empty()) return -1; int index = 0; for (std::vector<std::string>::const_iterator cit = languages_.begin(); cit != languages_.end(); ++cit) { if (*cit == language) return index; index++; } return -1; } void LanguageOrderTableModel::MoveDown(int index) { if (index < 0 || index >= RowCount() - 1) return; std::string item = languages_.at(index); languages_.erase(languages_.begin() + index); if (index == RowCount() - 1) languages_.push_back(item); else languages_.insert(languages_.begin() + index + 1, item); if (observer_) observer_->OnItemsChanged(0, RowCount()); } void LanguageOrderTableModel::MoveUp(int index) { if (index <= 0 || index >= static_cast<int>(languages_.size())) return; std::string item = languages_.at(index); languages_.erase(languages_.begin() + index); languages_.insert(languages_.begin() + index - 1, item); if (observer_) observer_->OnItemsChanged(0, RowCount()); } int LanguageOrderTableModel::RowCount() { return static_cast<int>(languages_.size()); } void LanguageOrderTableModel::ListToVector(const std::string& list, std::vector<std::string>* vector) { SplitString(list, ',', vector); } std::string LanguageOrderTableModel::VectorToList( const std::vector<std::string>& vector) { std::string list; for (int i = 0 ; i < static_cast<int>(vector.size()) ; i++) { list += vector.at(i); if (i != static_cast<int>(vector.size()) - 1) list += ','; } return list; } <|endoftext|>
<commit_before><commit_msg>"flip_over_serum_line"<commit_after><|endoftext|>
<commit_before>// Material.cpp #include "Material.h" #include "CycException.h" #include "Timer.h" #include "Logger.h" #include <cmath> #include <vector> using namespace std; std::vector<mat_rsrc_ptr> Material::materials_; bool Material::decay_wanted_ = false; int Material::decay_interval_ = 1; Table *Material::material_table = new Table("MaterialHistory"); bool Material::type_is_logged_ = false; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Material::Material() { last_update_time_ = TI->time(); CLOG(LEV_INFO4) << "Material created {"; print(); CLOG(LEV_INFO4) << "}"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Material::Material(IsoVector comp) { last_update_time_ = TI->time(); iso_vector_ = comp; CLOG(LEV_INFO4) << "Material created {"; print(); CLOG(LEV_INFO4) << "}"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Material::Material(const Material& other) { iso_vector_ = other.iso_vector_; last_update_time_ = other.last_update_time_; CLOG(LEV_INFO4) << "Material created {"; print(); CLOG(LEV_INFO4) << "}"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::absorb(mat_rsrc_ptr matToAdd) { // @gidden figure out how to handle this with the database - mjg // Get the given Material's composition. IsoVector vec_to_add = matToAdd->isoVector(); iso_vector_ = iso_vector_ + vec_to_add; CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " absorbed material ID=" << matToAdd->ID() << "."; CLOG(LEV_DEBUG3) << "New Material state:"; print(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mat_rsrc_ptr Material::extract(double mass) { IsoVector new_comp = iso_vector_; new_comp.setMass(mass); iso_vector_ = iso_vector_ - new_comp; CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had " << mass << " kg extracted from it. New mass=" << quantity() << " kg."; mat_rsrc_ptr new_mat = new Material(new_comp); // we just split a resource, so keep track of the original for book keeping new_mat->setOriginalID( this->originalID() ); return mat_rsrc_ptr(new_mat); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mat_rsrc_ptr Material::extract(IsoVector rem_comp) { iso_vector_ = iso_vector_ - rem_comp; CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had vector extracted."; CLOG(LEV_DEBUG3) << "New Material state:"; print(); mat_rsrc_ptr new_mat = new Material(rem_comp); // we just split a resource, so keep track of the original for book keeping new_mat->setOriginalID( this->originalID() ); return mat_rsrc_ptr(new_mat); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::print() { CLOG(LEV_INFO4) << "Material ID=" << ID_ << ", quantity=" << quantity() << ", units=" << units(); CLOG(LEV_INFO5) << "Composition {"; std::vector<std::string>::iterator entry; std::vector<std::string> entries = iso_vector_.compStrings(); for (entry = entries.begin(); entry != entries.end(); entry++) { CLOG(LEV_INFO5) << " " << *entry; } CLOG(LEV_INFO5) << "}"; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::setQuantity(double quantity) { iso_vector_.setMass(quantity); CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had mass set to" << quantity << " kg"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - rsrc_ptr Material::clone() { CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " was cloned."; print(); rsrc_ptr mat(new Material(*this)); return mat; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Material::checkQuality(rsrc_ptr other){ // This will be false until proven true bool toRet = false; IsoVector lhs_vec = iso_vector_; try { // Make sure the other is a material mat_rsrc_ptr mat = boost::dynamic_pointer_cast<Material>(other); if (mat) { toRet = true; } } catch (...) { } return toRet; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Material::checkQuantityEqual(rsrc_ptr other) { // This will be false until proven true bool toRet = false; // Make sure the other is a material try{ // check mass values double second_qty = boost::dynamic_pointer_cast<Material>(other)->quantity(); toRet=( abs(quantity() - second_qty) < EPS_KG); } catch (std::exception e) { } return toRet; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Material::checkQuantityGT(rsrc_ptr other){ // true if the total atoms in the other is greater than in the base. // This will be true until proven false bool toRet = false; // Make sure the other is a material try{ // check mass values double second_qty = boost::dynamic_pointer_cast<Material>(other)->quantity(); toRet = second_qty - quantity() > EPS_KG; } catch (std::exception& e){ } return toRet; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::decay() { int curr_time = TI->time(); int delta_time = curr_time - last_update_time_; iso_vector_.executeDecay(delta_time); last_update_time_ = curr_time; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::decayMaterials(int time) { // if decay is on if (decay_wanted_) { // and if (time(mod interval)==0) if (time % decay_interval_ == 0) { // acquire a list of all materials for (vector<mat_rsrc_ptr>::iterator mat = materials_.begin(); mat != materials_.end(); mat++){ // and decay each of them (*mat)->decay(); } } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::setDecay(int dec) { if ( dec <= 0 ) { decay_wanted_ = false; } else if ( dec > 0 ) { decay_wanted_ = true; decay_interval_ = dec; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::define_table() { // declare the table columns column id("ID","INTEGER"); column state_id("StateID","INTEGER"); column time("Time","INTEGER"); // declare the table's primary key primary_key pk; pk.push_back("ID"), pk.push_back("StateID"); material_table->setPrimaryKey(pk); // add columns to the table material_table->addColumn(id); material_table->addColumn(state_id); material_table->addColumn(time); // add foreign keys foreign_key_ref *fkref; foreign_key *fk; key myk, theirk; // IsotopicStates table foreign keys theirk.push_back("ID"); fkref = new foreign_key_ref("IsotopicStates",theirk); // the state id myk.push_back("StateID"); fk = new foreign_key(myk, (*fkref) ); material_table->addForeignKey( (*fk) ); // stated id references isotopicstates' id // we've now defined the table material_table->tableDefined(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::addToTable(){ // if we haven't logged an material yet, define the table if ( !material_table->defined() ) Material::define_table(); // make a row // declare data data an_id( this->ID() ), a_state( 1 ), // @MJG FLAG need to do state recording a_time( TI->time() ); // declare entries entry id("ID",an_id), state("StateID",a_state), time("Time",a_time); // declare row row aRow; aRow.push_back(id), aRow.push_back(state), aRow.push_back(time); // add the row material_table->addRow(aRow); // record this primary key pkref_.push_back(id); pkref_.push_back(state); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::setOriginatorID(int id){ originatorID_ = id; this->Resource::addToTable(); this->Material::addToTable(); } <commit_msg>added foreign key designation to material history table<commit_after>// Material.cpp #include "Material.h" #include "CycException.h" #include "Timer.h" #include "Logger.h" #include <cmath> #include <vector> using namespace std; std::vector<mat_rsrc_ptr> Material::materials_; bool Material::decay_wanted_ = false; int Material::decay_interval_ = 1; Table *Material::material_table = new Table("MaterialHistory"); bool Material::type_is_logged_ = false; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Material::Material() { last_update_time_ = TI->time(); CLOG(LEV_INFO4) << "Material created {"; print(); CLOG(LEV_INFO4) << "}"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Material::Material(IsoVector comp) { last_update_time_ = TI->time(); iso_vector_ = comp; CLOG(LEV_INFO4) << "Material created {"; print(); CLOG(LEV_INFO4) << "}"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Material::Material(const Material& other) { iso_vector_ = other.iso_vector_; last_update_time_ = other.last_update_time_; CLOG(LEV_INFO4) << "Material created {"; print(); CLOG(LEV_INFO4) << "}"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::absorb(mat_rsrc_ptr matToAdd) { // @gidden figure out how to handle this with the database - mjg // Get the given Material's composition. IsoVector vec_to_add = matToAdd->isoVector(); iso_vector_ = iso_vector_ + vec_to_add; CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " absorbed material ID=" << matToAdd->ID() << "."; CLOG(LEV_DEBUG3) << "New Material state:"; print(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mat_rsrc_ptr Material::extract(double mass) { IsoVector new_comp = iso_vector_; new_comp.setMass(mass); iso_vector_ = iso_vector_ - new_comp; CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had " << mass << " kg extracted from it. New mass=" << quantity() << " kg."; mat_rsrc_ptr new_mat = new Material(new_comp); // we just split a resource, so keep track of the original for book keeping new_mat->setOriginalID( this->originalID() ); return mat_rsrc_ptr(new_mat); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mat_rsrc_ptr Material::extract(IsoVector rem_comp) { iso_vector_ = iso_vector_ - rem_comp; CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had vector extracted."; CLOG(LEV_DEBUG3) << "New Material state:"; print(); mat_rsrc_ptr new_mat = new Material(rem_comp); // we just split a resource, so keep track of the original for book keeping new_mat->setOriginalID( this->originalID() ); return mat_rsrc_ptr(new_mat); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::print() { CLOG(LEV_INFO4) << "Material ID=" << ID_ << ", quantity=" << quantity() << ", units=" << units(); CLOG(LEV_INFO5) << "Composition {"; std::vector<std::string>::iterator entry; std::vector<std::string> entries = iso_vector_.compStrings(); for (entry = entries.begin(); entry != entries.end(); entry++) { CLOG(LEV_INFO5) << " " << *entry; } CLOG(LEV_INFO5) << "}"; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::setQuantity(double quantity) { iso_vector_.setMass(quantity); CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " had mass set to" << quantity << " kg"; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - rsrc_ptr Material::clone() { CLOG(LEV_DEBUG2) << "Material ID=" << ID_ << " was cloned."; print(); rsrc_ptr mat(new Material(*this)); return mat; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Material::checkQuality(rsrc_ptr other){ // This will be false until proven true bool toRet = false; IsoVector lhs_vec = iso_vector_; try { // Make sure the other is a material mat_rsrc_ptr mat = boost::dynamic_pointer_cast<Material>(other); if (mat) { toRet = true; } } catch (...) { } return toRet; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Material::checkQuantityEqual(rsrc_ptr other) { // This will be false until proven true bool toRet = false; // Make sure the other is a material try{ // check mass values double second_qty = boost::dynamic_pointer_cast<Material>(other)->quantity(); toRet=( abs(quantity() - second_qty) < EPS_KG); } catch (std::exception e) { } return toRet; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool Material::checkQuantityGT(rsrc_ptr other){ // true if the total atoms in the other is greater than in the base. // This will be true until proven false bool toRet = false; // Make sure the other is a material try{ // check mass values double second_qty = boost::dynamic_pointer_cast<Material>(other)->quantity(); toRet = second_qty - quantity() > EPS_KG; } catch (std::exception& e){ } return toRet; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::decay() { int curr_time = TI->time(); int delta_time = curr_time - last_update_time_; iso_vector_.executeDecay(delta_time); last_update_time_ = curr_time; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::decayMaterials(int time) { // if decay is on if (decay_wanted_) { // and if (time(mod interval)==0) if (time % decay_interval_ == 0) { // acquire a list of all materials for (vector<mat_rsrc_ptr>::iterator mat = materials_.begin(); mat != materials_.end(); mat++){ // and decay each of them (*mat)->decay(); } } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::setDecay(int dec) { if ( dec <= 0 ) { decay_wanted_ = false; } else if ( dec > 0 ) { decay_wanted_ = true; decay_interval_ = dec; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::define_table() { // declare the table columns column id("ID","INTEGER"); column state_id("StateID","INTEGER"); column time("Time","INTEGER"); // declare the table's primary key primary_key pk; pk.push_back("ID"), pk.push_back("StateID"); material_table->setPrimaryKey(pk); // add columns to the table material_table->addColumn(id); material_table->addColumn(state_id); material_table->addColumn(time); // add foreign keys foreign_key_ref *fkref; foreign_key *fk; key myk, theirk; // Resources table foreign keys theirk.push_back("ID"); fkref = new foreign_key_ref("Resources",theirk); // the resource id myk.push_back("ID"); fk = new foreign_key(myk, (*fkref) ); material_table->addForeignKey( (*fk) ); // id references resources' id myk.clear(), theirk.clear(); // IsotopicStates table foreign keys theirk.push_back("ID"); fkref = new foreign_key_ref("IsotopicStates",theirk); // the state id myk.push_back("StateID"); fk = new foreign_key(myk, (*fkref) ); material_table->addForeignKey( (*fk) ); // stateid references isotopicstates' id myk.clear(), theirk.clear(); // we've now defined the table material_table->tableDefined(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::addToTable(){ // if we haven't logged an material yet, define the table if ( !material_table->defined() ) Material::define_table(); // make a row // declare data data an_id( this->originalID() ), a_state( 1 ), // @MJG FLAG need to do state recording a_time( TI->time() ); // declare entries entry id("ID",an_id), state("StateID",a_state), time("Time",a_time); // declare row row aRow; aRow.push_back(id), aRow.push_back(state), aRow.push_back(time); // add the row material_table->addRow(aRow); // record this primary key pkref_.push_back(id); pkref_.push_back(state); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Material::setOriginatorID(int id){ originatorID_ = id; this->Resource::addToTable(); this->Material::addToTable(); } <|endoftext|>
<commit_before>/* Copyright 2008 Larry Gritz and the other authors and contributors. 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 software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <iterator> #include <OpenEXR/ImathMatrix.h> #include <OpenEXR/ImathVec.h> #include "argparse.h" #include "imageio.h" using namespace OpenImageIO; #include "ustring.h" #include "imagebuf.h" #include "texture.h" #include "fmath.h" #include "sysutil.h" static std::vector<std::string> filenames; static std::string output_filename = "out.exr"; static bool verbose = false; static int output_xres = 512, output_yres = 512; static float blur = 0; static float width = 1; static int iters = 1; static int autotile = 0; static bool automip = false; static TextureSystem *texsys = NULL; static std::string searchpath; static int blocksize = 1; static bool nowarp = false; static float cachesize = -1; static float missing[4] = {-1, 0, 0, 1}; static int parse_files (int argc, const char *argv[]) { for (int i = 0; i < argc; i++) filenames.push_back (argv[i]); return 0; } static void getargs (int argc, const char *argv[]) { bool help = false; ArgParse ap; ap.options ("Usage: testtex [options] inputfile", "%*", parse_files, "", "--help", &help, "Print help message", "-v", &verbose, "Verbose status messages", "-o %s", &output_filename, "Output test image", "-res %d %d", &output_xres, &output_yres, "Resolution of output test image", "-iters %d", &iters, "Iterations for time trials", "--blur %f", &blur, "Add blur to texture lookup", "--width %f", &width, "Multiply filter width of texture lookup", "--missing %f %f %f", &missing[0], &missing[1], &missing[2], "Specify missing texture color", "--autotile %d", &autotile, "Set auto-tile size for the image cache", "--automip", &automip, "Set auto-MIPmap for the image cache", "--blocksize %d", &blocksize, "Set blocksize (n x n) for batches", "--searchpath %s", &searchpath, "Search path for files", "--nowarp", &nowarp, "Do not warp the image->texture mapping", "--cachesize %g", &cachesize, "Set cache size, in MB", NULL); if (ap.parse (argc, argv) < 0) { std::cerr << ap.geterror() << std::endl; ap.usage (); exit (EXIT_FAILURE); } if (help) { ap.usage (); exit (EXIT_FAILURE); } if (filenames.size() < 1) { std::cerr << "testtex: Must have at least one input file\n"; ap.usage(); exit (EXIT_FAILURE); } } static void test_gettextureinfo (ustring filename) { bool ok; int res[2]; ok = texsys->get_texture_info (filename, ustring("resolution"), TypeDesc(TypeDesc::INT,2), res); std::cerr << "Result of get_texture_info resolution = " << ok << ' ' << res[0] << 'x' << res[1] << "\n"; int chan; ok = texsys->get_texture_info (filename, ustring("channels"), TypeDesc::INT, &chan); std::cerr << "Result of get_texture_info channels = " << ok << ' ' << chan << "\n"; float fchan; ok = texsys->get_texture_info (filename, ustring("channels"), TypeDesc::FLOAT, &fchan); std::cerr << "Result of get_texture_info channels = " << ok << ' ' << fchan << "\n"; int dataformat; ok = texsys->get_texture_info (filename, ustring("format"), TypeDesc::INT, &dataformat); std::cerr << "Result of get_texture_info data format = " << ok << ' ' << TypeDesc((TypeDesc::BASETYPE)dataformat).c_str() << "\n"; const char *datetime = NULL; ok = texsys->get_texture_info (filename, ustring("DateTime"), TypeDesc::STRING, &datetime); std::cerr << "Result of get_texture_info datetime = " << ok << ' ' << (datetime ? datetime : "") << "\n"; const char *texturetype = NULL; ok = texsys->get_texture_info (filename, ustring("textureformat"), TypeDesc::STRING, &texturetype); std::cerr << "Texture type is " << ok << ' ' << (texturetype ? texturetype : "") << "\n"; std::cerr << "\n"; } inline Imath::V3f warp (float x, float y, Imath::M33f &xform) { Imath::V3f coord (x, y, 1.0f); coord *= xform; coord[0] *= 1/(1+2*std::max (-0.5f, coord[1])); return coord; } static void test_plain_texture (ustring filename) { std::cerr << "Testing 2d texture " << filename << ", output = " << output_filename << "\n"; const int nchannels = 4; ImageSpec outspec (output_xres, output_yres, nchannels, TypeDesc::HALF); ImageBuf image (output_filename, outspec); image.zero (); Imath::M33f scale; scale.scale (Imath::V2f (0.5, 0.5)); Imath::M33f rot; rot.rotate (radians(30.0f)); Imath::M33f trans; trans.translate (Imath::V2f (0.35f, 0.15f)); Imath::M33f xform = scale * rot * trans; xform.invert(); TextureOptions opt; opt.sblur = blur; opt.tblur = blur; opt.swidth = width; opt.twidth = width; opt.nchannels = nchannels; float fill = 1; opt.fill = fill; if (missing[0] >= 0) opt.missingcolor.init ((float *)&missing, 0); // opt.interpmode = TextureOptions::InterpSmartBicubic; // opt.mipmode = TextureOptions::MipModeAniso; opt.swrap = opt.twrap = TextureOptions::WrapPeriodic; // opt.twrap = TextureOptions::WrapBlack; int shadepoints = blocksize*blocksize; float *s = ALLOCA (float, shadepoints); float *t = ALLOCA (float, shadepoints); Runflag *runflags = ALLOCA (Runflag, shadepoints); float *dsdx = ALLOCA (float, shadepoints); float *dtdx = ALLOCA (float, shadepoints); float *dsdy = ALLOCA (float, shadepoints); float *dtdy = ALLOCA (float, shadepoints); float *result = ALLOCA (float, shadepoints*nchannels); for (int iter = 0; iter < iters; ++iter) { // Iterate over blocks // Trick: switch to second texture, if given, for second iteration if (iter && filenames.size() > 1) filename = ustring (filenames[1]); for (int by = 0; by < output_yres; by+=blocksize) { for (int bx = 0; bx < output_xres; bx+=blocksize) { // Process pixels within a block. First save the texture warp // (s,t) and derivatives into SIMD vectors. int idx = 0; for (int y = by; y < by+blocksize; ++y) { for (int x = bx; x < bx+blocksize; ++x) { if (x < output_xres && y < output_yres) { if (nowarp) { s[idx] = (float)x/output_xres; t[idx] = (float)y/output_yres; dsdx[idx] = 1.0f/output_xres; dtdx[idx] = 0; dsdy[idx] = 0; dtdy[idx] = 1.0f/output_yres; } else { Imath::V3f coord = warp ((float)x/output_xres, (float)y/output_yres, xform); Imath::V3f coordx = warp ((float)(x+1)/output_xres, (float)y/output_yres, xform); Imath::V3f coordy = warp ((float)x/output_xres, (float)(y+1)/output_yres, xform); s[idx] = coord[0]; t[idx] = coord[1]; dsdx[idx] = coordx[0] - coord[0]; dtdx[idx] = coordx[1] - coord[1]; dsdy[idx] = coordy[0] - coord[0]; dtdy[idx] = coordy[1] - coord[1]; } runflags[idx] = RunFlagOn; } else { runflags[idx] = RunFlagOff; } ++idx; } } // Call the texture system to do the filtering. bool ok = texsys->texture (filename, opt, runflags, 0, shadepoints, Varying(s), Varying(t), Varying(dsdx), Varying(dtdx), Varying(dsdy), Varying(dtdy), result); if (! ok) { std::string e = texsys->geterror (); if (! e.empty()) std::cerr << "ERROR: " << e << "\n"; } // Save filtered pixels back to the image. idx = 0; for (int y = by; y < by+blocksize; ++y) { for (int x = bx; x < bx+blocksize; ++x) { if (runflags[idx]) { image.setpixel (x, y, result + idx*nchannels); } ++idx; } } } } } if (! image.save ()) std::cerr << "Error writing " << output_filename << " : " << image.geterror() << "\n"; } static void test_shadow (ustring filename) { } static void test_environment (ustring filename) { } static void test_getimagespec_gettexels (ustring filename) { ImageSpec spec; if (! texsys->get_imagespec (filename, spec)) { std::cerr << "Could not get spec for " << filename << "\n"; std::string e = texsys->geterror (); if (! e.empty()) std::cerr << "ERROR: " << e << "\n"; return; } int w = spec.width/2, h = spec.height/2; ImageSpec postagespec (w, h, spec.nchannels, TypeDesc::FLOAT); ImageBuf buf ("postage.exr", postagespec); TextureOptions opt; opt.nchannels = spec.nchannels; if (missing[0] >= 0) opt.missingcolor.init ((float *)&missing, 0); std::vector<float> tmp (w*h*spec.nchannels); texsys->get_texels (filename, opt, 0, w/2, w/2+w, h/2, h/2+h, 0, 1, postagespec.format, &tmp[0]); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { imagesize_t offset = (y*w + x) * spec.nchannels; buf.setpixel (x, y, &tmp[offset]); } buf.save (); } int main (int argc, const char *argv[]) { getargs (argc, argv); texsys = TextureSystem::create (); std::cerr << "Created texture system\n"; texsys->attribute ("statistics:level", 2); texsys->attribute ("autotile", autotile); texsys->attribute ("automip", (int)automip); if (cachesize >= 0) texsys->attribute ("max_memory_MB", cachesize); if (searchpath.length()) texsys->attribute ("searchpath", searchpath); if (iters > 0) { ustring filename (filenames[0]); test_gettextureinfo (filename); const char *texturetype = "Plain Texture"; texsys->get_texture_info (filename, ustring("texturetype"), TypeDesc::STRING, &texturetype); if (! strcmp (texturetype, "Plain Texture")) { test_plain_texture (filename); } if (! strcmp (texturetype, "Shadow")) { test_shadow (filename); } if (! strcmp (texturetype, "Environment")) { test_environment (filename); } test_getimagespec_gettexels (filename); } TextureSystem::destroy (texsys); return 0; } <commit_msg>fixed testtex: it was crashing when performing texture-missing.<commit_after>/* Copyright 2008 Larry Gritz and the other authors and contributors. 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 software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <iterator> #include <OpenEXR/ImathMatrix.h> #include <OpenEXR/ImathVec.h> #include "argparse.h" #include "imageio.h" using namespace OpenImageIO; #include "ustring.h" #include "imagebuf.h" #include "texture.h" #include "fmath.h" #include "sysutil.h" static std::vector<std::string> filenames; static std::string output_filename = "out.exr"; static bool verbose = false; static int output_xres = 512, output_yres = 512; static float blur = 0; static float width = 1; static int iters = 1; static int autotile = 0; static bool automip = false; static TextureSystem *texsys = NULL; static std::string searchpath; static int blocksize = 1; static bool nowarp = false; static float cachesize = -1; static float missing[4] = {-1, 0, 0, 1}; static int parse_files (int argc, const char *argv[]) { for (int i = 0; i < argc; i++) filenames.push_back (argv[i]); return 0; } static void getargs (int argc, const char *argv[]) { bool help = false; ArgParse ap; ap.options ("Usage: testtex [options] inputfile", "%*", parse_files, "", "--help", &help, "Print help message", "-v", &verbose, "Verbose status messages", "-o %s", &output_filename, "Output test image", "-res %d %d", &output_xres, &output_yres, "Resolution of output test image", "-iters %d", &iters, "Iterations for time trials", "--blur %f", &blur, "Add blur to texture lookup", "--width %f", &width, "Multiply filter width of texture lookup", "--missing %f %f %f", &missing[0], &missing[1], &missing[2], "Specify missing texture color", "--autotile %d", &autotile, "Set auto-tile size for the image cache", "--automip", &automip, "Set auto-MIPmap for the image cache", "--blocksize %d", &blocksize, "Set blocksize (n x n) for batches", "--searchpath %s", &searchpath, "Search path for files", "--nowarp", &nowarp, "Do not warp the image->texture mapping", "--cachesize %g", &cachesize, "Set cache size, in MB", NULL); if (ap.parse (argc, argv) < 0) { std::cerr << ap.geterror() << std::endl; ap.usage (); exit (EXIT_FAILURE); } if (help) { ap.usage (); exit (EXIT_FAILURE); } if (filenames.size() < 1) { std::cerr << "testtex: Must have at least one input file\n"; ap.usage(); exit (EXIT_FAILURE); } } static void test_gettextureinfo (ustring filename) { bool ok; int res[2] = {0}; ok = texsys->get_texture_info (filename, ustring("resolution"), TypeDesc(TypeDesc::INT,2), res); std::cerr << "Result of get_texture_info resolution = " << ok << ' ' << res[0] << 'x' << res[1] << "\n"; int chan = 0; ok = texsys->get_texture_info (filename, ustring("channels"), TypeDesc::INT, &chan); std::cerr << "Result of get_texture_info channels = " << ok << ' ' << chan << "\n"; float fchan = 0; ok = texsys->get_texture_info (filename, ustring("channels"), TypeDesc::FLOAT, &fchan); std::cerr << "Result of get_texture_info channels = " << ok << ' ' << fchan << "\n"; int dataformat = 0; ok = texsys->get_texture_info (filename, ustring("format"), TypeDesc::INT, &dataformat); std::cerr << "Result of get_texture_info data format = " << ok << ' ' << TypeDesc((TypeDesc::BASETYPE)dataformat).c_str() << "\n"; const char *datetime = NULL; ok = texsys->get_texture_info (filename, ustring("DateTime"), TypeDesc::STRING, &datetime); std::cerr << "Result of get_texture_info datetime = " << ok << ' ' << (datetime ? datetime : "") << "\n"; const char *texturetype = NULL; ok = texsys->get_texture_info (filename, ustring("textureformat"), TypeDesc::STRING, &texturetype); std::cerr << "Texture type is " << ok << ' ' << (texturetype ? texturetype : "") << "\n"; std::cerr << "\n"; } inline Imath::V3f warp (float x, float y, Imath::M33f &xform) { Imath::V3f coord (x, y, 1.0f); coord *= xform; coord[0] *= 1/(1+2*std::max (-0.5f, coord[1])); return coord; } static void test_plain_texture (ustring filename) { std::cerr << "Testing 2d texture " << filename << ", output = " << output_filename << "\n"; const int nchannels = 4; ImageSpec outspec (output_xres, output_yres, nchannels, TypeDesc::HALF); ImageBuf image (output_filename, outspec); image.zero (); Imath::M33f scale; scale.scale (Imath::V2f (0.5, 0.5)); Imath::M33f rot; rot.rotate (radians(30.0f)); Imath::M33f trans; trans.translate (Imath::V2f (0.35f, 0.15f)); Imath::M33f xform = scale * rot * trans; xform.invert(); TextureOptions opt; opt.sblur = blur; opt.tblur = blur; opt.swidth = width; opt.twidth = width; opt.nchannels = nchannels; float fill = 1; opt.fill = fill; if (missing[0] >= 0) opt.missingcolor.init ((float *)&missing, 0); // opt.interpmode = TextureOptions::InterpSmartBicubic; // opt.mipmode = TextureOptions::MipModeAniso; opt.swrap = opt.twrap = TextureOptions::WrapPeriodic; // opt.twrap = TextureOptions::WrapBlack; int shadepoints = blocksize*blocksize; float *s = ALLOCA (float, shadepoints); float *t = ALLOCA (float, shadepoints); Runflag *runflags = ALLOCA (Runflag, shadepoints); float *dsdx = ALLOCA (float, shadepoints); float *dtdx = ALLOCA (float, shadepoints); float *dsdy = ALLOCA (float, shadepoints); float *dtdy = ALLOCA (float, shadepoints); float *result = ALLOCA (float, shadepoints*nchannels); for (int iter = 0; iter < iters; ++iter) { // Iterate over blocks // Trick: switch to second texture, if given, for second iteration if (iter && filenames.size() > 1) filename = ustring (filenames[1]); for (int by = 0; by < output_yres; by+=blocksize) { for (int bx = 0; bx < output_xres; bx+=blocksize) { // Process pixels within a block. First save the texture warp // (s,t) and derivatives into SIMD vectors. int idx = 0; for (int y = by; y < by+blocksize; ++y) { for (int x = bx; x < bx+blocksize; ++x) { if (x < output_xres && y < output_yres) { if (nowarp) { s[idx] = (float)x/output_xres; t[idx] = (float)y/output_yres; dsdx[idx] = 1.0f/output_xres; dtdx[idx] = 0; dsdy[idx] = 0; dtdy[idx] = 1.0f/output_yres; } else { Imath::V3f coord = warp ((float)x/output_xres, (float)y/output_yres, xform); Imath::V3f coordx = warp ((float)(x+1)/output_xres, (float)y/output_yres, xform); Imath::V3f coordy = warp ((float)x/output_xres, (float)(y+1)/output_yres, xform); s[idx] = coord[0]; t[idx] = coord[1]; dsdx[idx] = coordx[0] - coord[0]; dtdx[idx] = coordx[1] - coord[1]; dsdy[idx] = coordy[0] - coord[0]; dtdy[idx] = coordy[1] - coord[1]; } runflags[idx] = RunFlagOn; } else { runflags[idx] = RunFlagOff; } ++idx; } } // Call the texture system to do the filtering. bool ok = texsys->texture (filename, opt, runflags, 0, shadepoints, Varying(s), Varying(t), Varying(dsdx), Varying(dtdx), Varying(dsdy), Varying(dtdy), result); if (! ok) { std::string e = texsys->geterror (); if (! e.empty()) std::cerr << "ERROR: " << e << "\n"; } // Save filtered pixels back to the image. idx = 0; for (int y = by; y < by+blocksize; ++y) { for (int x = bx; x < bx+blocksize; ++x) { if (runflags[idx]) { image.setpixel (x, y, result + idx*nchannels); } ++idx; } } } } } if (! image.save ()) std::cerr << "Error writing " << output_filename << " : " << image.geterror() << "\n"; } static void test_shadow (ustring filename) { } static void test_environment (ustring filename) { } static void test_getimagespec_gettexels (ustring filename) { ImageSpec spec; if (! texsys->get_imagespec (filename, spec)) { std::cerr << "Could not get spec for " << filename << "\n"; std::string e = texsys->geterror (); if (! e.empty()) std::cerr << "ERROR: " << e << "\n"; return; } int w = spec.width/2, h = spec.height/2; ImageSpec postagespec (w, h, spec.nchannels, TypeDesc::FLOAT); ImageBuf buf ("postage.exr", postagespec); TextureOptions opt; opt.nchannels = spec.nchannels; if (missing[0] >= 0) opt.missingcolor.init ((float *)&missing, 0); std::vector<float> tmp (w*h*spec.nchannels); texsys->get_texels (filename, opt, 0, w/2, w/2+w, h/2, h/2+h, 0, 1, postagespec.format, &tmp[0]); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { imagesize_t offset = (y*w + x) * spec.nchannels; buf.setpixel (x, y, &tmp[offset]); } buf.save (); } int main (int argc, const char *argv[]) { getargs (argc, argv); texsys = TextureSystem::create (); std::cerr << "Created texture system\n"; texsys->attribute ("statistics:level", 2); texsys->attribute ("autotile", autotile); texsys->attribute ("automip", (int)automip); if (cachesize >= 0) texsys->attribute ("max_memory_MB", cachesize); if (searchpath.length()) texsys->attribute ("searchpath", searchpath); if (iters > 0) { ustring filename (filenames[0]); test_gettextureinfo (filename); const char *texturetype = "Plain Texture"; texsys->get_texture_info (filename, ustring("texturetype"), TypeDesc::STRING, &texturetype); if (! strcmp (texturetype, "Plain Texture")) { test_plain_texture (filename); } if (! strcmp (texturetype, "Shadow")) { test_shadow (filename); } if (! strcmp (texturetype, "Environment")) { test_environment (filename); } test_getimagespec_gettexels (filename); } TextureSystem::destroy (texsys); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypter.h" #include "script.h" #include "scrypt.h" #include <string> #include <vector> #include <boost/foreach.hpp> #include <openssl/opensslv.h> // For using openssl 1.0 and 1.1 branches. #include <openssl/aes.h> #include <openssl/evp.h> #ifdef WIN32 #include <windows.h> #endif bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) { i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); } if (nDerivationMethod == 1) { // Passphrase conversion uint256 scryptHash = scrypt_salted_multiround_hash((const void*)strKeyData.c_str(), strKeyData.size(), &chSalt[0], 8, nRounds); i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char *)&scryptHash, sizeof scryptHash, nRounds, chKey, chIV); OPENSSL_cleanse(&scryptHash, sizeof scryptHash); } if (i != (int)WALLET_CRYPTO_KEY_SIZE) { OPENSSL_cleanse(chKey, sizeof(chKey)); OPENSSL_cleanse(chIV, sizeof(chIV)); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) return false; memcpy(&chKey[0], &chNewKey[0], sizeof chKey); memcpy(&chIV[0], &chNewIV[0], sizeof chIV); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = vchPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; vchCiphertext = std::vector<unsigned char> (nCLen); #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX ctx; #else EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); #endif bool fOk = true; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX_init(&ctx); if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); #else EVP_CIPHER_CTX_init(ctx); if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0])+nCLen, &nFLen); EVP_CIPHER_CTX_free(ctx); #endif if (!fOk) return false; vchCiphertext.resize(nCLen + nFLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); int nPLen = nLen, nFLen = 0; vchPlaintext = CKeyingMaterial(nPLen); #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX ctx; #else EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); #endif bool fOk = true; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX_init(&ctx); if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); #else EVP_CIPHER_CTX_init(ctx); if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0])+nPLen, &nFLen); EVP_CIPHER_CTX_free(ctx); #endif if (!fOk) return false; vchPlaintext.resize(nPLen + nFLen); return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::LockKeyStore() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { if (fDebug) LogPrintf("CCryptoKeyStore::Unlock()\n"); { LOCK(cs_KeyStore); if (!SetCrypted()) return false; int nUnlocked = 0; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if (vchCryptedSecret.size() < 1) // key was recieved from stealth/anon txn with wallet locked, will be expanded after this { if (fDebug) LogPrintf("Skipping unexpanded key %s.\n", vchPubKey.GetHash().ToString().c_str()); continue; }; if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) { LogPrintf("DecryptSecret() failed.\n"); return false; }; if (vchSecret.size() != 32) return false; CKey key; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); if (key.GetPubKey() != vchPubKey) { LogPrintf("Unlock failed: PubKey mismatch %s.\n", vchPubKey.GetHash().ToString().c_str()); return false; }; nUnlocked++; break; }; if (nUnlocked < 1) // at least 1 key must pass the test { LogPrintf("Unlock failed: No keys unlocked.\n"); return false; }; vMasterKey = vMasterKeyIn; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKey(const CKey& key) { return CCryptoKeyStore::AddKeyPubKey(key, key.GetPubKey()); } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; // -- NOTE: this is CWallet::AddCryptedKey if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys) { const CKey &key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } <commit_msg>map c keys<commit_after>// Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypter.h" #include "script.h" #include "scrypt.h" #include <string> #include <vector> #include <boost/foreach.hpp> #include <openssl/opensslv.h> // For using openssl 1.0 and 1.1 branches. #include <openssl/aes.h> #include <openssl/evp.h> #ifdef WIN32 #include <windows.h> #endif bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) { i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); } if (nDerivationMethod == 1) { // Passphrase conversion uint256 scryptHash = scrypt_salted_multiround_hash((const void*)strKeyData.c_str(), strKeyData.size(), &chSalt[0], 8, nRounds); i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char *)&scryptHash, sizeof scryptHash, nRounds, chKey, chIV); OPENSSL_cleanse(&scryptHash, sizeof scryptHash); } if (i != (int)WALLET_CRYPTO_KEY_SIZE) { OPENSSL_cleanse(chKey, sizeof(chKey)); OPENSSL_cleanse(chIV, sizeof(chIV)); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) return false; memcpy(&chKey[0], &chNewKey[0], sizeof chKey); memcpy(&chIV[0], &chNewIV[0], sizeof chIV); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = vchPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; vchCiphertext = std::vector<unsigned char> (nCLen); #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX ctx; #else EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); #endif bool fOk = true; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX_init(&ctx); if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); #else EVP_CIPHER_CTX_init(ctx); if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0])+nCLen, &nFLen); EVP_CIPHER_CTX_free(ctx); #endif if (!fOk) return false; vchCiphertext.resize(nCLen + nFLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); int nPLen = nLen, nFLen = 0; vchPlaintext = CKeyingMaterial(nPLen); #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX ctx; #else EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); #endif bool fOk = true; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_CIPHER_CTX_init(&ctx); if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); #else EVP_CIPHER_CTX_init(ctx); if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0])+nPLen, &nFLen); EVP_CIPHER_CTX_free(ctx); #endif if (!fOk) return false; vchPlaintext.resize(nPLen + nFLen); return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::LockKeyStore() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { if (fDebug) LogPrintf("CCryptoKeyStore::Unlock()\n"); { LOCK(cs_KeyStore); if (!SetCrypted()) return false; int nUnlocked = 0; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if (vchCryptedSecret.size() < 1) // key was recieved from stealth/anon txn with wallet locked, will be expanded after this { if (fDebug) LogPrintf("Skipping unexpanded key %s.\n", vchPubKey.GetHash().ToString().c_str()); continue; }; if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) { LogPrintf("DecryptSecret() failed.\n"); return false; }; if (vchSecret.size() != 32) return false; CKey key; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); if (key.GetPubKey() != vchPubKey) { LogPrintf("Unlock failed: PubKey mismatch %s.\n", vchPubKey.GetHash().ToString().c_str()); return false; }; nUnlocked++; break; }; if (nUnlocked < 1) // at least 1 key must pass the test { if (mapCryptedKeys.size() > 0) { LogPrintf("Unlock failed: No keys unlocked.\n"); return false; }; }; vMasterKey = vMasterKeyIn; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKey(const CKey& key) { return CCryptoKeyStore::AddKeyPubKey(key, key.GetPubKey()); } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; // -- NOTE: this is CWallet::AddCryptedKey if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys) { const CKey &key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2019, Sergey Abbakumov // 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 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "rst/TaskRunner/PollingTaskRunner.h" #include <utility> #include "rst/Check/Check.h" #include "rst/NoDestructor/NoDestructor.h" namespace chrono = std::chrono; namespace rst { PollingTaskRunner::PollingTaskRunner( std::function<chrono::milliseconds()>&& time_function) : time_function_(std::move(time_function)) {} PollingTaskRunner::~PollingTaskRunner() = default; void PollingTaskRunner::PostDelayedTask(std::function<void()>&& task, const chrono::milliseconds delay) { RST_DCHECK(delay.count() >= 0); const auto now = time_function_(); const auto future_time_point = now + delay; std::lock_guard<std::mutex> lock(mutex_); queue_.emplace(future_time_point, task_id_, std::move(task)); task_id_++; } void PollingTaskRunner::RunPendingTasks() { pending_tasks_.clear(); { std::lock_guard<std::mutex> lock(mutex_); const auto now = time_function_(); while (!queue_.empty()) { const auto& item = queue_.top(); if (now < item.time_point) break; auto task = item.task; queue_.pop(); pending_tasks_.emplace_back(std::move(task)); } } for (const auto& task : pending_tasks_) task(); } } // namespace rst <commit_msg>Remove unused include<commit_after>// Copyright (c) 2019, Sergey Abbakumov // 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 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "rst/TaskRunner/PollingTaskRunner.h" #include <utility> #include "rst/Check/Check.h" namespace chrono = std::chrono; namespace rst { PollingTaskRunner::PollingTaskRunner( std::function<chrono::milliseconds()>&& time_function) : time_function_(std::move(time_function)) {} PollingTaskRunner::~PollingTaskRunner() = default; void PollingTaskRunner::PostDelayedTask(std::function<void()>&& task, const chrono::milliseconds delay) { RST_DCHECK(delay.count() >= 0); const auto now = time_function_(); const auto future_time_point = now + delay; std::lock_guard<std::mutex> lock(mutex_); queue_.emplace(future_time_point, task_id_, std::move(task)); task_id_++; } void PollingTaskRunner::RunPendingTasks() { pending_tasks_.clear(); { std::lock_guard<std::mutex> lock(mutex_); const auto now = time_function_(); while (!queue_.empty()) { const auto& item = queue_.top(); if (now < item.time_point) break; auto task = item.task; queue_.pop(); pending_tasks_.emplace_back(std::move(task)); } } for (const auto& task : pending_tasks_) task(); } } // namespace rst <|endoftext|>
<commit_before>#ifndef RFR_MOSTLY_CONTINUOUS_DATA_CONTAINER_WITH_INSTANCES_HPP #define RFR_MOSTLY_CONTINUOUS_DATA_CONTAINER_WITH_INSTANCES_HPP #include <vector> #include <map> #include <cmath> #include "rfr/data_containers/data_container_base.hpp" #include "rfr/data_containers/data_container_utils.hpp" namespace rfr{ namespace data_containers{ /** \brief A data container for mostly continuous data with instances. * * Similar to the mostly_continuous_data container, but with the capability * to handle instance features. */ template<typename num_type = float, typename response_type = float, typename index_type = unsigned int> class mostly_continuous_data_with_instances : public rfr::data_containers::data_container_base<num_type, response_type, index_type>{ protected: std::vector< std::vector<num_type> > configurations;//!< 2d vector to store the feature values of all configurations std::vector< std::vector<num_type> > instances; //!< 2d vector to store the feature values of all instances std::vector<std::pair<index_type, index_type> > config_instance_pairs; std::vector<num_type> response_values; std::map<index_type, index_type> categorical_ranges;//!< a map storing the few categorical indices and their range index_type response_t; public: // empty constructor. Use this only if you read the data from a file! // the private vectors are not properly initialized! Adding data // points via 'add_data_point' may or may not fail! mostly_continuous_data_with_instances() { throw std::runtime_error("The empty constructor is not supported by this container.");} // if you plan on filling the container with single data points one at a time // use this constructor to specify the number of features for configurations and instances mostly_continuous_data_with_instances (index_type num_config_f, index_type num_instance_f): configurations(num_config_f, std::vector<num_type>(0)), instances(num_instance_f, std::vector<num_type>(0)), response_t(0){} virtual num_type feature (index_type feature_index, index_type sample_index) const { // find out if this is a config feature if (feature_index < configurations.size()){ index_type i = config_instance_pairs[sample_index].first; return(configurations[feature_index][i]); } // otherwise it should be a instance feature index_type i = config_instance_pairs[sample_index].second; feature_index -= configurations.size(); return(instances[feature_index][i]); } virtual std::vector<num_type> features (index_type feature_index, std::vector<index_type> &sample_indices) const { std::vector<num_type> rv; rv.reserve(sample_indices.size()); if (feature_index < configurations.size()){ for (auto i : sample_indices) rv.push_back( configurations[feature_index][config_instance_pairs[i].first]); } else{ feature_index -= configurations.size(); for (auto i : sample_indices) rv.push_back(instances[feature_index][config_instance_pairs[i].second]); } return(rv); } virtual response_type response (index_type sample_index) const{ return(response_values[sample_index]); } virtual void add_data_point (num_type*, index_type, response_type){ throw std::runtime_error("This container does not support adding a data point with this function"); } void add_data_point( index_type config_index, index_type instance_index, response_type r){ if (config_index >= num_configurations() ) throw std::runtime_error("Configuration index too large."); if (instance_index >= num_instances() ) throw std::runtime_error("Instance index too large."); config_instance_pairs.emplace_back(std::pair<index_type, index_type> (config_index, instance_index)); response_values.emplace_back(r); } index_type num_configurations(){ if (configurations.size() > 0) return(configurations[0].size()); return(0); } index_type num_instances(){ if (instances.size() > 0) return(instances[0].size()); return(0); } index_type add_configuration(num_type* config_features, index_type num_elements){ if (num_elements != configurations.size()) throw std::runtime_error("Number of configuration features is not what it should be!"); for (auto i = 0u; i< num_elements; i++) configurations[i].push_back(config_features[i]); return(num_configurations()-1); } index_type add_instance(num_type* instance_features, index_type num_elements){ if (num_elements != instances.size()) throw std::runtime_error("Number of instance features is not what it should be!"); for (auto i = 0u; i< num_elements; i++) instances[i].push_back(instance_features[i]); return(num_instances()-1); } virtual std::vector<num_type> retrieve_data_point (index_type index) const { std::vector<num_type> vec; vec.reserve(num_features()); for (auto i = 0u; i< num_features(); i++) vec.emplace_back(feature(i, index)); return(vec); } /** \brief method to query the type of a feature * * As most features are assumed to be numerical, it is actually * beneficial to store only the categorical exceptions in a hash-map. * Type = 0 means continuous, and Type = n >= 1 means categorical with * options \in {1, n}. For consistency, we exclude zero from the categorical * values if anyone wants to add sparse data later on. * * \param feature_index the index of the feature * \return int type of the feature: 0 - numerical value (float or int); n>0 - categorical value with n different values {1,2,...,n} * */ virtual index_type get_type_of_feature (index_type feature_index) const{ auto it = categorical_ranges.find(feature_index); if ( it == categorical_ranges.end()) return(0); return(it->second); } void set_type_of_configuration_feature(index_type index, index_type type){ if (type > 0){ // check consistency for categorical features for (auto &fv: configurations[index]){ if (!(fv<type)) throw std::runtime_error("Feature values not consistent with provided type. Data contains a value larger than allowed."); if (fv < 0) throw std::runtime_error("Feature values contain a negative value, can't make that a categorical feature."); // round it properly fv = std::round(fv); } categorical_ranges[index] = type; } else{ categorical_ranges.erase(index); } } void set_type_of_instance_feature(index_type index, index_type type){ if (type > 0){ // check consistency for categorical features for (auto &fv: instances[index]){ if (!(fv<type)) throw std::runtime_error("Feature values not consistent with provided type. Data contains a value larger than allowed."); if (fv < 0) throw std::runtime_error("Feature values contain a negative value, can't make that a categorical feature."); // round it properly fv = std::round(fv); } categorical_ranges[index + configurations.size()] = type; } else{ categorical_ranges.erase(index + configurations.size()); } } virtual void set_type_of_feature(index_type index, index_type type){ if (index >= num_features()) throw std::runtime_error("Unknown index specified."); if (! (type >= 0)) throw std::runtime_error("Type value should be >= 0"); if (index < configurations.size()) set_type_of_configuration_feature(index, type); else set_type_of_instance_feature(index-configurations.size(), type); } virtual index_type num_features() const {return(configurations.size() + instances.size());} virtual index_type num_data_points() const {return(config_instance_pairs.size());} void check_consistency(){ /* number of stored values has to be the same for: * 1. the response values * 2. every (row) vector in feature_values */ if (config_instance_pairs.size() != num_data_points) throw std::runtime_error("config_instance_pairs has the wrong size!"); if (response_values.size() != num_data_points) throw std::runtime_error("response_values has the wrong size!"); for (auto p: config_instance_pairs){ if ( (p.first <0 ) || (p.first >= num_configurations())) throw std::runtime_error("Invalid configuration index"); if ( (p.second <0 ) || (p.second >= num_instances())) throw std::runtime_error("Invalid instance index"); } // check all values for all features for (auto f = 0u; f<num_features(); f++){ if (get_type_of_feature(f) == 0){ for (auto n = 0u; n < num_data_points(); n++){ if (isnan(feature(f,n))) throw std::runtime_error("Features contain a NaN!"); } } else{ index_type t = get_type_of_feature(f); for (auto n = 0u; n < num_data_points(); n++){ if (isnan(feature(f,n))) throw std::runtime_error("Features contain a NaN!"); if ((feature(f,n) <0) || (feature(f,n) >= t)) throw std::runtime_error("A categorical feature has an invalid value!"); } } } index_type t = get_type_of_response(); for (auto r: response_values){ if (isnan(r)) throw std::runtime_error("Responses contain a NaN!"); } } virtual index_type get_type_of_response () const{ return(response_t); } virtual void set_type_of_response (index_type resp_t){ if (resp_t > 0){ for (auto &rv: response_values){ if (!(rv < resp_t)) throw std::runtime_error("Response value not consistent with provided type. Data contains a value larger than allowed."); if (rv < 0) throw std::runtime_error("Response values contain a negative value, can't make that a categorical value."); } response_t = resp_t; } } /** \brief method to get instance as set_feature for predict_mean_var_of_mean_response_on_set method in regression forest */ virtual std::vector<num_type> get_instance_set(){ std::vector<num_type> set_feature; set_feature.reserve( num_instances() * num_features()); for (auto instance_idx = 0u; instance_idx < num_instances(); ++instance_idx){ for (auto i = 0u; i < configurations.size(); ++i){ set_feature.emplace_back(NAN); } for (auto i = 0u; i < instances.size(); ++i){ set_feature.emplace_back(instances[i][instance_idx]); } } return set_feature; } virtual std::vector<num_type> get_configuration_set(num_type configuration_index){ std::vector<num_type> features; features.reserve(num_features()); for (auto i = 0u; i < configurations.size(); ++i){ features.emplace_back(configurations[i][configuration_index]); } for (auto i = configurations.size(); i < configurations.size() + instances.size(); ++i){ features.emplace_back(NAN); } return features; } }; }}//namespace rfr #endif <commit_msg>added a method to retrieve the feauture by configuration an instance idx in data container<commit_after>#ifndef RFR_MOSTLY_CONTINUOUS_DATA_CONTAINER_WITH_INSTANCES_HPP #define RFR_MOSTLY_CONTINUOUS_DATA_CONTAINER_WITH_INSTANCES_HPP #include <vector> #include <map> #include <cmath> #include "rfr/data_containers/data_container_base.hpp" #include "rfr/data_containers/data_container_utils.hpp" namespace rfr{ namespace data_containers{ /** \brief A data container for mostly continuous data with instances. * * Similar to the mostly_continuous_data container, but with the capability * to handle instance features. */ template<typename num_type = float, typename response_type = float, typename index_type = unsigned int> class mostly_continuous_data_with_instances : public rfr::data_containers::data_container_base<num_type, response_type, index_type>{ protected: std::vector< std::vector<num_type> > configurations;//!< 2d vector to store the feature values of all configurations std::vector< std::vector<num_type> > instances; //!< 2d vector to store the feature values of all instances std::vector<std::pair<index_type, index_type> > config_instance_pairs; std::vector<num_type> response_values; std::map<index_type, index_type> categorical_ranges;//!< a map storing the few categorical indices and their range index_type response_t; public: // empty constructor. Use this only if you read the data from a file! // the private vectors are not properly initialized! Adding data // points via 'add_data_point' may or may not fail! mostly_continuous_data_with_instances() { throw std::runtime_error("The empty constructor is not supported by this container.");} // if you plan on filling the container with single data points one at a time // use this constructor to specify the number of features for configurations and instances mostly_continuous_data_with_instances (index_type num_config_f, index_type num_instance_f): configurations(num_config_f, std::vector<num_type>(0)), instances(num_instance_f, std::vector<num_type>(0)), response_t(0){} virtual num_type feature (index_type feature_index, index_type sample_index) const { // find out if this is a config feature if (feature_index < configurations.size()){ index_type i = config_instance_pairs[sample_index].first; return(configurations[feature_index][i]); } // otherwise it should be a instance feature index_type i = config_instance_pairs[sample_index].second; feature_index -= configurations.size(); return(instances[feature_index][i]); } virtual std::vector<num_type> features (index_type feature_index, std::vector<index_type> &sample_indices) const { std::vector<num_type> rv; rv.reserve(sample_indices.size()); if (feature_index < configurations.size()){ for (auto i : sample_indices) rv.push_back( configurations[feature_index][config_instance_pairs[i].first]); } else{ feature_index -= configurations.size(); for (auto i : sample_indices) rv.push_back(instances[feature_index][config_instance_pairs[i].second]); } return(rv); } virtual response_type response (index_type sample_index) const{ return(response_values[sample_index]); } virtual void add_data_point (num_type*, index_type, response_type){ throw std::runtime_error("This container does not support adding a data point with this function"); } void add_data_point( index_type config_index, index_type instance_index, response_type r){ if (config_index >= num_configurations() ) throw std::runtime_error("Configuration index too large."); if (instance_index >= num_instances() ) throw std::runtime_error("Instance index too large."); config_instance_pairs.emplace_back(std::pair<index_type, index_type> (config_index, instance_index)); response_values.emplace_back(r); } index_type num_configurations(){ if (configurations.size() > 0) return(configurations[0].size()); return(0); } index_type num_instances(){ if (instances.size() > 0) return(instances[0].size()); return(0); } index_type add_configuration(num_type* config_features, index_type num_elements){ if (num_elements != configurations.size()) throw std::runtime_error("Number of configuration features is not what it should be!"); for (auto i = 0u; i< num_elements; i++) configurations[i].push_back(config_features[i]); return(num_configurations()-1); } index_type add_instance(num_type* instance_features, index_type num_elements){ if (num_elements != instances.size()) throw std::runtime_error("Number of instance features is not what it should be!"); for (auto i = 0u; i< num_elements; i++) instances[i].push_back(instance_features[i]); return(num_instances()-1); } virtual std::vector<num_type> retrieve_data_point (index_type index) const { std::vector<num_type> vec; vec.reserve(num_features()); for (auto i = 0u; i< num_features(); i++) vec.emplace_back(feature(i, index)); return(vec); } /** \brief method to query the type of a feature * * As most features are assumed to be numerical, it is actually * beneficial to store only the categorical exceptions in a hash-map. * Type = 0 means continuous, and Type = n >= 1 means categorical with * options \in {1, n}. For consistency, we exclude zero from the categorical * values if anyone wants to add sparse data later on. * * \param feature_index the index of the feature * \return int type of the feature: 0 - numerical value (float or int); n>0 - categorical value with n different values {1,2,...,n} * */ virtual index_type get_type_of_feature (index_type feature_index) const{ auto it = categorical_ranges.find(feature_index); if ( it == categorical_ranges.end()) return(0); return(it->second); } void set_type_of_configuration_feature(index_type index, index_type type){ if (type > 0){ // check consistency for categorical features for (auto &fv: configurations[index]){ if (!(fv<type)) throw std::runtime_error("Feature values not consistent with provided type. Data contains a value larger than allowed."); if (fv < 0) throw std::runtime_error("Feature values contain a negative value, can't make that a categorical feature."); // round it properly fv = std::round(fv); } categorical_ranges[index] = type; } else{ categorical_ranges.erase(index); } } void set_type_of_instance_feature(index_type index, index_type type){ if (type > 0){ // check consistency for categorical features for (auto &fv: instances[index]){ if (!(fv<type)) throw std::runtime_error("Feature values not consistent with provided type. Data contains a value larger than allowed."); if (fv < 0) throw std::runtime_error("Feature values contain a negative value, can't make that a categorical feature."); // round it properly fv = std::round(fv); } categorical_ranges[index + configurations.size()] = type; } else{ categorical_ranges.erase(index + configurations.size()); } } virtual void set_type_of_feature(index_type index, index_type type){ if (index >= num_features()) throw std::runtime_error("Unknown index specified."); if (! (type >= 0)) throw std::runtime_error("Type value should be >= 0"); if (index < configurations.size()) set_type_of_configuration_feature(index, type); else set_type_of_instance_feature(index-configurations.size(), type); } virtual index_type num_features() const {return(configurations.size() + instances.size());} virtual index_type num_data_points() const {return(config_instance_pairs.size());} void check_consistency(){ /* number of stored values has to be the same for: * 1. the response values * 2. every (row) vector in feature_values */ if (config_instance_pairs.size() != num_data_points) throw std::runtime_error("config_instance_pairs has the wrong size!"); if (response_values.size() != num_data_points) throw std::runtime_error("response_values has the wrong size!"); for (auto p: config_instance_pairs){ if ( (p.first <0 ) || (p.first >= num_configurations())) throw std::runtime_error("Invalid configuration index"); if ( (p.second <0 ) || (p.second >= num_instances())) throw std::runtime_error("Invalid instance index"); } // check all values for all features for (auto f = 0u; f<num_features(); f++){ if (get_type_of_feature(f) == 0){ for (auto n = 0u; n < num_data_points(); n++){ if (isnan(feature(f,n))) throw std::runtime_error("Features contain a NaN!"); } } else{ index_type t = get_type_of_feature(f); for (auto n = 0u; n < num_data_points(); n++){ if (isnan(feature(f,n))) throw std::runtime_error("Features contain a NaN!"); if ((feature(f,n) <0) || (feature(f,n) >= t)) throw std::runtime_error("A categorical feature has an invalid value!"); } } } index_type t = get_type_of_response(); for (auto r: response_values){ if (isnan(r)) throw std::runtime_error("Responses contain a NaN!"); } } virtual index_type get_type_of_response () const{ return(response_t); } virtual void set_type_of_response (index_type resp_t){ if (resp_t > 0){ for (auto &rv: response_values){ if (!(rv < resp_t)) throw std::runtime_error("Response value not consistent with provided type. Data contains a value larger than allowed."); if (rv < 0) throw std::runtime_error("Response values contain a negative value, can't make that a categorical value."); } response_t = resp_t; } } /** \brief method to get instance as set_feature for predict_mean_var_of_mean_response_on_set method in regression forest */ virtual std::vector<num_type> get_instance_set(){ std::vector<num_type> set_feature; set_feature.reserve( num_instances() * num_features()); for (auto instance_idx = 0u; instance_idx < num_instances(); ++instance_idx){ for (auto i = 0u; i < configurations.size(); ++i){ set_feature.emplace_back(NAN); } for (auto i = 0u; i < instances.size(); ++i){ set_feature.emplace_back(instances[i][instance_idx]); } } return set_feature; } virtual std::vector<num_type> get_configuration_set(num_type configuration_index){ std::vector<num_type> features; features.reserve(num_features()); for (auto i = 0u; i < configurations.size(); ++i){ features.emplace_back(configurations[i][configuration_index]); } for (auto i = 0; i < instances.size(); ++i){ features.emplace_back(NAN); } return features; } virtual std::vector<num_type> get_features_by_configuration_and_instance(num_type configuration_index, num_type instance_index){ std::vector<num_type> features; features.reserve(num_features()); for (auto i = 0u; i < configurations.size(); ++i){ features.emplace_back(configurations[i][configuration_index]); } for (auto i = 0; i < instances.size(); ++i){ features.emplace_back(instances[i][instance_index]); } return features; } }; }}//namespace rfr #endif <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include "hadesmem/process.hpp" #include <array> #include <utility> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/assert.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" namespace hadesmem { Process::Process(DWORD id) : id_(id), handle_(Open(id)) { CheckWoW64(); } Process::Process(Process&& other) BOOST_NOEXCEPT : id_(other.id_), handle_(other.handle_) { other.id_ = 0; other.handle_ = nullptr; } Process& Process::operator=(Process&& other) BOOST_NOEXCEPT { Cleanup(); std::swap(this->id_, other.id_); std::swap(this->handle_, other.handle_); return *this; } Process::Process(Process const& other) : id_(0), handle_(nullptr) { HANDLE new_handle = nullptr; if (!DuplicateHandle(GetCurrentProcess(), other.handle_, GetCurrentProcess(), &new_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("DuplicateHandle failed.") << ErrorCodeWinLast(last_error)); } handle_ = new_handle; id_ = other.id_; } Process& Process::operator=(Process const& other) { HANDLE new_handle = nullptr; if (!DuplicateHandle(GetCurrentProcess(), other.handle_, GetCurrentProcess(), &new_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("DuplicateHandle failed.") << ErrorCodeWinLast(last_error)); } Cleanup(); handle_ = new_handle; id_ = other.id_; return *this; } Process::~Process() BOOST_NOEXCEPT { if (handle_ && handle_ != GetCurrentProcess()) { BOOST_VERIFY(CloseHandle(handle_)); } } DWORD Process::GetId() const BOOST_NOEXCEPT { return id_; } HANDLE Process::GetHandle() const BOOST_NOEXCEPT { return handle_; } void Process::Cleanup() { if (!handle_) { return; } BOOST_ASSERT(id_); if (!CloseHandle(handle_)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("CloseHandle failed.") << ErrorCodeWinLast(last_error)); } id_ = 0; handle_ = nullptr; } void Process::CheckWoW64() const { BOOL is_wow64_me = FALSE; if (!::IsWow64Process(GetCurrentProcess(), &is_wow64_me)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not detect WoW64 status of current process.") << ErrorCodeWinLast(last_error)); } BOOL is_wow64 = FALSE; if (!::IsWow64Process(handle_, &is_wow64)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not detect WoW64 status of target process.") << ErrorCodeWinLast(last_error)); } if (is_wow64_me != is_wow64) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Cross-architecture process manipulation is currently " "unsupported.")); } } HANDLE Process::Open(DWORD id) { HANDLE handle = ::OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, id); if (!handle) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("OpenProcess failed.") << ErrorCodeWinLast(last_error)); } return handle; } void Process::CleanupUnchecked() BOOST_NOEXCEPT { try { Cleanup(); } catch (std::exception const& e) { // WARNING: Handle is leaked if 'Cleanup' fails. BOOST_ASSERT_MSG(false, boost::diagnostic_information(e).c_str()); id_ = 0; handle_ = nullptr; } } bool Process::operator==(Process const& other) const BOOST_NOEXCEPT { return this->id_ == other.id_; } bool Process::operator!=(Process const& other) const BOOST_NOEXCEPT { return !(*this == other); } std::wstring GetPath(Process const& process) { std::array<wchar_t, MAX_PATH> path = { { } }; DWORD path_len = static_cast<DWORD>(path.size()); if (!::QueryFullProcessImageName(process.GetHandle(), 0, path.data(), &path_len)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("QueryFullProcessImageName failed.") << ErrorCodeWinLast(last_error)); } return path.data(); } bool IsWoW64(Process const& process) { BOOL is_wow64 = FALSE; if (!::IsWow64Process(process.GetHandle(), &is_wow64)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("IsWow64Process failed.") << ErrorCodeWinLast(last_error)); } return is_wow64 != FALSE; } } <commit_msg>* [process] Fix the destructor properly because I'm an idiot. * [process] Minor cleanup.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include "hadesmem/process.hpp" #include <array> #include <utility> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/assert.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" namespace hadesmem { Process::Process(DWORD id) : id_(id), handle_(Open(id)) { CheckWoW64(); } Process::Process(Process&& other) BOOST_NOEXCEPT : id_(other.id_), handle_(other.handle_) { other.id_ = 0; other.handle_ = nullptr; } Process& Process::operator=(Process&& other) BOOST_NOEXCEPT { Cleanup(); std::swap(this->id_, other.id_); std::swap(this->handle_, other.handle_); return *this; } Process::Process(Process const& other) : id_(0), handle_(nullptr) { HANDLE new_handle = Duplicate(other.handle_); handle_ = new_handle; id_ = other.id_; } Process& Process::operator=(Process const& other) { HANDLE new_handle = Duplicate(other.handle_); Cleanup(); handle_ = new_handle; id_ = other.id_; return *this; } Process::~Process() BOOST_NOEXCEPT { CleanupUnchecked(); } DWORD Process::GetId() const BOOST_NOEXCEPT { return id_; } HANDLE Process::GetHandle() const BOOST_NOEXCEPT { return handle_; } void Process::Cleanup() { if (!handle_) { return; } BOOST_ASSERT(id_); if (!::CloseHandle(handle_)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("CloseHandle failed.") << ErrorCodeWinLast(last_error)); } id_ = 0; handle_ = nullptr; } void Process::CheckWoW64() const { BOOL is_wow64_me = FALSE; if (!::IsWow64Process(GetCurrentProcess(), &is_wow64_me)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not detect WoW64 status of current process.") << ErrorCodeWinLast(last_error)); } BOOL is_wow64 = FALSE; if (!::IsWow64Process(handle_, &is_wow64)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not detect WoW64 status of target process.") << ErrorCodeWinLast(last_error)); } if (is_wow64_me != is_wow64) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Cross-architecture process manipulation is currently " "unsupported.")); } } HANDLE Process::Open(DWORD id) { HANDLE handle = ::OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, id); if (!handle) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("OpenProcess failed.") << ErrorCodeWinLast(last_error)); } return handle; } void Process::CleanupUnchecked() BOOST_NOEXCEPT { try { Cleanup(); } catch (std::exception const& e) { // WARNING: Handle is leaked if 'Cleanup' fails. BOOST_ASSERT_MSG(false, boost::diagnostic_information(e).c_str()); id_ = 0; handle_ = nullptr; } } HANDLE Process::Duplicate(HANDLE handle) { HANDLE new_handle = nullptr; if (!::DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &new_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("DuplicateHandle failed.") << ErrorCodeWinLast(last_error)); } return new_handle; } bool Process::operator==(Process const& other) const BOOST_NOEXCEPT { return this->id_ == other.id_; } bool Process::operator!=(Process const& other) const BOOST_NOEXCEPT { return !(*this == other); } std::wstring GetPath(Process const& process) { std::array<wchar_t, MAX_PATH> path = { { } }; DWORD path_len = static_cast<DWORD>(path.size()); if (!::QueryFullProcessImageName(process.GetHandle(), 0, path.data(), &path_len)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("QueryFullProcessImageName failed.") << ErrorCodeWinLast(last_error)); } return path.data(); } bool IsWoW64(Process const& process) { BOOL is_wow64 = FALSE; if (!::IsWow64Process(process.GetHandle(), &is_wow64)) { DWORD const last_error = GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("IsWow64Process failed.") << ErrorCodeWinLast(last_error)); } return is_wow64 != FALSE; } } <|endoftext|>
<commit_before>// Filename: connectionManager.cxx // Created by: jns (07Feb00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "connectionManager.h" #include "connection.h" #include "connectionReader.h" #include "connectionWriter.h" #include "netAddress.h" #include "config_net.h" #include "lightMutexHolder.h" #include "trueClock.h" #if defined(WIN32_VC) || defined(WIN64_VC) #include <winsock2.h> // For gethostname() #endif //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// ConnectionManager:: ConnectionManager() : _set_mutex("ConnectionManager::_set_mutex") { } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::Destructor // Access: Public, Virtual // Description: //////////////////////////////////////////////////////////////////// ConnectionManager:: ~ConnectionManager() { // Notify all of our associated readers and writers that we're gone. Readers::iterator ri; for (ri = _readers.begin(); ri != _readers.end(); ++ri) { (*ri)->clear_manager(); } Writers::iterator wi; for (wi = _writers.begin(); wi != _writers.end(); ++wi) { (*wi)->clear_manager(); } } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_UDP_connection // Access: Public // Description: Opens a socket for sending and/or receiving UDP // packets. If the port number is greater than zero, // the UDP connection will be opened for listening on // the indicated port; otherwise, it will be useful only // for sending. // // Use a ConnectionReader and ConnectionWriter to handle // the actual communication. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_UDP_connection(int port) { Socket_UDP *socket = new Socket_UDP; if (port > 0) { NetAddress address; address.set_any(port); if (!socket->OpenForInput(address.get_addr())) { net_cat.error() << "Unable to bind to port " << port << " for UDP.\n"; delete socket; return PT(Connection)(); } net_cat.info() << "Creating UDP connection for port " << port << "\n"; } else { if (!socket->InitNoAddress()) { net_cat.error() << "Unable to initialize outgoing UDP.\n"; delete socket; return PT(Connection)(); } net_cat.info() << "Creating outgoing UDP connection\n"; } PT(Connection) connection = new Connection(this, socket); new_connection(connection); return connection; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_server_rendezvous // Access: Public // Description: Creates a socket to be used as a rendezvous socket // for a server to listen for TCP connections. The // socket returned by this call should only be added to // a ConnectionListener (not to a generic // ConnectionReader). // // This variant of this method accepts a single port, // and will listen to that port on all available // interfaces. // // backlog is the maximum length of the queue of pending // connections. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_server_rendezvous(int port, int backlog) { NetAddress address; address.set_any(port); return open_TCP_server_rendezvous(address, backlog); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_server_rendezvous // Access: Public // Description: Creates a socket to be used as a rendezvous socket // for a server to listen for TCP connections. The // socket returned by this call should only be added to // a ConnectionListener (not to a generic // ConnectionReader). // // This variant of this method accepts a "hostname", // which is usually just an IP address in dotted // notation, and a port number. It will listen on the // interface indicated by the IP address. If the IP // address is empty string, it will listen on all // interfaces. // // backlog is the maximum length of the queue of pending // connections. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_server_rendezvous(const string &hostname, int port, int backlog) { NetAddress address; if (hostname.empty()) { address.set_any(port); } else { address.set_host(hostname, port); } return open_TCP_server_rendezvous(address, backlog); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_server_rendezvous // Access: Public // Description: Creates a socket to be used as a rendezvous socket // for a server to listen for TCP connections. The // socket returned by this call should only be added to // a ConnectionListener (not to a generic // ConnectionReader). // // This variant of this method accepts a NetAddress, // which allows you to specify a specific interface to // listen to. // // backlog is the maximum length of the queue of pending // connections. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_server_rendezvous(const NetAddress &address, int backlog) { ostringstream strm; if (address.get_ip() == 0) { strm << "port " << address.get_port(); } else { strm << address.get_ip_string() << ":" << address.get_port(); } Socket_TCP_Listen *socket = new Socket_TCP_Listen; bool okflag = socket->OpenForListen(address.get_addr(), backlog); if (!okflag) { net_cat.info() << "Unable to listen to " << strm.str() << " for TCP.\n"; delete socket; return PT(Connection)(); } net_cat.info() << "Listening for TCP connections on " << strm.str() << "\n"; PT(Connection) connection = new Connection(this, socket); new_connection(connection); return connection; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_client_connection // Access: Public // Description: Attempts to establish a TCP client connection to a // server at the indicated address. If the connection // is not established within timeout_ms milliseconds, a // null connection is returned. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_client_connection(const NetAddress &address, int timeout_ms) { Socket_TCP *socket = new Socket_TCP; // We always open the connection with non-blocking mode first, so we // can implement the timeout. bool okflag = socket->ActiveOpenNonBlocking(address.get_addr()); if (okflag && socket->GetLastError() == LOCAL_CONNECT_BLOCKING) { // Now wait for the socket to connect. TrueClock *clock = TrueClock::get_global_ptr(); double start = clock->get_short_time(); Thread::force_yield(); Socket_fdset fset; fset.setForSocket(*socket); int ready = fset.WaitForWrite(true, 0); while (ready == 0) { double elapsed = clock->get_short_time() - start; if (elapsed * 1000.0 > timeout_ms) { // Timeout. okflag = false; break; } Thread::force_yield(); fset.setForSocket(*socket); ready = fset.WaitForWrite(true, 0); } } if (!okflag) { net_cat.error() << "Unable to open TCP connection to server " << address.get_ip_string() << " on port " << address.get_port() << "\n"; delete socket; return PT(Connection)(); } #if !defined(HAVE_THREADS) || !defined(SIMPLE_THREADS) // Now we have opened the socket in nonblocking mode. Unless we're // using SIMPLE_THREADS, though, we really want the socket in // blocking mode (since that's what we support here). Change it. socket->SetBlocking(); #endif // SIMPLE_THREADS net_cat.info() << "Opened TCP connection to server " << address.get_ip_string() << " " << " on port " << address.get_port() << "\n"; PT(Connection) connection = new Connection(this, socket); new_connection(connection); return connection; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_client_connection // Access: Public // Description: This is a shorthand version of the function to // directly establish communications to a named host and // port. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_client_connection(const string &hostname, int port, int timeout_ms) { NetAddress address; if (!address.set_host(hostname, port)) { return PT(Connection)(); } return open_TCP_client_connection(address, timeout_ms); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::close_connection // Access: Public // Description: Terminates a UDP or TCP socket previously opened. // This also removes it from any associated // ConnectionReader or ConnectionListeners. // // The socket itself may not be immediately closed--it // will not be closed until all outstanding pointers to // it are cleared, including any pointers remaining in // NetDatagrams recently received from the socket. // // The return value is true if the connection was marked // to be closed, or false if close_connection() had // already been called (or the connection did not belong // to this ConnectionManager). In neither case can you // infer anything about whether the connection has // *actually* been closed yet based on the return value. //////////////////////////////////////////////////////////////////// bool ConnectionManager:: close_connection(const PT(Connection) &connection) { if (connection != (Connection *)NULL) { connection->flush(); } { LightMutexHolder holder(_set_mutex); Connections::iterator ci = _connections.find(connection); if (ci == _connections.end()) { // Already closed, or not part of this ConnectionManager. return false; } _connections.erase(ci); Readers::iterator ri; for (ri = _readers.begin(); ri != _readers.end(); ++ri) { (*ri)->remove_connection(connection); } } Socket_IP *socket = connection->get_socket(); // We can't *actually* close the connection right now, because // there might be outstanding pointers to it. But we can at least // shut it down. It will be eventually closed when all the // pointers let go. net_cat.info() << "Shutting down connection " << (void *)connection << " locally.\n"; socket->Close(); return true; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::get_host_name // Access: Public, Static // Description: Returns the name of this particular machine on the // network, if available, or the empty string if the // hostname cannot be determined. //////////////////////////////////////////////////////////////////// string ConnectionManager:: get_host_name() { char temp_buff[1024]; if (gethostname(temp_buff, 1024) == 0) { return string(temp_buff); } return string(); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::new_connection // Access: Protected // Description: This internal function is called whenever a new // connection is established. It allows the // ConnectionManager to save all of the pointers to open // connections so they can't be inadvertently deleted // until close_connection() is called. //////////////////////////////////////////////////////////////////// void ConnectionManager:: new_connection(const PT(Connection) &connection) { LightMutexHolder holder(_set_mutex); _connections.insert(connection); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::flush_read_connection // Access: Protected, Virtual // Description: An internal function called by ConnectionWriter only // when a write failure has occurred. This method // ensures that all of the read data has been flushed // from the pipe before the connection is fully removed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: flush_read_connection(Connection *connection) { Readers readers; { LightMutexHolder holder(_set_mutex); Connections::iterator ci = _connections.find(connection); if (ci == _connections.end()) { // Already closed, or not part of this ConnectionManager. return; } _connections.erase(ci); // Get a copy first, so we can release the lock before traversing. readers = _readers; } Readers::iterator ri; for (ri = readers.begin(); ri != readers.end(); ++ri) { (*ri)->flush_read_connection(connection); } Socket_IP *socket = connection->get_socket(); socket->Close(); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::connection_reset // Access: Protected, Virtual // Description: An internal function called by the ConnectionReader, // ConnectionWriter, or ConnectionListener when a // connection has been externally reset. This adds the // connection to the queue of those which have recently // been reset. //////////////////////////////////////////////////////////////////// void ConnectionManager:: connection_reset(const PT(Connection) &connection, bool okflag) { if (net_cat.is_info()) { if (okflag) { net_cat.info() << "Connection " << (void *)connection << " was closed normally by the other end"; } else { net_cat.info() << "Lost connection " << (void *)connection << " unexpectedly\n"; } } // Turns out we do need to explicitly mark the connection as closed // immediately, rather than waiting for the user to do it, since // otherwise we'll keep trying to listen for noise on the socket and // we'll always hear a "yes" answer. close_connection(connection); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::add_reader // Access: Protected // Description: This internal function is called by ConnectionReader // when it is constructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: add_reader(ConnectionReader *reader) { LightMutexHolder holder(_set_mutex); _readers.insert(reader); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::remove_reader // Access: Protected // Description: This internal function is called by ConnectionReader // when it is destructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: remove_reader(ConnectionReader *reader) { LightMutexHolder holder(_set_mutex); _readers.erase(reader); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::add_writer // Access: Protected // Description: This internal function is called by ConnectionWriter // when it is constructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: add_writer(ConnectionWriter *writer) { LightMutexHolder holder(_set_mutex); _writers.insert(writer); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::remove_writer // Access: Protected // Description: This internal function is called by ConnectionWriter // when it is destructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: remove_writer(ConnectionWriter *writer) { LightMutexHolder holder(_set_mutex); _writers.erase(writer); } <commit_msg>fix identification of failed TCP connection<commit_after>// Filename: connectionManager.cxx // Created by: jns (07Feb00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "connectionManager.h" #include "connection.h" #include "connectionReader.h" #include "connectionWriter.h" #include "netAddress.h" #include "config_net.h" #include "lightMutexHolder.h" #include "trueClock.h" #if defined(WIN32_VC) || defined(WIN64_VC) #include <winsock2.h> // For gethostname() #endif //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// ConnectionManager:: ConnectionManager() : _set_mutex("ConnectionManager::_set_mutex") { } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::Destructor // Access: Public, Virtual // Description: //////////////////////////////////////////////////////////////////// ConnectionManager:: ~ConnectionManager() { // Notify all of our associated readers and writers that we're gone. Readers::iterator ri; for (ri = _readers.begin(); ri != _readers.end(); ++ri) { (*ri)->clear_manager(); } Writers::iterator wi; for (wi = _writers.begin(); wi != _writers.end(); ++wi) { (*wi)->clear_manager(); } } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_UDP_connection // Access: Public // Description: Opens a socket for sending and/or receiving UDP // packets. If the port number is greater than zero, // the UDP connection will be opened for listening on // the indicated port; otherwise, it will be useful only // for sending. // // Use a ConnectionReader and ConnectionWriter to handle // the actual communication. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_UDP_connection(int port) { Socket_UDP *socket = new Socket_UDP; if (port > 0) { NetAddress address; address.set_any(port); if (!socket->OpenForInput(address.get_addr())) { net_cat.error() << "Unable to bind to port " << port << " for UDP.\n"; delete socket; return PT(Connection)(); } net_cat.info() << "Creating UDP connection for port " << port << "\n"; } else { if (!socket->InitNoAddress()) { net_cat.error() << "Unable to initialize outgoing UDP.\n"; delete socket; return PT(Connection)(); } net_cat.info() << "Creating outgoing UDP connection\n"; } PT(Connection) connection = new Connection(this, socket); new_connection(connection); return connection; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_server_rendezvous // Access: Public // Description: Creates a socket to be used as a rendezvous socket // for a server to listen for TCP connections. The // socket returned by this call should only be added to // a ConnectionListener (not to a generic // ConnectionReader). // // This variant of this method accepts a single port, // and will listen to that port on all available // interfaces. // // backlog is the maximum length of the queue of pending // connections. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_server_rendezvous(int port, int backlog) { NetAddress address; address.set_any(port); return open_TCP_server_rendezvous(address, backlog); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_server_rendezvous // Access: Public // Description: Creates a socket to be used as a rendezvous socket // for a server to listen for TCP connections. The // socket returned by this call should only be added to // a ConnectionListener (not to a generic // ConnectionReader). // // This variant of this method accepts a "hostname", // which is usually just an IP address in dotted // notation, and a port number. It will listen on the // interface indicated by the IP address. If the IP // address is empty string, it will listen on all // interfaces. // // backlog is the maximum length of the queue of pending // connections. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_server_rendezvous(const string &hostname, int port, int backlog) { NetAddress address; if (hostname.empty()) { address.set_any(port); } else { address.set_host(hostname, port); } return open_TCP_server_rendezvous(address, backlog); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_server_rendezvous // Access: Public // Description: Creates a socket to be used as a rendezvous socket // for a server to listen for TCP connections. The // socket returned by this call should only be added to // a ConnectionListener (not to a generic // ConnectionReader). // // This variant of this method accepts a NetAddress, // which allows you to specify a specific interface to // listen to. // // backlog is the maximum length of the queue of pending // connections. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_server_rendezvous(const NetAddress &address, int backlog) { ostringstream strm; if (address.get_ip() == 0) { strm << "port " << address.get_port(); } else { strm << address.get_ip_string() << ":" << address.get_port(); } Socket_TCP_Listen *socket = new Socket_TCP_Listen; bool okflag = socket->OpenForListen(address.get_addr(), backlog); if (!okflag) { net_cat.info() << "Unable to listen to " << strm.str() << " for TCP.\n"; delete socket; return PT(Connection)(); } net_cat.info() << "Listening for TCP connections on " << strm.str() << "\n"; PT(Connection) connection = new Connection(this, socket); new_connection(connection); return connection; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_client_connection // Access: Public // Description: Attempts to establish a TCP client connection to a // server at the indicated address. If the connection // is not established within timeout_ms milliseconds, a // null connection is returned. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_client_connection(const NetAddress &address, int timeout_ms) { Socket_TCP *socket = new Socket_TCP; // We always open the connection with non-blocking mode first, so we // can implement the timeout. bool okflag = socket->ActiveOpenNonBlocking(address.get_addr()); if (okflag && socket->GetLastError() == LOCAL_CONNECT_BLOCKING) { // Now wait for the socket to connect. TrueClock *clock = TrueClock::get_global_ptr(); double start = clock->get_short_time(); Thread::force_yield(); Socket_fdset fset; fset.setForSocket(*socket); int ready = fset.WaitForWrite(true, 0); while (ready == 0) { double elapsed = clock->get_short_time() - start; if (elapsed * 1000.0 > timeout_ms) { // Timeout. okflag = false; break; } Thread::force_yield(); fset.setForSocket(*socket); ready = fset.WaitForWrite(true, 0); } } if (okflag) { // So, the connect() operation finished, but did it succeed or fail? if (socket->GetPeerName().GetIPAddressRaw() == 0) { // No peer means it failed. okflag = false; } } if (!okflag) { net_cat.error() << "Unable to open TCP connection to server " << address.get_ip_string() << " on port " << address.get_port() << "\n"; delete socket; return PT(Connection)(); } #if !defined(HAVE_THREADS) || !defined(SIMPLE_THREADS) // Now we have opened the socket in nonblocking mode. Unless we're // using SIMPLE_THREADS, though, we really want the socket in // blocking mode (since that's what we support here). Change it. socket->SetBlocking(); #endif // SIMPLE_THREADS net_cat.info() << "Opened TCP connection to server " << address.get_ip_string() << " " << " on port " << address.get_port() << "\n"; PT(Connection) connection = new Connection(this, socket); new_connection(connection); return connection; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::open_TCP_client_connection // Access: Public // Description: This is a shorthand version of the function to // directly establish communications to a named host and // port. //////////////////////////////////////////////////////////////////// PT(Connection) ConnectionManager:: open_TCP_client_connection(const string &hostname, int port, int timeout_ms) { NetAddress address; if (!address.set_host(hostname, port)) { return PT(Connection)(); } return open_TCP_client_connection(address, timeout_ms); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::close_connection // Access: Public // Description: Terminates a UDP or TCP socket previously opened. // This also removes it from any associated // ConnectionReader or ConnectionListeners. // // The socket itself may not be immediately closed--it // will not be closed until all outstanding pointers to // it are cleared, including any pointers remaining in // NetDatagrams recently received from the socket. // // The return value is true if the connection was marked // to be closed, or false if close_connection() had // already been called (or the connection did not belong // to this ConnectionManager). In neither case can you // infer anything about whether the connection has // *actually* been closed yet based on the return value. //////////////////////////////////////////////////////////////////// bool ConnectionManager:: close_connection(const PT(Connection) &connection) { if (connection != (Connection *)NULL) { connection->flush(); } { LightMutexHolder holder(_set_mutex); Connections::iterator ci = _connections.find(connection); if (ci == _connections.end()) { // Already closed, or not part of this ConnectionManager. return false; } _connections.erase(ci); Readers::iterator ri; for (ri = _readers.begin(); ri != _readers.end(); ++ri) { (*ri)->remove_connection(connection); } } Socket_IP *socket = connection->get_socket(); // We can't *actually* close the connection right now, because // there might be outstanding pointers to it. But we can at least // shut it down. It will be eventually closed when all the // pointers let go. net_cat.info() << "Shutting down connection " << (void *)connection << " locally.\n"; socket->Close(); return true; } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::get_host_name // Access: Public, Static // Description: Returns the name of this particular machine on the // network, if available, or the empty string if the // hostname cannot be determined. //////////////////////////////////////////////////////////////////// string ConnectionManager:: get_host_name() { char temp_buff[1024]; if (gethostname(temp_buff, 1024) == 0) { return string(temp_buff); } return string(); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::new_connection // Access: Protected // Description: This internal function is called whenever a new // connection is established. It allows the // ConnectionManager to save all of the pointers to open // connections so they can't be inadvertently deleted // until close_connection() is called. //////////////////////////////////////////////////////////////////// void ConnectionManager:: new_connection(const PT(Connection) &connection) { LightMutexHolder holder(_set_mutex); _connections.insert(connection); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::flush_read_connection // Access: Protected, Virtual // Description: An internal function called by ConnectionWriter only // when a write failure has occurred. This method // ensures that all of the read data has been flushed // from the pipe before the connection is fully removed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: flush_read_connection(Connection *connection) { Readers readers; { LightMutexHolder holder(_set_mutex); Connections::iterator ci = _connections.find(connection); if (ci == _connections.end()) { // Already closed, or not part of this ConnectionManager. return; } _connections.erase(ci); // Get a copy first, so we can release the lock before traversing. readers = _readers; } Readers::iterator ri; for (ri = readers.begin(); ri != readers.end(); ++ri) { (*ri)->flush_read_connection(connection); } Socket_IP *socket = connection->get_socket(); socket->Close(); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::connection_reset // Access: Protected, Virtual // Description: An internal function called by the ConnectionReader, // ConnectionWriter, or ConnectionListener when a // connection has been externally reset. This adds the // connection to the queue of those which have recently // been reset. //////////////////////////////////////////////////////////////////// void ConnectionManager:: connection_reset(const PT(Connection) &connection, bool okflag) { if (net_cat.is_info()) { if (okflag) { net_cat.info() << "Connection " << (void *)connection << " was closed normally by the other end"; } else { net_cat.info() << "Lost connection " << (void *)connection << " unexpectedly\n"; } } // Turns out we do need to explicitly mark the connection as closed // immediately, rather than waiting for the user to do it, since // otherwise we'll keep trying to listen for noise on the socket and // we'll always hear a "yes" answer. close_connection(connection); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::add_reader // Access: Protected // Description: This internal function is called by ConnectionReader // when it is constructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: add_reader(ConnectionReader *reader) { LightMutexHolder holder(_set_mutex); _readers.insert(reader); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::remove_reader // Access: Protected // Description: This internal function is called by ConnectionReader // when it is destructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: remove_reader(ConnectionReader *reader) { LightMutexHolder holder(_set_mutex); _readers.erase(reader); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::add_writer // Access: Protected // Description: This internal function is called by ConnectionWriter // when it is constructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: add_writer(ConnectionWriter *writer) { LightMutexHolder holder(_set_mutex); _writers.insert(writer); } //////////////////////////////////////////////////////////////////// // Function: ConnectionManager::remove_writer // Access: Protected // Description: This internal function is called by ConnectionWriter // when it is destructed. //////////////////////////////////////////////////////////////////// void ConnectionManager:: remove_writer(ConnectionWriter *writer) { LightMutexHolder holder(_set_mutex); _writers.erase(writer); } <|endoftext|>
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/popo/server_options.hpp" #include "test.hpp" namespace { using namespace ::testing; TEST(ServerOptions_test, SerializationRoundTripIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "888f49c2-0b70-4033-a13a-175dbc1b8e38"); iox::popo::ServerOptions defaultOptions; iox::popo::ServerOptions testOptions; testOptions.requestQueueCapacity = 42; testOptions.nodeName = "hypnotoad"; testOptions.offerOnCreate = false; testOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER; testOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; iox::popo::ServerOptions::deserialize(testOptions.serialize()) .and_then([&](auto& roundTripOptions) { EXPECT_THAT(roundTripOptions.requestQueueCapacity, Ne(defaultOptions.requestQueueCapacity)); EXPECT_THAT(roundTripOptions.requestQueueCapacity, Eq(testOptions.requestQueueCapacity)); EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName)); EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName)); EXPECT_THAT(roundTripOptions.offerOnCreate, Ne(defaultOptions.offerOnCreate)); EXPECT_THAT(roundTripOptions.offerOnCreate, Eq(testOptions.offerOnCreate)); EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Ne(defaultOptions.requestQueueFullPolicy)); EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Eq(testOptions.requestQueueFullPolicy)); EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Ne(defaultOptions.clientTooSlowPolicy)); EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Eq(testOptions.clientTooSlowPolicy)); }) .or_else([&](auto&) { FAIL() << "Serialization/Deserialization of ServerOptions failed!"; }); } TEST(ServerOptions_test, DeserializingBogusDataFails) { ::testing::Test::RecordProperty("TEST_ID", "ebc97c23-87df-484c-8c3c-1b76f1351997"); const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star"); iox::popo::ServerOptions::deserialize(bogusSerialization) .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; }) .or_else([&](auto&) { GTEST_SUCCEED(); }); } using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>; using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>; iox::cxx::Serialization enumSerialization(QueueFullPolicyUT requsetQueueFullPolicy, ConsumerTooSlowPolicyUT clientTooSlowPolicy) { constexpr uint64_t REQUEST_QUEUE_CAPACITY{42U}; const iox::NodeName_t NODE_NAME{"harr-harr"}; constexpr bool OFFER_ON_CREATE{true}; return iox::cxx::Serialization::create( REQUEST_QUEUE_CAPACITY, NODE_NAME, OFFER_ON_CREATE, requsetQueueFullPolicy, clientTooSlowPolicy); } TEST(ServerOptions_test, DeserializingValidRequestQueueFullPolicyAndClientTooSlowPolicyIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "95cd1efc-63c8-4eee-9f4e-ed105e653d71"); constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)}; constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)}; const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY); iox::popo::ServerOptions::deserialize(serialized).and_then([&](auto&) { GTEST_SUCCEED(); }).or_else([&](auto&) { GTEST_FAIL() << "Serialization/Deserialization of ServerOptions failed!"; }); } TEST(ServerOptions_test, DeserializingInvalidRequestQueueFullPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "3d392b0a-6140-4b06-a08d-b06ad27f31cd"); constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{123}; constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)}; const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY); iox::popo::ServerOptions::deserialize(serialized) .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; }) .or_else([&](auto&) { GTEST_SUCCEED(); }); } TEST(ServerOptions_test, DeserializingInvalidClientTooSlowPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "35b85d5a-7e59-4f0c-8afc-38f1eec914b8"); constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA)}; constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{111}; const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY); iox::popo::ServerOptions::deserialize(serialized) .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; }) .or_else([&](auto&) { GTEST_SUCCEED(); }); } } // namespace <commit_msg>iox-#27 Add tests for comparison operator for ServerOptions<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/popo/server_options.hpp" #include "test.hpp" namespace { using namespace ::testing; using namespace iox::popo; TEST(ServerOptions_test, SerializationRoundTripIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "888f49c2-0b70-4033-a13a-175dbc1b8e38"); iox::popo::ServerOptions defaultOptions; iox::popo::ServerOptions testOptions; testOptions.requestQueueCapacity = 42; testOptions.nodeName = "hypnotoad"; testOptions.offerOnCreate = false; testOptions.requestQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER; testOptions.clientTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; iox::popo::ServerOptions::deserialize(testOptions.serialize()) .and_then([&](auto& roundTripOptions) { EXPECT_THAT(roundTripOptions.requestQueueCapacity, Ne(defaultOptions.requestQueueCapacity)); EXPECT_THAT(roundTripOptions.requestQueueCapacity, Eq(testOptions.requestQueueCapacity)); EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName)); EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName)); EXPECT_THAT(roundTripOptions.offerOnCreate, Ne(defaultOptions.offerOnCreate)); EXPECT_THAT(roundTripOptions.offerOnCreate, Eq(testOptions.offerOnCreate)); EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Ne(defaultOptions.requestQueueFullPolicy)); EXPECT_THAT(roundTripOptions.requestQueueFullPolicy, Eq(testOptions.requestQueueFullPolicy)); EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Ne(defaultOptions.clientTooSlowPolicy)); EXPECT_THAT(roundTripOptions.clientTooSlowPolicy, Eq(testOptions.clientTooSlowPolicy)); }) .or_else([&](auto&) { FAIL() << "Serialization/Deserialization of ServerOptions failed!"; }); } TEST(ServerOptions_test, DeserializingBogusDataFails) { ::testing::Test::RecordProperty("TEST_ID", "ebc97c23-87df-484c-8c3c-1b76f1351997"); const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star"); iox::popo::ServerOptions::deserialize(bogusSerialization) .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; }) .or_else([&](auto&) { GTEST_SUCCEED(); }); } using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>; using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>; iox::cxx::Serialization enumSerialization(QueueFullPolicyUT requsetQueueFullPolicy, ConsumerTooSlowPolicyUT clientTooSlowPolicy) { constexpr uint64_t REQUEST_QUEUE_CAPACITY{42U}; const iox::NodeName_t NODE_NAME{"harr-harr"}; constexpr bool OFFER_ON_CREATE{true}; return iox::cxx::Serialization::create( REQUEST_QUEUE_CAPACITY, NODE_NAME, OFFER_ON_CREATE, requsetQueueFullPolicy, clientTooSlowPolicy); } TEST(ServerOptions_test, DeserializingValidRequestQueueFullPolicyAndClientTooSlowPolicyIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "95cd1efc-63c8-4eee-9f4e-ed105e653d71"); constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)}; constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)}; const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY); iox::popo::ServerOptions::deserialize(serialized).and_then([&](auto&) { GTEST_SUCCEED(); }).or_else([&](auto&) { GTEST_FAIL() << "Serialization/Deserialization of ServerOptions failed!"; }); } TEST(ServerOptions_test, DeserializingInvalidRequestQueueFullPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "3d392b0a-6140-4b06-a08d-b06ad27f31cd"); constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{123}; constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)}; const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY); iox::popo::ServerOptions::deserialize(serialized) .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; }) .or_else([&](auto&) { GTEST_SUCCEED(); }); } TEST(ServerOptions_test, DeserializingInvalidClientTooSlowPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "35b85d5a-7e59-4f0c-8afc-38f1eec914b8"); constexpr QueueFullPolicyUT REQUEST_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::DISCARD_OLDEST_DATA)}; constexpr ConsumerTooSlowPolicyUT CLIENT_TOO_SLOW_POLICY{111}; const auto serialized = enumSerialization(REQUEST_QUEUE_FULL_POLICY, CLIENT_TOO_SLOW_POLICY); iox::popo::ServerOptions::deserialize(serialized) .and_then([&](auto&) { GTEST_FAIL() << "Deserialization is expected to fail!"; }) .or_else([&](auto&) { GTEST_SUCCEED(); }); } TEST(ServerOptions_test, ComparisonOperatorReturnsTrueWhenEqual) { ::testing::Test::RecordProperty("TEST_ID", "98e68269-94d0-41bb-b8a8-5b06ac0b7bc0"); ServerOptions options1; ServerOptions options2; EXPECT_TRUE(options1 == options1); EXPECT_TRUE(options1 == options2); EXPECT_TRUE(options2 == options1); } TEST(ServerOptions_test, ComparisonOperatorReturnsFalseWhenRequestQueueCapacityDoesNotMatch) { ::testing::Test::RecordProperty("TEST_ID", "5fede46a-ddfd-426b-a237-25b3088ee011"); ServerOptions options1; options1.requestQueueCapacity = 42; ServerOptions options2; options2.requestQueueCapacity = 73; EXPECT_FALSE(options1 == options2); EXPECT_FALSE(options2 == options1); } TEST(ServerOptions_test, ComparisonOperatorReturnsFalseWhenNodeNameDoesNotMatch) { ::testing::Test::RecordProperty("TEST_ID", "fed82e4a-5037-4a77-9b28-e0ca8ec7ad5d"); ServerOptions options1; options1.nodeName = "kirk"; ServerOptions options2; options2.nodeName = "picard"; EXPECT_FALSE(options1 == options2); EXPECT_FALSE(options2 == options1); } TEST(ServerOptions_test, ComparisonOperatorReturnsFalseWhenOfferOnCreateDoesNotMatch) { ::testing::Test::RecordProperty("TEST_ID", "7831b7c7-72b1-4acf-8a95-fd7ee2348835"); ServerOptions options1; options1.offerOnCreate = false; ServerOptions options2; options2.offerOnCreate = true; EXPECT_FALSE(options1 == options2); EXPECT_FALSE(options2 == options1); } TEST(ServerOptions_test, ComparisonOperatorReturnsFalseRequestQueueFullPolicyDoesNotMatch) { ::testing::Test::RecordProperty("TEST_ID", "cc97e01c-94f7-41a9-8fac-19db1fd2d20e"); ServerOptions options1; options1.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER; ServerOptions options2; options2.requestQueueFullPolicy = QueueFullPolicy::DISCARD_OLDEST_DATA; EXPECT_FALSE(options1 == options2); EXPECT_FALSE(options2 == options1); } TEST(ServerOptions_test, ComparisonOperatorReturnsFalseClientTooSlowPolicyDoesNotMatch) { ::testing::Test::RecordProperty("TEST_ID", "80c7e7a3-084c-48e1-aa3c-d51688c41682"); ServerOptions options1; options1.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; ServerOptions options2; options2.clientTooSlowPolicy = ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA; EXPECT_FALSE(options1 == options2); EXPECT_FALSE(options2 == options1); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_layout_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/escape.h" #include "net/test/test_server.h" struct IsSearchProviderTestData; class SearchProviderTest : public UITest { protected: SearchProviderTest(); IsSearchProviderTestData StartIsSearchProviderInstalledTest( BrowserProxy* browser_proxy, const char* host, const char* expected_result); void FinishIsSearchProviderInstalledTest( const IsSearchProviderTestData& data); net::TestServer test_server_; private: DISALLOW_COPY_AND_ASSIGN(SearchProviderTest); }; SearchProviderTest::SearchProviderTest() : test_server_(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))) { // Enable the search provider additions. launch_arguments_.AppendSwitch(switches::kEnableSearchProviderApiV2); // Map all hosts to our local server. std::string host_rule("MAP * " + test_server_.host_port_pair().ToString()); launch_arguments_.AppendSwitchASCII(switches::kHostRules, host_rule); } struct IsSearchProviderTestData { IsSearchProviderTestData() { } IsSearchProviderTestData(TabProxy* t, std::string h, GURL url) : tab(t), host(h), test_url(url) { } scoped_refptr<TabProxy> tab; std::string host; GURL test_url; }; IsSearchProviderTestData SearchProviderTest::StartIsSearchProviderInstalledTest( BrowserProxy* browser_proxy, const char* host, const char* expected_result) { // Set-up a new tab for the navigation. int num_tabs = 0; if (!browser_proxy->GetTabCount(&num_tabs)) { ADD_FAILURE() << "BrowserProxy::GetTabCount failed."; return IsSearchProviderTestData(); } GURL blank(chrome::kAboutBlankURL); if (!browser_proxy->AppendTab(blank)) { ADD_FAILURE() << "BrowserProxy::AppendTab failed."; return IsSearchProviderTestData(); } scoped_refptr<TabProxy> tab(browser_proxy->GetTab(num_tabs)); if (!tab.get()) { ADD_FAILURE() << "BrowserProxy::GetTab for the new tab failed."; return IsSearchProviderTestData(); } // Go to the test page. GURL local_url = test_server_.GetURL("files/is_search_provider_installed.html"); GURL test_url(std::string("http://") + host + local_url.path() + "#" + expected_result); EXPECT_TRUE(tab->NavigateToURLAsync(test_url)); // Bundle up information needed to verify the result. return IsSearchProviderTestData(tab, host, test_url); } void SearchProviderTest::FinishIsSearchProviderInstalledTest( const IsSearchProviderTestData& data) { ASSERT_TRUE(data.tab.get()); std::string cookie_name = data.host + "testResult"; std::string escaped_value = WaitUntilCookieNonEmpty(data.tab, data.test_url, cookie_name.c_str(), action_max_timeout_ms()); // Unescapes and normalizes the actual result. std::string value = UnescapeURLComponent( escaped_value, UnescapeRule::NORMAL | UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS); value += "\n"; ReplaceSubstringsAfterOffset(&value, 0, "\r", ""); EXPECT_STREQ("1\n", value.c_str()); } TEST_F(SearchProviderTest, TestIsSearchProviderInstalled) { ASSERT_TRUE(test_server_.Start()); // Use the default search provider, other installed search provider, and // one not installed as well. (Note that yahoo isn't tested because the // its host name varies a lot for different locales unlike Google and Bing, // which would make the test fail depending on the machine's locale.) const char* test_hosts[] = { "www.google.com", "www.bing.com", "localhost" }; const char* expected_results[] = { "2", "1", "0" }; COMPILE_ASSERT(arraysize(test_hosts) == arraysize(expected_results), there_should_be_a_result_for_each_host); IsSearchProviderTestData test_data[2 * arraysize(test_hosts)]; // Start results for the normal mode. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); for (size_t i = 0; i < arraysize(test_hosts); ++i) { test_data[i] = StartIsSearchProviderInstalledTest( browser, test_hosts[i], expected_results[i]); } // Start tests for incognito mode (and verify the result is 0). ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW)); scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1)); ASSERT_TRUE(incognito.get()); for (size_t i = 0; i < arraysize(test_hosts); ++i) { test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest( incognito, test_hosts[i], "0"); } // Do the verification. for (size_t i = 0; i < arraysize(test_data); ++i) { FinishIsSearchProviderInstalledTest(test_data[i]); } } <commit_msg>Mark SearchProviderTest.TestIsSearchProviderInstalled as flaky.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_layout_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/escape.h" #include "net/test/test_server.h" struct IsSearchProviderTestData; class SearchProviderTest : public UITest { protected: SearchProviderTest(); IsSearchProviderTestData StartIsSearchProviderInstalledTest( BrowserProxy* browser_proxy, const char* host, const char* expected_result); void FinishIsSearchProviderInstalledTest( const IsSearchProviderTestData& data); net::TestServer test_server_; private: DISALLOW_COPY_AND_ASSIGN(SearchProviderTest); }; SearchProviderTest::SearchProviderTest() : test_server_(net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("chrome/test/data"))) { // Enable the search provider additions. launch_arguments_.AppendSwitch(switches::kEnableSearchProviderApiV2); // Map all hosts to our local server. std::string host_rule("MAP * " + test_server_.host_port_pair().ToString()); launch_arguments_.AppendSwitchASCII(switches::kHostRules, host_rule); } struct IsSearchProviderTestData { IsSearchProviderTestData() { } IsSearchProviderTestData(TabProxy* t, std::string h, GURL url) : tab(t), host(h), test_url(url) { } scoped_refptr<TabProxy> tab; std::string host; GURL test_url; }; IsSearchProviderTestData SearchProviderTest::StartIsSearchProviderInstalledTest( BrowserProxy* browser_proxy, const char* host, const char* expected_result) { // Set-up a new tab for the navigation. int num_tabs = 0; if (!browser_proxy->GetTabCount(&num_tabs)) { ADD_FAILURE() << "BrowserProxy::GetTabCount failed."; return IsSearchProviderTestData(); } GURL blank(chrome::kAboutBlankURL); if (!browser_proxy->AppendTab(blank)) { ADD_FAILURE() << "BrowserProxy::AppendTab failed."; return IsSearchProviderTestData(); } scoped_refptr<TabProxy> tab(browser_proxy->GetTab(num_tabs)); if (!tab.get()) { ADD_FAILURE() << "BrowserProxy::GetTab for the new tab failed."; return IsSearchProviderTestData(); } // Go to the test page. GURL local_url = test_server_.GetURL("files/is_search_provider_installed.html"); GURL test_url(std::string("http://") + host + local_url.path() + "#" + expected_result); EXPECT_TRUE(tab->NavigateToURLAsync(test_url)); // Bundle up information needed to verify the result. return IsSearchProviderTestData(tab, host, test_url); } void SearchProviderTest::FinishIsSearchProviderInstalledTest( const IsSearchProviderTestData& data) { ASSERT_TRUE(data.tab.get()); std::string cookie_name = data.host + "testResult"; std::string escaped_value = WaitUntilCookieNonEmpty(data.tab, data.test_url, cookie_name.c_str(), action_max_timeout_ms()); // Unescapes and normalizes the actual result. std::string value = UnescapeURLComponent( escaped_value, UnescapeRule::NORMAL | UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS); value += "\n"; ReplaceSubstringsAfterOffset(&value, 0, "\r", ""); EXPECT_STREQ("1\n", value.c_str()); } // Flaky, http://crbug.com/57405. TEST_F(SearchProviderTest, FLAKY_TestIsSearchProviderInstalled) { ASSERT_TRUE(test_server_.Start()); // Use the default search provider, other installed search provider, and // one not installed as well. (Note that yahoo isn't tested because the // its host name varies a lot for different locales unlike Google and Bing, // which would make the test fail depending on the machine's locale.) const char* test_hosts[] = { "www.google.com", "www.bing.com", "localhost" }; const char* expected_results[] = { "2", "1", "0" }; COMPILE_ASSERT(arraysize(test_hosts) == arraysize(expected_results), there_should_be_a_result_for_each_host); IsSearchProviderTestData test_data[2 * arraysize(test_hosts)]; // Start results for the normal mode. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); for (size_t i = 0; i < arraysize(test_hosts); ++i) { test_data[i] = StartIsSearchProviderInstalledTest( browser, test_hosts[i], expected_results[i]); } // Start tests for incognito mode (and verify the result is 0). ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW)); scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1)); ASSERT_TRUE(incognito.get()); for (size_t i = 0; i < arraysize(test_hosts); ++i) { test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest( incognito, test_hosts[i], "0"); } // Do the verification. for (size_t i = 0; i < arraysize(test_data); ++i) { FinishIsSearchProviderInstalledTest(test_data[i]); } } <|endoftext|>
<commit_before>/* $Id: middlewareGeneralTests.cpp,v 1.1.2.7 2013/02/01 17:26:58 matthewmulhern Exp $ * * OpenMAMA: The open middleware agnostic messaging API * Copyright (C) 2011 NYSE Technologies, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 <gtest/gtest.h> #include "mama/mama.h" #include "MainUnitTestC.h" #include <iostream> #include "bridge.h" #include "mama/types.h" using std::cout; using std::endl; class MiddlewareGeneralTests : public ::testing::Test { protected: MiddlewareGeneralTests(void); virtual ~MiddlewareGeneralTests(void); virtual void SetUp(void); virtual void TearDown(void); mamaBridge mBridge; }; MiddlewareGeneralTests::MiddlewareGeneralTests(void) { } MiddlewareGeneralTests::~MiddlewareGeneralTests(void) { } void MiddlewareGeneralTests::SetUp(void) { mama_loadBridge (&mBridge,getMiddleware()); } void MiddlewareGeneralTests::TearDown(void) { } /*=================================================================== = Used in mama.c = ====================================================================*/ TEST_F (MiddlewareGeneralTests, open) { ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeOpen(mBridge)); } TEST_F (MiddlewareGeneralTests, openInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeOpen(NULL)); } TEST_F (MiddlewareGeneralTests, DISABLED_openClose) /*calling bridgeClose in this test causes next test to seg fault always*/ { ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeOpen(mBridge)); ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeClose(mBridge)); } TEST_F (MiddlewareGeneralTests, closeInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeClose(NULL)); } TEST_F (MiddlewareGeneralTests, DISABLED_startStop) /* hangs, bridgeClose never executed */ /* MH - Seems to be an issue in wSemaphore.c with the sem_timedwait() function */ { mamaQueue defaultEventQueue = NULL; ASSERT_EQ (MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge, &defaultEventQueue)); ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeStart(defaultEventQueue)); ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeStop(defaultEventQueue)); } TEST_F (MiddlewareGeneralTests, startInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStart(NULL)); } TEST_F (MiddlewareGeneralTests, stopInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStop(NULL)); } TEST_F (MiddlewareGeneralTests, getVersion) { const char* res = "0.0"; res = mBridge->bridgeGetVersion(); ASSERT_TRUE (res != NULL); } TEST_F (MiddlewareGeneralTests, getName) { const char* res = "name"; res = mBridge->bridgeGetName(); ASSERT_TRUE (res != NULL); } TEST_F (MiddlewareGeneralTests, getDefaultPayloadId) { char** names = {NULL}; char* id = "id"; ASSERT_EQ (MAMA_STATUS_OK, mBridge-> bridgeGetDefaultPayloadId(&names,&id)); } TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidName) { char* id = "id"; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge-> bridgeGetDefaultPayloadId(NULL,&id)); } TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidId) { char ** names; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge-> bridgeGetDefaultPayloadId(&names,NULL)); } <commit_msg>UNIT TESTS: Changes to middleware general tests.<commit_after>/* $Id: middlewareGeneralTests.cpp,v 1.1.2.7 2013/02/01 17:26:58 matthewmulhern Exp $ * * OpenMAMA: The open middleware agnostic messaging API * Copyright (C) 2011 NYSE Technologies, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 <gtest/gtest.h> #include "mama/mama.h" #include "MainUnitTestC.h" #include <iostream> #include "bridge.h" #include "mama/types.h" using std::cout; using std::endl; class MiddlewareGeneralTests : public ::testing::Test { protected: MiddlewareGeneralTests(void); virtual ~MiddlewareGeneralTests(void); virtual void SetUp(void); virtual void TearDown(void); mamaBridge mBridge; }; MiddlewareGeneralTests::MiddlewareGeneralTests(void) { } MiddlewareGeneralTests::~MiddlewareGeneralTests(void) { } void MiddlewareGeneralTests::SetUp(void) { mama_loadBridge (&mBridge,getMiddleware()); } void MiddlewareGeneralTests::TearDown(void) { } /*=================================================================== = Used in mama.c = ====================================================================*/ /* TODO: Rewrite this test to call bridgeStart on a separate thread, since it is * a blocking call. Otherwise, bridgeStop is never called. * */ TEST_F (MiddlewareGeneralTests, DISABLED_startStop) { mamaQueue defaultEventQueue = NULL; ASSERT_EQ (MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge, &defaultEventQueue)); ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeStart(defaultEventQueue)); ASSERT_EQ (MAMA_STATUS_OK, mBridge->bridgeStop(defaultEventQueue)); } TEST_F (MiddlewareGeneralTests, startInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStart(NULL)); } TEST_F (MiddlewareGeneralTests, stopInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeStop(NULL)); } TEST_F (MiddlewareGeneralTests, getVersion) { const char* res = "0.0"; res = mBridge->bridgeGetVersion(); ASSERT_TRUE (res != NULL); } TEST_F (MiddlewareGeneralTests, getName) { const char* res = "name"; res = mBridge->bridgeGetName(); ASSERT_TRUE (res != NULL); } TEST_F (MiddlewareGeneralTests, getDefaultPayloadId) { char** names = {NULL}; char* id = "id"; ASSERT_EQ (MAMA_STATUS_OK, mBridge-> bridgeGetDefaultPayloadId(&names,&id)); } TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidName) { char* id = "id"; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge-> bridgeGetDefaultPayloadId(NULL,&id)); } TEST_F (MiddlewareGeneralTests, getDefaultPayloadIdInvalidId) { char ** names; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge-> bridgeGetDefaultPayloadId(&names,NULL)); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/base/test_web_dialog_observer.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/test/js_injection_ready_observer.h" #include "content/public/test/test_utils.h" using content::NavigationController; TestWebDialogObserver::TestWebDialogObserver( content::JsInjectionReadyObserver* js_injection_ready_observer) : js_injection_ready_observer_(js_injection_ready_observer), web_ui_(NULL), done_(false), running_(false) { } TestWebDialogObserver::~TestWebDialogObserver() { } void TestWebDialogObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { break; case content::NOTIFICATION_LOAD_STOP: DCHECK(web_ui_); registrar_.Remove(this, content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>( &web_ui_->GetWebContents()->GetController())); done_ = true; // If the message loop is running stop it. if (running_) { running_ = false; message_loop_runner_->Quit(); } break; default: NOTREACHED(); }; } void TestWebDialogObserver::OnDialogShown( content::WebUI* webui, content::RenderViewHost* render_view_host) { if (js_injection_ready_observer_) { js_injection_ready_observer_->OnJsInjectionReady(render_view_host); } web_ui_ = webui; // Wait for navigation on the new WebUI instance to complete. This depends // on receiving the notification of the WebDialog being shown before the // NavigationController finishes loading. The WebDialog notification is // issued from web_dialog_ui.cc on RenderView creation which results from // the call to render_manager_.Navigate in the method // WebContents::NavigateToEntry. The new RenderView is later told to // navigate in this method, ensuring that this is not a race condition. registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>( &web_ui_->GetWebContents()->GetController())); } content::WebUI* TestWebDialogObserver::GetWebUI() { if (!done_) { EXPECT_FALSE(running_); running_ = true; message_loop_runner_ = new content::MessageLoopRunner; message_loop_runner_->Run(); } return web_ui_; } <commit_msg>chrome: Remove unused include from test_web_dialog_observer.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/base/test_web_dialog_observer.h" #include "base/logging.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/test/js_injection_ready_observer.h" #include "content/public/test/test_utils.h" using content::NavigationController; TestWebDialogObserver::TestWebDialogObserver( content::JsInjectionReadyObserver* js_injection_ready_observer) : js_injection_ready_observer_(js_injection_ready_observer), web_ui_(NULL), done_(false), running_(false) { } TestWebDialogObserver::~TestWebDialogObserver() { } void TestWebDialogObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { break; case content::NOTIFICATION_LOAD_STOP: DCHECK(web_ui_); registrar_.Remove(this, content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>( &web_ui_->GetWebContents()->GetController())); done_ = true; // If the message loop is running stop it. if (running_) { running_ = false; message_loop_runner_->Quit(); } break; default: NOTREACHED(); }; } void TestWebDialogObserver::OnDialogShown( content::WebUI* webui, content::RenderViewHost* render_view_host) { if (js_injection_ready_observer_) { js_injection_ready_observer_->OnJsInjectionReady(render_view_host); } web_ui_ = webui; // Wait for navigation on the new WebUI instance to complete. This depends // on receiving the notification of the WebDialog being shown before the // NavigationController finishes loading. The WebDialog notification is // issued from web_dialog_ui.cc on RenderView creation which results from // the call to render_manager_.Navigate in the method // WebContents::NavigateToEntry. The new RenderView is later told to // navigate in this method, ensuring that this is not a race condition. registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>( &web_ui_->GetWebContents()->GetController())); } content::WebUI* TestWebDialogObserver::GetWebUI() { if (!done_) { DCHECK(running_ == false); running_ = true; message_loop_runner_ = new content::MessageLoopRunner; message_loop_runner_->Run(); } return web_ui_; } <|endoftext|>
<commit_before>#include "callback_parameter.hpp" #include "callback_object.hpp" #include "cpp/ylikuutio/common/any_value.hpp" #include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string namespace callback_system { CallbackParameter::CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* parent_pointer) { // constructor. this->name = name; this->any_value = any_value; this->is_reference = is_reference; } CallbackParameter::~CallbackParameter() { // destructor. std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n"; // set pointer to this object to nullptr. this->parent_pointer->set_callback_parameter_pointer(this->childID, nullptr); } void CallbackParameter::bind_to_parent() { callback_system::CallbackObject* parent_pointer; parent_pointer = this->parent_pointer; std::vector<void*> callback_parameter_void_pointer_vector; callback_parameter_void_pointer_vector.assign(parent_pointer->callback_parameter_pointer_vector.begin(), parent_pointer->callback_parameter_pointer_vector.end()); hierarchy::bind_child_to_parent<callback_system::CallbackParameter*>(this, callback_parameter_void_pointer_vector, parent_pointer->free_callback_parameterID_queue); } } <commit_msg>`parent_pointer` of each `CallbackParameter` gets set now.<commit_after>#include "callback_parameter.hpp" #include "callback_object.hpp" #include "cpp/ylikuutio/common/any_value.hpp" #include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string namespace callback_system { CallbackParameter::CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* parent_pointer) { // constructor. this->name = name; this->any_value = any_value; this->is_reference = is_reference; this->parent_pointer = parent_pointer; } CallbackParameter::~CallbackParameter() { // destructor. std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n"; // set pointer to this object to nullptr. this->parent_pointer->set_callback_parameter_pointer(this->childID, nullptr); } void CallbackParameter::bind_to_parent() { callback_system::CallbackObject* parent_pointer; parent_pointer = this->parent_pointer; std::vector<void*> callback_parameter_void_pointer_vector; callback_parameter_void_pointer_vector.assign(parent_pointer->callback_parameter_pointer_vector.begin(), parent_pointer->callback_parameter_pointer_vector.end()); hierarchy::bind_child_to_parent<callback_system::CallbackParameter*>(this, callback_parameter_void_pointer_vector, parent_pointer->free_callback_parameterID_queue); } } <|endoftext|>
<commit_before>// $Id: DCDFile.C,v 1.5 2000/12/20 18:39:02 anker Exp $ #include <BALL/FORMAT/DCDFile.h> #include <BALL/MOLMEC/COMMON/snapShot.h> using namespace std; namespace BALL { DCDFile::DCDFile() throw() : TrajectoryFile(), header_(), swap_bytes_(false) { if (sizeof(int) != 4) { Log.error() << "DCDFile::DCDFile(): " << "Size of int is not equal to 4 on this machine." << endl; } if (sizeof(double) != 8) { Log.error() << "DCDFile::DCDFile(): " << "Size of double is not equal to 4 on this machine." << endl; } } DCDFile::DCDFile(const DCDFile& file) throw() : TrajectoryFile(), header_(file.header_), swap_bytes_(file.swap_bytes_) { if (sizeof(int) != 4) { Log.error() << "DCDFile::DCDFile(): " << "Size of int is not equal to 4 on this machine." << endl; } if (sizeof(double) != 8) { Log.error() << "DCDFile::DCDFile(): " << "Size of double is not equal to 4 on this machine." << endl; } } DCDFile::DCDFile(const String& name, File::OpenMode open_mode) throw() : TrajectoryFile(name, open_mode), header_(), swap_bytes_(false) { if (sizeof(int) != 4) { Log.error() << "DCDFile::DCDFile(): " << "Size of int is not equal to 4 on this machine." << endl; } if (sizeof(double) != 8) { Log.error() << "DCDFile::DCDFile(): " << "Size of double is not equal to 4 on this machine." << endl; } } DCDFile::~DCDFile() throw() { clear(); } const DCDFile& DCDFile::operator = (const DCDFile& file) throw() { TrajectoryFile::operator = (file); header_ = file.header_; return *this; } void DCDFile::clear() throw() { header_ = DCDHeader(); swap_bytes_ = false; TrajectoryFile::clear(); } bool DCDFile::operator == (const DCDFile& file) throw() { // BAUSTELLE: Header vergleichen. Was heit gleich eigentlich in diesem // Fall? return (TrajectoryFile::operator == (file)); } bool DCDFile::readHeader() throw() { return true; /* char fourbytes[4]; char eightyfourbytes[84]; int tmp_int; DCDHeader tmp_header; File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); if (tmp_int != 84) { // it might be a problem of endianness, so swap the bytes and test // again. // tmp_int = swapFourBytes(tmp_int); if (tmp_int != 84) { Log.error() << "DCDFile::readHeader(): " << "file seems corrupted (wrong magic number)" << endl; return false; } else { // we have to swap bytes... // if (verbosity > 1) // { Log.info() << "DCDFile::readHeader(): enabling byte swap" << endl; // } swap_bytes_ = true; } } // read this block File::read(eightyfourbytes, 84); if (swap_bytes_) { // BAUSTELLE } else { // check for "CORD" signature if ((eightyfourbytes[0] != 'C') || (eightyfourbytes[1] != 'O') || (eightyfourbytes[2] != 'O') || (eightyfourbytes[3] != 'D')) { Log.error() << "DCDFile::readHeader() " << "File seems to be corrupted (CORD missing)" << endl; return false; } tmp_header.number_of_coordinate_sets = *((int*)(eightyfourbytes + 4)); tmp_header.step_number_of_starting_time = *((int*)(eightyfourbytes + 8)); tmp_header.steps_between_saves = *((int*)(eightyfourbytes + 12)); tmp_header.time_step_length = *((double*)(eightyfourbytes + 40)); // check if the block is terminated correctly File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); if (tmp_int != 84) { Log.error() << "DCDFile::readHeader() " << "File seems to be corrupted (84 bytes incorrectly terninated)" << endl; return false; } // now handle the next block File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); // check if the length of the next block allows n titles of 80 chars // length int number_of_titles; if (((tmp_int - 4) % 80) == 0) { File::read(fourbytes, 4); number_of_titles = *((int*)fourbytes); // here we believe that the number stated in the file is correct. for (int i = 0; i < number_of_titles; ++i) { File::read(eightyfourbytes, 80); // BAUSTELLE jetzt noch was mit den titeln tun... } } else { Log.error() << "DCDFile::readHeader() " << "File seems to be corrupted (number of titles wrong)" << endl; return false; } File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); if (tmp_int != number_of_titles) { Log.error() << "DCDFile::readHeader(): " << "File seems to be corrupted (title block terminated incorrectly" << endl; return false; } // GROSSBAUSTELLE } return false; */ } bool DCDFile::updateHeader(const SnapShotManager& manager) throw() { // BAUSTELLE header_.number_of_coordinate_sets = manager.getNumberOfSnapShots(); header_.number_of_atoms = manager.getNumberOfAtoms(); return true; } bool DCDFile::writeHeader() throw() { // the following would be nice. Unfortunately the compiler does strange // things when storing the struct in memory... // *this << BinaryFileAdaptor<struct DCDHeader>(header_); Size i; *this << BinaryFileAdaptor<Size>(header_.start_info_block); for (i = 0; i < 4; ++i) { *this << BinaryFileAdaptor<char>(header_.CORD[i]); } *this << BinaryFileAdaptor<Size>(header_.number_of_coordinate_sets); *this << BinaryFileAdaptor<Size>(header_.step_number_of_starting_time); *this << BinaryFileAdaptor<Size>(header_.steps_between_saves); for (i = 0; i < 6; ++i) { *this << BinaryFileAdaptor<Size>(header_.unused_1[i]); } *this << BinaryFileAdaptor<DoubleReal>(header_.time_step_length); for (i = 0; i < 9; ++i) { *this << BinaryFileAdaptor<Size>(header_.unused_2[i]); } *this << BinaryFileAdaptor<Size>(header_.end_info_block); *this << BinaryFileAdaptor<Size>(header_.start_title_block); *this << BinaryFileAdaptor<Size>(header_.number_of_comments); for (i = 0; i < 160; ++i) { *this << BinaryFileAdaptor<char>(header_.title[i]); } *this << BinaryFileAdaptor<Size>(header_.end_title_block); *this << BinaryFileAdaptor<Size>(header_.start_atomnumber_block); *this << BinaryFileAdaptor<Size>(header_.number_of_atoms); *this << BinaryFileAdaptor<Size>(header_.end_atomnumber_block); return true; } bool DCDFile::read(SnapShotManager& /* manager */) throw(Exception::NotImplemented) { throw Exception::NotImplemented(__FILE__, __LINE__); return false; } bool DCDFile::write(const SnapShotManager& /* manager */) throw(Exception::NotImplemented) { throw Exception::NotImplemented(__FILE__, __LINE__); return false; } bool DCDFile::append(const SnapShot& snapshot) throw() { Size noa = snapshot.getNumberOfAtoms(); vector<Vector3> positions = snapshot.getAtomPositions(); if (positions.size() == 0) { Log.error() << "DCDFile::append(): " << "No atom positions available" << endl; return false; } *this << BinaryFileAdaptor<Size>(4*noa); for (Size atom = 0; atom < noa; ++atom) { *this << BinaryFileAdaptor<Real>((Real) positions[atom].x); } *this << BinaryFileAdaptor<Size>(4*noa); *this << BinaryFileAdaptor<Size>(4*noa); for (Size atom = 0; atom < noa; ++atom) { *this << BinaryFileAdaptor<Real>((Real) positions[atom].y); } *this << BinaryFileAdaptor<Size>(4*noa); *this << BinaryFileAdaptor<Size>(4*noa); for (Size atom = 0; atom < noa; ++atom) { *this << BinaryFileAdaptor<Real>((Real) positions[atom].z); } *this << BinaryFileAdaptor<Size>(4*noa); return true; } } // namespace BALL <commit_msg>fixed: compiler warning because of unreachable code<commit_after>// $Id: DCDFile.C,v 1.6 2001/03/02 14:49:49 anker Exp $ #include <BALL/FORMAT/DCDFile.h> #include <BALL/MOLMEC/COMMON/snapShot.h> using namespace std; namespace BALL { DCDFile::DCDFile() throw() : TrajectoryFile(), header_(), swap_bytes_(false) { if (sizeof(int) != 4) { Log.error() << "DCDFile::DCDFile(): " << "Size of int is not equal to 4 on this machine." << endl; } if (sizeof(double) != 8) { Log.error() << "DCDFile::DCDFile(): " << "Size of double is not equal to 4 on this machine." << endl; } } DCDFile::DCDFile(const DCDFile& file) throw() : TrajectoryFile(), header_(file.header_), swap_bytes_(file.swap_bytes_) { if (sizeof(int) != 4) { Log.error() << "DCDFile::DCDFile(): " << "Size of int is not equal to 4 on this machine." << endl; } if (sizeof(double) != 8) { Log.error() << "DCDFile::DCDFile(): " << "Size of double is not equal to 4 on this machine." << endl; } } DCDFile::DCDFile(const String& name, File::OpenMode open_mode) throw() : TrajectoryFile(name, open_mode), header_(), swap_bytes_(false) { if (sizeof(int) != 4) { Log.error() << "DCDFile::DCDFile(): " << "Size of int is not equal to 4 on this machine." << endl; } if (sizeof(double) != 8) { Log.error() << "DCDFile::DCDFile(): " << "Size of double is not equal to 4 on this machine." << endl; } } DCDFile::~DCDFile() throw() { clear(); } const DCDFile& DCDFile::operator = (const DCDFile& file) throw() { TrajectoryFile::operator = (file); header_ = file.header_; return *this; } void DCDFile::clear() throw() { header_ = DCDHeader(); swap_bytes_ = false; TrajectoryFile::clear(); } bool DCDFile::operator == (const DCDFile& file) throw() { // BAUSTELLE: Header vergleichen. Was heit gleich eigentlich in diesem // Fall? return (TrajectoryFile::operator == (file)); } bool DCDFile::readHeader() throw() { return true; /* char fourbytes[4]; char eightyfourbytes[84]; int tmp_int; DCDHeader tmp_header; File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); if (tmp_int != 84) { // it might be a problem of endianness, so swap the bytes and test // again. // tmp_int = swapFourBytes(tmp_int); if (tmp_int != 84) { Log.error() << "DCDFile::readHeader(): " << "file seems corrupted (wrong magic number)" << endl; return false; } else { // we have to swap bytes... // if (verbosity > 1) // { Log.info() << "DCDFile::readHeader(): enabling byte swap" << endl; // } swap_bytes_ = true; } } // read this block File::read(eightyfourbytes, 84); if (swap_bytes_) { // BAUSTELLE } else { // check for "CORD" signature if ((eightyfourbytes[0] != 'C') || (eightyfourbytes[1] != 'O') || (eightyfourbytes[2] != 'O') || (eightyfourbytes[3] != 'D')) { Log.error() << "DCDFile::readHeader() " << "File seems to be corrupted (CORD missing)" << endl; return false; } tmp_header.number_of_coordinate_sets = *((int*)(eightyfourbytes + 4)); tmp_header.step_number_of_starting_time = *((int*)(eightyfourbytes + 8)); tmp_header.steps_between_saves = *((int*)(eightyfourbytes + 12)); tmp_header.time_step_length = *((double*)(eightyfourbytes + 40)); // check if the block is terminated correctly File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); if (tmp_int != 84) { Log.error() << "DCDFile::readHeader() " << "File seems to be corrupted (84 bytes incorrectly terninated)" << endl; return false; } // now handle the next block File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); // check if the length of the next block allows n titles of 80 chars // length int number_of_titles; if (((tmp_int - 4) % 80) == 0) { File::read(fourbytes, 4); number_of_titles = *((int*)fourbytes); // here we believe that the number stated in the file is correct. for (int i = 0; i < number_of_titles; ++i) { File::read(eightyfourbytes, 80); // BAUSTELLE jetzt noch was mit den titeln tun... } } else { Log.error() << "DCDFile::readHeader() " << "File seems to be corrupted (number of titles wrong)" << endl; return false; } File::read(fourbytes, 4); tmp_int = *((int*)fourbytes); if (tmp_int != number_of_titles) { Log.error() << "DCDFile::readHeader(): " << "File seems to be corrupted (title block terminated incorrectly" << endl; return false; } // GROSSBAUSTELLE } return false; */ } bool DCDFile::updateHeader(const SnapShotManager& manager) throw() { // BAUSTELLE header_.number_of_coordinate_sets = manager.getNumberOfSnapShots(); header_.number_of_atoms = manager.getNumberOfAtoms(); return true; } bool DCDFile::writeHeader() throw() { // the following would be nice. Unfortunately the compiler does strange // things when storing the struct in memory... // *this << BinaryFileAdaptor<struct DCDHeader>(header_); Size i; *this << BinaryFileAdaptor<Size>(header_.start_info_block); for (i = 0; i < 4; ++i) { *this << BinaryFileAdaptor<char>(header_.CORD[i]); } *this << BinaryFileAdaptor<Size>(header_.number_of_coordinate_sets); *this << BinaryFileAdaptor<Size>(header_.step_number_of_starting_time); *this << BinaryFileAdaptor<Size>(header_.steps_between_saves); for (i = 0; i < 6; ++i) { *this << BinaryFileAdaptor<Size>(header_.unused_1[i]); } *this << BinaryFileAdaptor<DoubleReal>(header_.time_step_length); for (i = 0; i < 9; ++i) { *this << BinaryFileAdaptor<Size>(header_.unused_2[i]); } *this << BinaryFileAdaptor<Size>(header_.end_info_block); *this << BinaryFileAdaptor<Size>(header_.start_title_block); *this << BinaryFileAdaptor<Size>(header_.number_of_comments); for (i = 0; i < 160; ++i) { *this << BinaryFileAdaptor<char>(header_.title[i]); } *this << BinaryFileAdaptor<Size>(header_.end_title_block); *this << BinaryFileAdaptor<Size>(header_.start_atomnumber_block); *this << BinaryFileAdaptor<Size>(header_.number_of_atoms); *this << BinaryFileAdaptor<Size>(header_.end_atomnumber_block); return true; } bool DCDFile::read(SnapShotManager& /* manager */) throw(Exception::NotImplemented) { throw Exception::NotImplemented(__FILE__, __LINE__); } bool DCDFile::write(const SnapShotManager& /* manager */) throw(Exception::NotImplemented) { throw Exception::NotImplemented(__FILE__, __LINE__); } bool DCDFile::append(const SnapShot& snapshot) throw() { Size noa = snapshot.getNumberOfAtoms(); vector<Vector3> positions = snapshot.getAtomPositions(); if (positions.size() == 0) { Log.error() << "DCDFile::append(): " << "No atom positions available" << endl; return false; } *this << BinaryFileAdaptor<Size>(4*noa); for (Size atom = 0; atom < noa; ++atom) { *this << BinaryFileAdaptor<Real>((Real) positions[atom].x); } *this << BinaryFileAdaptor<Size>(4*noa); *this << BinaryFileAdaptor<Size>(4*noa); for (Size atom = 0; atom < noa; ++atom) { *this << BinaryFileAdaptor<Real>((Real) positions[atom].y); } *this << BinaryFileAdaptor<Size>(4*noa); *this << BinaryFileAdaptor<Size>(4*noa); for (Size atom = 0; atom < noa; ++atom) { *this << BinaryFileAdaptor<Real>((Real) positions[atom].z); } *this << BinaryFileAdaptor<Size>(4*noa); return true; } } // namespace BALL <|endoftext|>
<commit_before>#include <QChildEvent> #include "ButtonItem.h" #include "LayoutItem.h" #include "ModeItem.h" ModeItem::ModeItem(QQuickItem *parent): QQuickItem(parent), m_layout(0) { setVisible(false); setLayout(new LayoutItem()); } ModeItem::~ModeItem() { } LayoutItem *ModeItem::layout() const { return m_layout; } void ModeItem::setLayout(LayoutItem *layout) { if (m_layout == layout) { return; } if (m_layout) { m_layout->setParentItem(0); delete m_layout; } if (layout) { layout->setParentItem(this); foreach (ButtonItem *button, m_buttons) { m_layout->addButton(button); } layout->property("anchors").value<QObject *>()->setProperty("fill", QVariant::fromValue<QQuickItem *>(this)); } m_layout = layout; } QQmlListProperty<ButtonItem> ModeItem::buttons() { return QQmlListProperty<ButtonItem>( this, &m_buttons, &ModeItem::buttons_append, &ModeItem::buttons_count, &ModeItem::buttons_at, &ModeItem::buttons_clear ); } void ModeItem::buttons_append(QQmlListProperty<ButtonItem> *property, ButtonItem *button) { ModeItem *that = static_cast<ModeItem *>(property->object); button->setParentItem(that); that->m_buttons.append(button); if (that->m_layout) { that->m_layout->addButton(button); } QObject::connect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &))); } int ModeItem::buttons_count(QQmlListProperty<ButtonItem> *property) { ModeItem *that = static_cast<ModeItem *>(property->object); return that->m_buttons.count(); } ButtonItem *ModeItem::buttons_at(QQmlListProperty<ButtonItem> *property, int idx) { ModeItem *that = static_cast<ModeItem *>(property->object); return that->m_buttons.value(idx, 0); } void ModeItem::buttons_clear(QQmlListProperty<ButtonItem> *property) { ModeItem *that = static_cast<ModeItem *>(property->object); if (that->m_layout) { that->m_layout->clearButtons(); } foreach (ButtonItem *button, that->m_buttons) { QObject::disconnect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &))); button->setParentItem(0); } that->m_buttons.clear(); } void ModeItem::onSymbolTriggered(const QString &symbol) { } <commit_msg>Changed default layout to GridLayout.<commit_after>#include <QChildEvent> #include "ButtonItem.h" #include "GridLayoutItem.h" #include "ModeItem.h" ModeItem::ModeItem(QQuickItem *parent): QQuickItem(parent), m_layout(0) { setVisible(false); setLayout(new GridLayoutItem()); } ModeItem::~ModeItem() { } LayoutItem *ModeItem::layout() const { return m_layout; } void ModeItem::setLayout(LayoutItem *layout) { if (m_layout == layout) { return; } if (m_layout) { m_layout->setParentItem(0); delete m_layout; } if (layout) { layout->setParentItem(this); foreach (ButtonItem *button, m_buttons) { m_layout->addButton(button); } layout->property("anchors").value<QObject *>()->setProperty("fill", QVariant::fromValue<QQuickItem *>(this)); } m_layout = layout; } QQmlListProperty<ButtonItem> ModeItem::buttons() { return QQmlListProperty<ButtonItem>( this, &m_buttons, &ModeItem::buttons_append, &ModeItem::buttons_count, &ModeItem::buttons_at, &ModeItem::buttons_clear ); } void ModeItem::buttons_append(QQmlListProperty<ButtonItem> *property, ButtonItem *button) { ModeItem *that = static_cast<ModeItem *>(property->object); button->setParentItem(that); that->m_buttons.append(button); if (that->m_layout) { that->m_layout->addButton(button); } QObject::connect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &))); } int ModeItem::buttons_count(QQmlListProperty<ButtonItem> *property) { ModeItem *that = static_cast<ModeItem *>(property->object); return that->m_buttons.count(); } ButtonItem *ModeItem::buttons_at(QQmlListProperty<ButtonItem> *property, int idx) { ModeItem *that = static_cast<ModeItem *>(property->object); return that->m_buttons.value(idx, 0); } void ModeItem::buttons_clear(QQmlListProperty<ButtonItem> *property) { ModeItem *that = static_cast<ModeItem *>(property->object); if (that->m_layout) { that->m_layout->clearButtons(); } foreach (ButtonItem *button, that->m_buttons) { QObject::disconnect(button, SIGNAL(symbolTriggered(const QString &)), that, SLOT(onSymbolTriggered(const QString &))); button->setParentItem(0); } that->m_buttons.clear(); } void ModeItem::onSymbolTriggered(const QString &symbol) { } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: configinit.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2006-10-12 14:05:05 $ * * 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_desktop.hxx" #include "configinit.hxx" #include "desktop.hrc" #include "app.hxx" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #include <uno/current_context.hxx> #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <stdio.h> #include <map> #ifndef _COM_SUN_STAR_LANG_SERVICENOTREGISTEREDEXCEPTION_HPP_ #include <com/sun/star/lang/ServiceNotRegisteredException.hpp> #endif #include <com/sun/star/configuration/CannotLoadConfigurationException.hpp> #include <com/sun/star/configuration/InvalidBootstrapFileException.hpp> #include <com/sun/star/configuration/backend/BackendSetupException.hpp> #include <com/sun/star/configuration/backend/CannotConnectException.hpp> // ---------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; namespace configuration = ::com::sun::star::configuration; namespace backend = ::com::sun::star::configuration::backend; using rtl::OUString; using uno::UNO_QUERY; using desktop::Desktop; // ---------------------------------------------------------------------------- static char const CONFIGURATION_PROVIDER[] = "com.sun.star.configuration.ConfigurationProvider"; static char const CONFIGURATION_ERROR_HANDLER[] = "com.sun.star.configuration.backend.InteractionHandler"; // must be aligned with configmgr/source/misc/configinteractionhandler static char const CONFIG_ERROR_HANDLER[] = "configuration.interaction-handler"; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- #define arraysize( arr ) ( sizeof (arr)/sizeof *(arr) ) typedef uno::Reference< lang::XMultiServiceFactory > ConfigurationProvider; #define OUSTRING( constascii ) OUString( RTL_CONSTASCII_USTRINGPARAM( constascii ) ) #define OU2O( ustr, enc ) rtl::OUStringToOString( (ustr), RTL_TEXTENCODING_ ## enc ) #define k_PROVIDER OUSTRING( CONFIGURATION_PROVIDER ) #define k_ERRORHANDLER OUSTRING( CONFIGURATION_ERROR_HANDLER ) // ---------------------------------------------------------------------------- // Get a message string securely. There is a fallback string if the resource // is not available. Adapted from Desktop::GetMsgString() OUString getMsgString( USHORT nId, char const * aFallBackMsg ) { ResMgr* pResMgr = Desktop::GetDesktopResManager(); if ( !pResMgr || !nId ) return OUString::createFromAscii(aFallBackMsg); else return OUString( String(ResId( nId, pResMgr ))); } // ---------------------------------------------------------------------------- /** Creates the normal configuration provider. */ static ConfigurationProvider createDefaultConfigurationProvider( ) { uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory(); OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for CreateApplicationConfigurationProvider"); ConfigurationProvider xProvider; if (xServiceManager.is()) { xProvider.set( xServiceManager->createInstance(k_PROVIDER), UNO_QUERY); } if (!xProvider.is()) { OUString const sMsg = OUSTRING("Service \"") + k_PROVIDER + OUSTRING("\" is not available at the service manager."); throw lang::ServiceNotRegisteredException(sMsg, xServiceManager); } return xProvider; } // ---------------------------------------------------------------------------- /// @attention this method must be called from a catch statement! static void handleGeneralException(uno::Exception& aException, const rtl::OUString& aMessage) { aException.Message = aMessage ; throw ; } // ---------------------------------------------------------------------------- uno::Reference< lang::XMultiServiceFactory > CreateApplicationConfigurationProvider( ) { uno::Reference< lang::XMultiServiceFactory > xProvider; try { xProvider = createDefaultConfigurationProvider( ); } catch (configuration::InvalidBootstrapFileException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_SETTINGS_INCOMPLETE, "The startup settings for your configuration settings are incomplete. ")); } catch (backend::CannotConnectException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT, "A connection to your configuration settings could not be established. ")); } catch (backend::BackendSetupException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT, "A connection to your configuration settings could not be established. ")); } catch (configuration::CannotLoadConfigurationException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT, "A connection to your configuration settings could not be established. ")); } catch (uno::Exception & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_ACCESS_GENERAL, "A general error occurred while accessing your configuration settings.")); } return xProvider ; } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ConfigurationErrorHandler // ---------------------------------------------------------------------------- namespace { typedef uno::Reference< uno::XCurrentContext > CurrentContext; class SimpleCurrentContext : public cppu::WeakImplHelper1< uno::XCurrentContext > { CurrentContext m_xChainedContext; public: explicit SimpleCurrentContext(const CurrentContext & xChainedContext) : m_xChainedContext(xChainedContext) {} void install() { uno::setCurrentContext(this); } void deinstall() { uno::setCurrentContext(m_xChainedContext); } uno::Any getChainedValueByName( OUString const & aName) const { return m_xChainedContext.is() ? m_xChainedContext->getValueByName(aName) : uno::Any(); } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException); }; uno::Any SAL_CALL SimpleCurrentContext::getValueByName( OUString const & aName) throw (uno::RuntimeException) { return getChainedValueByName(aName); } } // ---------------------------------------------------------------------------- class ConfigurationErrorHandler::Context : public SimpleCurrentContext { public: Context() : SimpleCurrentContext( uno::getCurrentContext() ) { } ~Context() { } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException); private: InteractionHandler m_xHandler; }; //------------------------------------------------------------------------------ uno::Any SAL_CALL ConfigurationErrorHandler::Context::getValueByName( OUString const & aName) throw (uno::RuntimeException) { if ( aName.equalsAscii( CONFIG_ERROR_HANDLER ) ) { if ( !m_xHandler.is() ) m_xHandler = ConfigurationErrorHandler::getDefaultInteractionHandler(); return uno::Any( m_xHandler ); } return SimpleCurrentContext::getValueByName( aName ); } //------------------------------------------------------------------------------ ConfigurationErrorHandler::~ConfigurationErrorHandler() { deactivate(); } //------------------------------------------------------------------------------ /// installs the handler into the current context void ConfigurationErrorHandler::activate() { if (!m_pContext) { m_pContext = new Context; m_pContext->acquire(); } m_pContext->install(); } //------------------------------------------------------------------------------ /// deinstalls the handler from the current context, restoring the previous context void ConfigurationErrorHandler::deactivate() { if (m_pContext) { m_pContext->deinstall(); m_pContext->release(); m_pContext = 0; } } //------------------------------------------------------------------------------ ConfigurationErrorHandler::InteractionHandler ConfigurationErrorHandler::getDefaultInteractionHandler() { uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory(); OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for ConfigurationErrorHandler"); InteractionHandler xHandler; if (xServiceManager.is()) { xHandler.set( xServiceManager->createInstance(k_ERRORHANDLER), UNO_QUERY ); } return xHandler; } //------------------------------------------------------------------------------ <commit_msg>INTEGRATION: CWS residcleanup (1.13.114); FILE MERGED 2007/02/24 19:59:49 pl 1.13.114.1: #i74635# residcleanup<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: configinit.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2007-04-26 08:22:20 $ * * 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_desktop.hxx" #include "configinit.hxx" #include "desktop.hrc" #include "app.hxx" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #include <uno/current_context.hxx> #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <stdio.h> #include <map> #ifndef _COM_SUN_STAR_LANG_SERVICENOTREGISTEREDEXCEPTION_HPP_ #include <com/sun/star/lang/ServiceNotRegisteredException.hpp> #endif #include <com/sun/star/configuration/CannotLoadConfigurationException.hpp> #include <com/sun/star/configuration/InvalidBootstrapFileException.hpp> #include <com/sun/star/configuration/backend/BackendSetupException.hpp> #include <com/sun/star/configuration/backend/CannotConnectException.hpp> // ---------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; namespace configuration = ::com::sun::star::configuration; namespace backend = ::com::sun::star::configuration::backend; using rtl::OUString; using uno::UNO_QUERY; using desktop::Desktop; // ---------------------------------------------------------------------------- static char const CONFIGURATION_PROVIDER[] = "com.sun.star.configuration.ConfigurationProvider"; static char const CONFIGURATION_ERROR_HANDLER[] = "com.sun.star.configuration.backend.InteractionHandler"; // must be aligned with configmgr/source/misc/configinteractionhandler static char const CONFIG_ERROR_HANDLER[] = "configuration.interaction-handler"; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- #define arraysize( arr ) ( sizeof (arr)/sizeof *(arr) ) typedef uno::Reference< lang::XMultiServiceFactory > ConfigurationProvider; #define OUSTRING( constascii ) OUString( RTL_CONSTASCII_USTRINGPARAM( constascii ) ) #define OU2O( ustr, enc ) rtl::OUStringToOString( (ustr), RTL_TEXTENCODING_ ## enc ) #define k_PROVIDER OUSTRING( CONFIGURATION_PROVIDER ) #define k_ERRORHANDLER OUSTRING( CONFIGURATION_ERROR_HANDLER ) // ---------------------------------------------------------------------------- // Get a message string securely. There is a fallback string if the resource // is not available. Adapted from Desktop::GetMsgString() OUString getMsgString( USHORT nId, char const * aFallBackMsg ) { ResMgr* pResMgr = Desktop::GetDesktopResManager(); if ( !pResMgr || !nId ) return OUString::createFromAscii(aFallBackMsg); else return OUString( String(ResId( nId, *pResMgr ))); } // ---------------------------------------------------------------------------- /** Creates the normal configuration provider. */ static ConfigurationProvider createDefaultConfigurationProvider( ) { uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory(); OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for CreateApplicationConfigurationProvider"); ConfigurationProvider xProvider; if (xServiceManager.is()) { xProvider.set( xServiceManager->createInstance(k_PROVIDER), UNO_QUERY); } if (!xProvider.is()) { OUString const sMsg = OUSTRING("Service \"") + k_PROVIDER + OUSTRING("\" is not available at the service manager."); throw lang::ServiceNotRegisteredException(sMsg, xServiceManager); } return xProvider; } // ---------------------------------------------------------------------------- /// @attention this method must be called from a catch statement! static void handleGeneralException(uno::Exception& aException, const rtl::OUString& aMessage) { aException.Message = aMessage ; throw ; } // ---------------------------------------------------------------------------- uno::Reference< lang::XMultiServiceFactory > CreateApplicationConfigurationProvider( ) { uno::Reference< lang::XMultiServiceFactory > xProvider; try { xProvider = createDefaultConfigurationProvider( ); } catch (configuration::InvalidBootstrapFileException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_SETTINGS_INCOMPLETE, "The startup settings for your configuration settings are incomplete. ")); } catch (backend::CannotConnectException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT, "A connection to your configuration settings could not be established. ")); } catch (backend::BackendSetupException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT, "A connection to your configuration settings could not be established. ")); } catch (configuration::CannotLoadConfigurationException & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_CANNOT_CONNECT, "A connection to your configuration settings could not be established. ")); } catch (uno::Exception & exception) { handleGeneralException(exception, getMsgString( STR_CONFIG_ERR_ACCESS_GENERAL, "A general error occurred while accessing your configuration settings.")); } return xProvider ; } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ConfigurationErrorHandler // ---------------------------------------------------------------------------- namespace { typedef uno::Reference< uno::XCurrentContext > CurrentContext; class SimpleCurrentContext : public cppu::WeakImplHelper1< uno::XCurrentContext > { CurrentContext m_xChainedContext; public: explicit SimpleCurrentContext(const CurrentContext & xChainedContext) : m_xChainedContext(xChainedContext) {} void install() { uno::setCurrentContext(this); } void deinstall() { uno::setCurrentContext(m_xChainedContext); } uno::Any getChainedValueByName( OUString const & aName) const { return m_xChainedContext.is() ? m_xChainedContext->getValueByName(aName) : uno::Any(); } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException); }; uno::Any SAL_CALL SimpleCurrentContext::getValueByName( OUString const & aName) throw (uno::RuntimeException) { return getChainedValueByName(aName); } } // ---------------------------------------------------------------------------- class ConfigurationErrorHandler::Context : public SimpleCurrentContext { public: Context() : SimpleCurrentContext( uno::getCurrentContext() ) { } ~Context() { } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException); private: InteractionHandler m_xHandler; }; //------------------------------------------------------------------------------ uno::Any SAL_CALL ConfigurationErrorHandler::Context::getValueByName( OUString const & aName) throw (uno::RuntimeException) { if ( aName.equalsAscii( CONFIG_ERROR_HANDLER ) ) { if ( !m_xHandler.is() ) m_xHandler = ConfigurationErrorHandler::getDefaultInteractionHandler(); return uno::Any( m_xHandler ); } return SimpleCurrentContext::getValueByName( aName ); } //------------------------------------------------------------------------------ ConfigurationErrorHandler::~ConfigurationErrorHandler() { deactivate(); } //------------------------------------------------------------------------------ /// installs the handler into the current context void ConfigurationErrorHandler::activate() { if (!m_pContext) { m_pContext = new Context; m_pContext->acquire(); } m_pContext->install(); } //------------------------------------------------------------------------------ /// deinstalls the handler from the current context, restoring the previous context void ConfigurationErrorHandler::deactivate() { if (m_pContext) { m_pContext->deinstall(); m_pContext->release(); m_pContext = 0; } } //------------------------------------------------------------------------------ ConfigurationErrorHandler::InteractionHandler ConfigurationErrorHandler::getDefaultInteractionHandler() { uno::Reference< lang::XMultiServiceFactory > xServiceManager = ::comphelper::getProcessServiceFactory(); OSL_ENSURE( xServiceManager.is(),"No ServiceManager set for ConfigurationErrorHandler"); InteractionHandler xHandler; if (xServiceManager.is()) { xHandler.set( xServiceManager->createInstance(k_ERRORHANDLER), UNO_QUERY ); } return xHandler; } //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>#include "t200_thruster.h" //#include "sub_thruster_library/seabotix_thruster.h" #include "generic_thruster.h" #include "sub_trajectory/ThrusterCmd.h" #include <json/json.h> #include <ros/ros.h> #include <std_srvs/Empty.h> #include <diagnostic_msgs/DiagnosticStatus.h> #include <diagnostic_msgs/SelfTest.h> //TODO: implement self tests #include <self_test/self_test.h> #include <iostream> #include <fstream> #include <memory> inline const std::string BoolToString(const bool b); //http://stackoverflow.com/a/29798 class ThrusterManager { ros::NodeHandle nh_; ros::Subscriber command_subscriber; ros::Publisher diagnostics_output; self_test::TestRunner self_test_; sub_trajectory::ThrusterCmd savedMsg; std::map<int, std::unique_ptr<GenericThruster>> thrusterMap; int updateRate; ros::ServiceServer initServer; public: ThrusterManager() : self_test_() { for(int i = 0; i < 8; i++) { savedMsg.cmd.push_back(0.0); } command_subscriber = nh_.subscribe("/thrusters/cmd_vel", 1000, &ThrusterManager::thrusterCb, this); diagnostics_output = nh_.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 1000); self_test_.add("Test connections", this, &ThrusterManager::testThrusterConnections); initServer = nh_.advertiseService("initThrusters", &ThrusterManager::initService, this); nh_.param("/updateRate", updateRate, 30); } Json::Value loadConfig(std::string filename) { ifstream configFile(filename); if(!configFile.is_open()){ ROS_ERROR("Thruster controller couldn't open config file"); //status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Config file didn't load"); Json::Value obj; return obj; } ROS_INFO("Thruster controller config loading"); Json::Value obj; configFile >> obj; ROS_INFO("Thruster controller config loaded"); return obj; } bool initService(std_srvs::Empty::Request& req, std_srvs::Empty::Response& resp) { init(); return true; } void init() { thrusterMap.clear(); Json::Value thrustersJson = loadConfig("config.json")["COMPUTE"]; savedMsg = sub_trajectory::ThrusterCmd(); savedMsg.cmd.resize(thrustersJson.size(), 0.0); diagnostic_msgs::DiagnosticArray diag; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types int thrusterAddress = thrustersJson[i]["Address"].asInt(); ROS_INFO("Initializing thruster %d", thrusterID); try{ thrusterMap[i] = std::unique_ptr<GenericThruster>(new T200Thruster(1,thrusterAddress)); } catch(I2CException e){ //If we get here there's a bus problem ROS_ERROR("I2C error while connecting to thruster address %x", thrusterAddress); thrusterMap.erase(i); //Publish an error message for the diagnostic system to do something about diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thrusters_"+thrustersJson[i]["Address"].asString(); status.level = status.ERROR; diag.status.push_back(status) } } diagnostics_output.publish(diag); ros::spinOnce(); ROS_INFO("Done initializing thrusters"); } void spin() { diagnostic_msgs::DiagnosticArray diag; ros::Rate rate(updateRate); while(ros::ok()) { //Publish diagnostic data here ROS_DEBUG("Updating thrusters"); for(auto& iter:thrusterMap) { diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thruster_"+std::to_string(iter.first); try { iter.second->updateStatus(); iter.second->setVelocityRatio(savedMsg.cmd.at(iter.first)); } catch(I2CException e) { //Publish an error message for the diagnostic system to do something about status.level = status.ERROR; } if (thrusterOk(iter.second) && status.level != status.ERROR) status.level = status.OK; else status.level = status.ERROR; PushDiagData(status, iter.second, std::to_string(iter.first)); diag.status.push_back(status); } diagnostics_output.publish(diag); ros::spinOnce(); self_test_.checkTest(); rate.sleep(); } } bool thrusterOk (std::unique_ptr<GenericThruster> & thruster) { return thruster->isAlive() && thruster->inLimits(); } void PushDiagData(diagnostic_msgs::DiagnosticStatus & statusmsg, std::unique_ptr<GenericThruster> & thruster, std::string thrusterName) { diagnostic_msgs::KeyValue thrusterValue; thrusterValue.key = "Thruster Type"; thrusterValue.value = thruster->getType(); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Alive"; thrusterValue.value = BoolToString(thruster->isAlive()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Voltage"; thrusterValue.value = std::to_string(thruster->getVoltage()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Current"; thrusterValue.value = std::to_string(thruster->getCurrent()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Temperature"; thrusterValue.value = std::to_string(thruster->getTemperature()); statusmsg.values.push_back(thrusterValue); } void thrusterCb(const sub_trajectory::ThrusterCmd &msg) { savedMsg = msg; } //Self test function void testThrusterConnections(diagnostic_updater::DiagnosticStatusWrapper& status) { self_test_.setID("thrusterController"); std::stringstream failedThrusters; Json::Value& thrustersJson = loadConfig("config.json")["COMPUTE"]; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types int thrusterAddress = thrustersJson[i]["Address"].asInt(); try{ T200Thruster(1, thrusterAddress).updateStatus(); } catch(I2CException e){ failedThrusters << thrusterAddress << " "; } } if(failedThrusters.str().length() > 0){ status.add("Failures", failedThrusters.str()); status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Thruster couldn't connect"); } else { status.summary(diagnostic_msgs::DiagnosticStatus::OK, "All thrusters OK"); } } }; int main(int argc, char** argv) { ros::init(argc, argv, "thruster_driver"); ThrusterManager tc; tc.init(); ROS_INFO("Thruster controller initialized, spinning"); tc.spin(); return 0; } inline const std::string BoolToString(const bool b) { return b ? "true" : "false"; } <commit_msg>missing semicolon<commit_after>#include "t200_thruster.h" //#include "sub_thruster_library/seabotix_thruster.h" #include "generic_thruster.h" #include "sub_trajectory/ThrusterCmd.h" #include <json/json.h> #include <ros/ros.h> #include <std_srvs/Empty.h> #include <diagnostic_msgs/DiagnosticStatus.h> #include <diagnostic_msgs/SelfTest.h> //TODO: implement self tests #include <self_test/self_test.h> #include <iostream> #include <fstream> #include <memory> inline const std::string BoolToString(const bool b); //http://stackoverflow.com/a/29798 class ThrusterManager { ros::NodeHandle nh_; ros::Subscriber command_subscriber; ros::Publisher diagnostics_output; self_test::TestRunner self_test_; sub_trajectory::ThrusterCmd savedMsg; std::map<int, std::unique_ptr<GenericThruster>> thrusterMap; int updateRate; ros::ServiceServer initServer; public: ThrusterManager() : self_test_() { for(int i = 0; i < 8; i++) { savedMsg.cmd.push_back(0.0); } command_subscriber = nh_.subscribe("/thrusters/cmd_vel", 1000, &ThrusterManager::thrusterCb, this); diagnostics_output = nh_.advertise<diagnostic_msgs::DiagnosticArray>("/diagnostics", 1000); self_test_.add("Test connections", this, &ThrusterManager::testThrusterConnections); initServer = nh_.advertiseService("initThrusters", &ThrusterManager::initService, this); nh_.param("/updateRate", updateRate, 30); } Json::Value loadConfig(std::string filename) { ifstream configFile(filename); if(!configFile.is_open()){ ROS_ERROR("Thruster controller couldn't open config file"); //status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Config file didn't load"); Json::Value obj; return obj; } ROS_INFO("Thruster controller config loading"); Json::Value obj; configFile >> obj; ROS_INFO("Thruster controller config loaded"); return obj; } bool initService(std_srvs::Empty::Request& req, std_srvs::Empty::Response& resp) { init(); return true; } void init() { thrusterMap.clear(); Json::Value thrustersJson = loadConfig("config.json")["COMPUTE"]; savedMsg = sub_trajectory::ThrusterCmd(); savedMsg.cmd.resize(thrustersJson.size(), 0.0); diagnostic_msgs::DiagnosticArray diag; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types int thrusterAddress = thrustersJson[i]["Address"].asInt(); ROS_INFO("Initializing thruster %d", thrusterID); try{ thrusterMap[i] = std::unique_ptr<GenericThruster>(new T200Thruster(1,thrusterAddress)); } catch(I2CException e){ //If we get here there's a bus problem ROS_ERROR("I2C error while connecting to thruster address %x", thrusterAddress); thrusterMap.erase(i); //Publish an error message for the diagnostic system to do something about diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thrusters_"+thrustersJson[i]["Address"].asString(); status.level = status.ERROR; diag.status.push_back(status); } } diagnostics_output.publish(diag); ros::spinOnce(); ROS_INFO("Done initializing thrusters"); } void spin() { diagnostic_msgs::DiagnosticArray diag; ros::Rate rate(updateRate); while(ros::ok()) { //Publish diagnostic data here ROS_DEBUG("Updating thrusters"); for(auto& iter:thrusterMap) { diagnostic_msgs::DiagnosticStatus status; status.name = "Thrusters"; status.hardware_id = "Thruster_"+std::to_string(iter.first); try { iter.second->updateStatus(); iter.second->setVelocityRatio(savedMsg.cmd.at(iter.first)); } catch(I2CException e) { //Publish an error message for the diagnostic system to do something about status.level = status.ERROR; } if (thrusterOk(iter.second) && status.level != status.ERROR) status.level = status.OK; else status.level = status.ERROR; PushDiagData(status, iter.second, std::to_string(iter.first)); diag.status.push_back(status); } diagnostics_output.publish(diag); ros::spinOnce(); self_test_.checkTest(); rate.sleep(); } } bool thrusterOk (std::unique_ptr<GenericThruster> & thruster) { return thruster->isAlive() && thruster->inLimits(); } void PushDiagData(diagnostic_msgs::DiagnosticStatus & statusmsg, std::unique_ptr<GenericThruster> & thruster, std::string thrusterName) { diagnostic_msgs::KeyValue thrusterValue; thrusterValue.key = "Thruster Type"; thrusterValue.value = thruster->getType(); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Alive"; thrusterValue.value = BoolToString(thruster->isAlive()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Voltage"; thrusterValue.value = std::to_string(thruster->getVoltage()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Current"; thrusterValue.value = std::to_string(thruster->getCurrent()); statusmsg.values.push_back(thrusterValue); thrusterValue.key = thrusterName + " Temperature"; thrusterValue.value = std::to_string(thruster->getTemperature()); statusmsg.values.push_back(thrusterValue); } void thrusterCb(const sub_trajectory::ThrusterCmd &msg) { savedMsg = msg; } //Self test function void testThrusterConnections(diagnostic_updater::DiagnosticStatusWrapper& status) { self_test_.setID("thrusterController"); std::stringstream failedThrusters; Json::Value& thrustersJson = loadConfig("config.json")["COMPUTE"]; for(int i = 0; i < thrustersJson.size(); i++) { int thrusterID = thrustersJson[i]["ID"].asInt(); int thrusterType = thrustersJson[i]["Type"].asInt(); //TODO: support for multiple thruster types int thrusterAddress = thrustersJson[i]["Address"].asInt(); try{ T200Thruster(1, thrusterAddress).updateStatus(); } catch(I2CException e){ failedThrusters << thrusterAddress << " "; } } if(failedThrusters.str().length() > 0){ status.add("Failures", failedThrusters.str()); status.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Thruster couldn't connect"); } else { status.summary(diagnostic_msgs::DiagnosticStatus::OK, "All thrusters OK"); } } }; int main(int argc, char** argv) { ros::init(argc, argv, "thruster_driver"); ThrusterManager tc; tc.init(); ROS_INFO("Thruster controller initialized, spinning"); tc.spin(); return 0; } inline const std::string BoolToString(const bool b) { return b ? "true" : "false"; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../../cvmfs/util_concurrency.h" class DummyLocker { public: DummyLocker() : locked(false) {} void Lock() const { locked = true; } void Unlock() const { locked = false; } public: mutable bool locked; }; TEST(T_UtilConcurrency, ArbitraryLockGurad) { DummyLocker locker; ASSERT_FALSE (locker.locked); { LockGuard<DummyLocker> lock(locker); EXPECT_TRUE (locker.locked) << "LockGuard didn't lock"; } EXPECT_FALSE (locker.locked) << "LockGuard didn't unlock"; } TEST(T_UtilConcurrency, MutexLockGuard) { pthread_mutex_t mutex; int retcode = pthread_mutex_init(&mutex, NULL); ASSERT_EQ (0, retcode); { MutexLockGuard lock(mutex); retcode = pthread_mutex_trylock(&mutex); EXPECT_EQ (EBUSY, retcode) << "MutexLockGuard didn't lock"; } retcode = pthread_mutex_trylock(&mutex); EXPECT_EQ (0, retcode) << "MutexLockGuard didn't unlock"; retcode = pthread_mutex_unlock(&mutex); EXPECT_EQ (0, retcode); retcode = pthread_mutex_destroy(&mutex); EXPECT_EQ (0, retcode); } TEST(T_UtilConcurrency, ReadLockGuard) { pthread_rwlock_t rwlock; int retcode = pthread_rwlock_init(&rwlock, NULL); ASSERT_EQ (0, retcode); { ReadLockGuard lock(rwlock); retcode = pthread_rwlock_tryrdlock(&rwlock); EXPECT_EQ (0, retcode) << "ReadLockGuard prevents additional read lock"; retcode = pthread_rwlock_unlock(&rwlock); EXPECT_EQ (0, retcode); retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (EBUSY, retcode) << "ReadLockGuard allows concurrent read and write"; } retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (0, retcode) << "ReadLockGuard didn't unlock"; retcode = pthread_rwlock_unlock(&rwlock); EXPECT_EQ (0, retcode); retcode = pthread_rwlock_destroy(&rwlock); EXPECT_EQ (0, retcode); } TEST(T_UtilConcurrency, WriteLockGuard) { pthread_rwlock_t rwlock; int retcode = pthread_rwlock_init(&rwlock, NULL); ASSERT_EQ (0, retcode); { WriteLockGuard lock(rwlock); retcode = pthread_rwlock_tryrdlock(&rwlock); EXPECT_EQ (EBUSY, retcode) << "WriteLockGuard didn't lock - rdlock possible"; if (0 == retcode) { retcode = pthread_rwlock_unlock(&rwlock); ASSERT_EQ (0, retcode); } retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (EBUSY, retcode) << "WriteLockGuard didn't lock - wrlock possible"; if (0 == retcode) { retcode = pthread_rwlock_unlock(&rwlock); ASSERT_EQ (0, retcode); } } retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (0, retcode) << "WriteLockGuard didn't unlock"; retcode = pthread_rwlock_unlock(&rwlock); EXPECT_EQ (0, retcode); retcode = pthread_rwlock_destroy(&rwlock); EXPECT_EQ (0, retcode); } class DummyLockable : public Lockable {}; TEST(T_UtilConcurrency, Lockable) { DummyLockable lockable; int retcode = 0; { LockGuard<DummyLockable> lock(lockable); retcode = lockable.TryLock(); EXPECT_EQ (EBUSY, retcode) << "Lockable didn't lock"; } retcode = lockable.TryLock(); EXPECT_EQ (0, retcode) << "Lockable didn't unlock"; } <commit_msg>add tests for basic callback functionality<commit_after>#include <gtest/gtest.h> #include "../../cvmfs/util_concurrency.h" class DummyLocker { public: DummyLocker() : locked(false) {} void Lock() const { locked = true; } void Unlock() const { locked = false; } public: mutable bool locked; }; TEST(T_UtilConcurrency, ArbitraryLockGurad) { DummyLocker locker; ASSERT_FALSE (locker.locked); { LockGuard<DummyLocker> lock(locker); EXPECT_TRUE (locker.locked) << "LockGuard didn't lock"; } EXPECT_FALSE (locker.locked) << "LockGuard didn't unlock"; } TEST(T_UtilConcurrency, MutexLockGuard) { pthread_mutex_t mutex; int retcode = pthread_mutex_init(&mutex, NULL); ASSERT_EQ (0, retcode); { MutexLockGuard lock(mutex); retcode = pthread_mutex_trylock(&mutex); EXPECT_EQ (EBUSY, retcode) << "MutexLockGuard didn't lock"; } retcode = pthread_mutex_trylock(&mutex); EXPECT_EQ (0, retcode) << "MutexLockGuard didn't unlock"; retcode = pthread_mutex_unlock(&mutex); EXPECT_EQ (0, retcode); retcode = pthread_mutex_destroy(&mutex); EXPECT_EQ (0, retcode); } TEST(T_UtilConcurrency, ReadLockGuard) { pthread_rwlock_t rwlock; int retcode = pthread_rwlock_init(&rwlock, NULL); ASSERT_EQ (0, retcode); { ReadLockGuard lock(rwlock); retcode = pthread_rwlock_tryrdlock(&rwlock); EXPECT_EQ (0, retcode) << "ReadLockGuard prevents additional read lock"; retcode = pthread_rwlock_unlock(&rwlock); EXPECT_EQ (0, retcode); retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (EBUSY, retcode) << "ReadLockGuard allows concurrent read and write"; } retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (0, retcode) << "ReadLockGuard didn't unlock"; retcode = pthread_rwlock_unlock(&rwlock); EXPECT_EQ (0, retcode); retcode = pthread_rwlock_destroy(&rwlock); EXPECT_EQ (0, retcode); } TEST(T_UtilConcurrency, WriteLockGuard) { pthread_rwlock_t rwlock; int retcode = pthread_rwlock_init(&rwlock, NULL); ASSERT_EQ (0, retcode); { WriteLockGuard lock(rwlock); retcode = pthread_rwlock_tryrdlock(&rwlock); EXPECT_EQ (EBUSY, retcode) << "WriteLockGuard didn't lock - rdlock possible"; if (0 == retcode) { retcode = pthread_rwlock_unlock(&rwlock); ASSERT_EQ (0, retcode); } retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (EBUSY, retcode) << "WriteLockGuard didn't lock - wrlock possible"; if (0 == retcode) { retcode = pthread_rwlock_unlock(&rwlock); ASSERT_EQ (0, retcode); } } retcode = pthread_rwlock_trywrlock(&rwlock); EXPECT_EQ (0, retcode) << "WriteLockGuard didn't unlock"; retcode = pthread_rwlock_unlock(&rwlock); EXPECT_EQ (0, retcode); retcode = pthread_rwlock_destroy(&rwlock); EXPECT_EQ (0, retcode); } class DummyLockable : public Lockable {}; TEST(T_UtilConcurrency, Lockable) { DummyLockable lockable; int retcode = 0; { LockGuard<DummyLockable> lock(lockable); retcode = lockable.TryLock(); EXPECT_EQ (EBUSY, retcode) << "Lockable didn't lock"; } retcode = lockable.TryLock(); EXPECT_EQ (0, retcode) << "Lockable didn't unlock"; } void CallbackFn(bool* const &param) { *param = true; } TEST(T_UtilConcurrency, SimpleCallback) { bool callback_called = false; Callback<bool*> callback(&CallbackFn); callback(&callback_called); EXPECT_TRUE (callback_called); } class DummyCallbackDelegate { public: DummyCallbackDelegate() : callback_result(-1) {} void CallbackMd(const int &value) { callback_result = value; } public: int callback_result; }; TEST(T_UtilConcurrency, BoundCallback) { DummyCallbackDelegate delegate; ASSERT_EQ (-1, delegate.callback_result); BoundCallback<int, DummyCallbackDelegate> callback( &DummyCallbackDelegate::CallbackMd, &delegate); callback(42); EXPECT_EQ (42, delegate.callback_result); } class DummyCallbackable : public Callbackable<int> { public: DummyCallbackable() : callback_result(-1) {} void CallbackMd(const int &value) { callback_result = value; } public: int callback_result; }; TEST(T_UtilConcurrency, Callbackable) { DummyCallbackable callbackable; ASSERT_EQ (-1, callbackable.callback_result); DummyCallbackable::callback_t *callback = DummyCallbackable::MakeCallback(&DummyCallbackable::CallbackMd, &callbackable); (*callback)(1337); EXPECT_EQ (1337, callbackable.callback_result); } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2013 \file app/rdo_studio/src/plugins/plugin_loader.cpp \author Чернов Алексей (ChernovAlexeyOlegovich@gmail.com) \date 22.09.2013 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include "utils/src/common/warning_disable.h" #include <QDir> #include <QApplication> #include <QSettings> #include <boost/foreach.hpp> #include "utils/src/common/warning_enable.h" // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/plugins/plugin_loader.h" // -------------------------------------------------------------------------------- using namespace rdo::plugin; Loader::Loader() : m_pPluginsParent(NULL) , m_pMergedPluginInfoList(rdo::Factory<PluginInfoList>::create(getMergedPluginInfoList())) {} Loader::~Loader() { BOOST_FOREACH(const LPPluginInfo& pluginInfo, *m_pMergedPluginInfoList) { if (pluginInfo->isActive()) stopPlugin(pluginInfo); } } PluginInfoList Loader::getMergedPluginInfoList() const { PluginInfoList pluginHistory = getPluginsHistory(); PluginInfoList currentLoadedPlugin = getCurrentPlugins(); PluginInfoList mergedPlugin; BOOST_FOREACH(const LPPluginInfo& pluginInfo, currentLoadedPlugin) { matchPluginInfo(pluginHistory, pluginInfo); mergedPlugin.push_back(pluginInfo); } BOOST_FOREACH(const LPPluginInfo& pluginInfo, pluginHistory) { if (matchPluginInfo(mergedPlugin, pluginInfo) != rdo::plugin::ExactMatched) { pluginInfo->setState(rdo::plugin::Deleted); mergedPlugin.push_back(pluginInfo); } } return mergedPlugin; } PluginInfoList Loader::getPluginsHistory() const { QSettings settings("RAO-studio", "RAO-studio"); PluginInfoList list; int size = settings.beginReadArray("plugins"); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); QString pluginName = settings.value("pluginName" , "").toString(); bool pluginAutoLoad = settings.value("pluginAutoLoad", false).toBool(); QString pluginAuthor = settings.value("pluginAuthor" , "").toString(); QString pluginVer = settings.value("pluginVer" , "").toString(); QUuid pluginGUID = settings.value("pluginGUID" , QUuid()).toUuid(); PluginInfo pluginInfo(pluginName, NULL, pluginAutoLoad, pluginGUID, pluginAuthor, pluginVer, rdo::plugin::Unique); list.push_back(rdo::Factory<PluginInfo>::create(pluginInfo)); } return list; } void Loader::setPluginInfoList(const PluginInfoList& value) const { QSettings settings; settings.remove("plugins"); settings.beginWriteArray("plugins"); int index = 0; BOOST_FOREACH(const LPPluginInfo& pluginInfo, value) { if (pluginInfo->getState() != rdo::plugin::IdOnlyMatched) { settings.setArrayIndex(index); settings.setValue("pluginName" , pluginInfo->getName()); settings.setValue("pluginAutoLoad", pluginInfo->getAutoload()); settings.setValue("pluginGUID" , pluginInfo->getGUID()); settings.setValue("pluginAuthor" , pluginInfo->getAuthor()); settings.setValue("pluginVer" , pluginInfo->getVersion()); index++; } } settings.endArray(); } PluginInfoList Loader::getCurrentPlugins() const { PluginInfoList list; QDir dir(qApp->applicationDirPath()); if (dir.cd("plugins")) { QStringList fileList = getFileList(dir.path()); BOOST_FOREACH(const QString& filePath, fileList) { QPluginLoader* pluginLoader = new QPluginLoader(filePath); PluginInterface* pluginInterface = loadPlugin(pluginLoader); if (pluginInterface) { PluginInfo pluginInfo = generatePluginInfo(pluginInterface, pluginLoader); LPPluginInfo pPlgnInfo = rdo::Factory<PluginInfo>::create(pluginInfo); pluginLoader->unload(); if (matchPluginInfo(list, pPlgnInfo) != rdo::plugin::ExactMatched) { list.push_back(pPlgnInfo); } else { delete pluginLoader; } } } } return list; } int Loader::matchPluginInfo(const PluginInfoList& list, const LPPluginInfo& pluginInfo) const { int pluginState = pluginInfo->getState(); BOOST_FOREACH(const LPPluginInfo& pluginInfo, list) { if (pluginInfo->getGUID() == pluginInfo->getGUID()) { if (pluginInfo->pluginSignInfoIsEqual(*pluginInfo)) { pluginInfo->setAutoload(pluginInfo->getAutoload()); pluginState = rdo::plugin::ExactMatched; break; } else { pluginState = rdo::plugin::IdOnlyMatched; } } } pluginInfo->setState(pluginState); return pluginState; } QStringList Loader::getFileList(const QString& startDir) const { QDir dir(startDir); QStringList list; BOOST_FOREACH(const QString& file, dir.entryList(QDir::Files)) { list += dir.absoluteFilePath(file); } BOOST_FOREACH(const QString& subdir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { list += getFileList(startDir + "/" + subdir); } return list; } PluginInterface* Loader::loadPlugin(QPluginLoader* pluginLoader) const { QObject* plugin = pluginLoader->instance(); if (plugin) { PluginInterface* pluginInterface = qobject_cast<PluginInterface*>(plugin); return pluginInterface; } return NULL; } PluginInfo Loader::generatePluginInfo(PluginInterface* pluginInterface, QPluginLoader* pluginLoader) const { QString pluginName = pluginInterface->getPluginName(); QUuid pluginGUID = pluginInterface->getGUID(); QString pluginAuthor = pluginInterface->getAuthor(); QString pluginVersion = pluginInterface->getVersion(); bool pluginAutoload = false; PluginInfo pluginInfo(pluginName, pluginLoader, pluginAutoload, pluginGUID, pluginAuthor, pluginVersion, rdo::plugin::Unique); return pluginInfo; } void Loader::stopPlugin(const LPPluginInfo& pluginInfo) { PluginInterface* pluginInterface = loadPlugin(pluginInfo->getLoader()); if (pluginInterface) { pluginInterface->pluginStopAction(m_pPluginsParent); pluginInfo->setActive(false); } } void Loader::startPlugin(const LPPluginInfo& pluginInfo) { PluginInterface* pluginInterface = loadPlugin(pluginInfo->getLoader()); if (pluginInterface) { pluginInterface->pluginStartAction(m_pPluginsParent); pluginInfo->setActive(true); } } void Loader::startAutoloadedPlugins() { BOOST_FOREACH(const LPPluginInfo& pluginInfo, *m_pMergedPluginInfoList) { if (pluginInfo->getAutoload() && pluginInfo->isAvailable()) { startPlugin(pluginInfo); } } } const LPPluginInfoList& Loader::getPluginInfoList() const { return m_pMergedPluginInfoList; } void Loader::initPluginParent(QWidget* pParent) { ASSERT(!m_pPluginsParent); ASSERT(pParent); m_pPluginsParent = pParent; } <commit_msg> - исправлена критичная опечатка в теле функции matchPluginInfo<commit_after>/*! \copyright (c) RDO-Team, 2013 \file app/rdo_studio/src/plugins/plugin_loader.cpp \author Чернов Алексей (ChernovAlexeyOlegovich@gmail.com) \date 22.09.2013 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include "utils/src/common/warning_disable.h" #include <QDir> #include <QApplication> #include <QSettings> #include <boost/foreach.hpp> #include "utils/src/common/warning_enable.h" // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/plugins/plugin_loader.h" // -------------------------------------------------------------------------------- using namespace rdo::plugin; Loader::Loader() : m_pPluginsParent(NULL) , m_pMergedPluginInfoList(rdo::Factory<PluginInfoList>::create(getMergedPluginInfoList())) {} Loader::~Loader() { BOOST_FOREACH(const LPPluginInfo& pluginInfo, *m_pMergedPluginInfoList) { if (pluginInfo->isActive()) stopPlugin(pluginInfo); } } PluginInfoList Loader::getMergedPluginInfoList() const { PluginInfoList pluginHistory = getPluginsHistory(); PluginInfoList currentLoadedPlugin = getCurrentPlugins(); PluginInfoList mergedPlugin; BOOST_FOREACH(const LPPluginInfo& pluginInfo, currentLoadedPlugin) { matchPluginInfo(pluginHistory, pluginInfo); mergedPlugin.push_back(pluginInfo); } BOOST_FOREACH(const LPPluginInfo& pluginInfo, pluginHistory) { if (matchPluginInfo(mergedPlugin, pluginInfo) != rdo::plugin::ExactMatched) { pluginInfo->setState(rdo::plugin::Deleted); mergedPlugin.push_back(pluginInfo); } } return mergedPlugin; } PluginInfoList Loader::getPluginsHistory() const { QSettings settings("RAO-studio", "RAO-studio"); PluginInfoList list; int size = settings.beginReadArray("plugins"); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); QString pluginName = settings.value("pluginName" , "").toString(); bool pluginAutoLoad = settings.value("pluginAutoLoad", false).toBool(); QString pluginAuthor = settings.value("pluginAuthor" , "").toString(); QString pluginVer = settings.value("pluginVer" , "").toString(); QUuid pluginGUID = settings.value("pluginGUID" , QUuid()).toUuid(); PluginInfo pluginInfo(pluginName, NULL, pluginAutoLoad, pluginGUID, pluginAuthor, pluginVer, rdo::plugin::Unique); list.push_back(rdo::Factory<PluginInfo>::create(pluginInfo)); } return list; } void Loader::setPluginInfoList(const PluginInfoList& value) const { QSettings settings; settings.remove("plugins"); settings.beginWriteArray("plugins"); int index = 0; BOOST_FOREACH(const LPPluginInfo& pluginInfo, value) { if (pluginInfo->getState() != rdo::plugin::IdOnlyMatched) { settings.setArrayIndex(index); settings.setValue("pluginName" , pluginInfo->getName()); settings.setValue("pluginAutoLoad", pluginInfo->getAutoload()); settings.setValue("pluginGUID" , pluginInfo->getGUID()); settings.setValue("pluginAuthor" , pluginInfo->getAuthor()); settings.setValue("pluginVer" , pluginInfo->getVersion()); index++; } } settings.endArray(); } PluginInfoList Loader::getCurrentPlugins() const { PluginInfoList list; QDir dir(qApp->applicationDirPath()); if (dir.cd("plugins")) { QStringList fileList = getFileList(dir.path()); BOOST_FOREACH(const QString& filePath, fileList) { QPluginLoader* pluginLoader = new QPluginLoader(filePath); PluginInterface* pluginInterface = loadPlugin(pluginLoader); if (pluginInterface) { PluginInfo pluginInfo = generatePluginInfo(pluginInterface, pluginLoader); LPPluginInfo pPlgnInfo = rdo::Factory<PluginInfo>::create(pluginInfo); pluginLoader->unload(); if (matchPluginInfo(list, pPlgnInfo) != rdo::plugin::ExactMatched) { list.push_back(pPlgnInfo); } else { delete pluginLoader; } } } } return list; } int Loader::matchPluginInfo(const PluginInfoList& list, const LPPluginInfo& matchingPluginInfo) const { int pluginState = matchingPluginInfo->getState(); BOOST_FOREACH(const LPPluginInfo& pluginInfo, list) { if (matchingPluginInfo->getGUID() == pluginInfo->getGUID()) { if (matchingPluginInfo->pluginSignInfoIsEqual(*pluginInfo)) { matchingPluginInfo->setAutoload(pluginInfo->getAutoload()); pluginState = rdo::plugin::ExactMatched; break; } else { pluginState = rdo::plugin::IdOnlyMatched; } } } matchingPluginInfo->setState(pluginState); return pluginState; } QStringList Loader::getFileList(const QString& startDir) const { QDir dir(startDir); QStringList list; BOOST_FOREACH(const QString& file, dir.entryList(QDir::Files)) { list += dir.absoluteFilePath(file); } BOOST_FOREACH(const QString& subdir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { list += getFileList(startDir + "/" + subdir); } return list; } PluginInterface* Loader::loadPlugin(QPluginLoader* pluginLoader) const { QObject* plugin = pluginLoader->instance(); if (plugin) { PluginInterface* pluginInterface = qobject_cast<PluginInterface*>(plugin); return pluginInterface; } return NULL; } PluginInfo Loader::generatePluginInfo(PluginInterface* pluginInterface, QPluginLoader* pluginLoader) const { QString pluginName = pluginInterface->getPluginName(); QUuid pluginGUID = pluginInterface->getGUID(); QString pluginAuthor = pluginInterface->getAuthor(); QString pluginVersion = pluginInterface->getVersion(); bool pluginAutoload = false; PluginInfo pluginInfo(pluginName, pluginLoader, pluginAutoload, pluginGUID, pluginAuthor, pluginVersion, rdo::plugin::Unique); return pluginInfo; } void Loader::stopPlugin(const LPPluginInfo& pluginInfo) { PluginInterface* pluginInterface = loadPlugin(pluginInfo->getLoader()); if (pluginInterface) { pluginInterface->pluginStopAction(m_pPluginsParent); pluginInfo->setActive(false); } } void Loader::startPlugin(const LPPluginInfo& pluginInfo) { PluginInterface* pluginInterface = loadPlugin(pluginInfo->getLoader()); if (pluginInterface) { pluginInterface->pluginStartAction(m_pPluginsParent); pluginInfo->setActive(true); } } void Loader::startAutoloadedPlugins() { BOOST_FOREACH(const LPPluginInfo& pluginInfo, *m_pMergedPluginInfoList) { if (pluginInfo->getAutoload() && pluginInfo->isAvailable()) { startPlugin(pluginInfo); } } } const LPPluginInfoList& Loader::getPluginInfoList() const { return m_pMergedPluginInfoList; } void Loader::initPluginParent(QWidget* pParent) { ASSERT(!m_pPluginsParent); ASSERT(pParent); m_pPluginsParent = pParent; } <|endoftext|>
<commit_before>/* Copyright (c) 2003-2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <vector> #include <cctype> #include <boost/bind.hpp> #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/aux_/session_impl.hpp" using boost::tuples::make_tuple; using boost::tuples::tuple; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; } namespace libtorrent { timeout_handler::timeout_handler(io_service& ios) : m_start_time(time_now_hires()) , m_read_time(m_start_time) , m_timeout(ios) , m_completion_timeout(0) , m_read_timeout(0) , m_abort(false) {} void timeout_handler::set_timeout(int completion_timeout, int read_timeout) { m_completion_timeout = completion_timeout; m_read_timeout = read_timeout; m_start_time = m_read_time = time_now_hires(); TORRENT_ASSERT(completion_timeout > 0 || read_timeout > 0); if (m_abort) return; int timeout = 0; if (m_read_timeout > 0) timeout = m_read_timeout; if (m_completion_timeout > 0) { timeout = timeout == 0 ? m_completion_timeout : (std::min)(m_completion_timeout, timeout); } #if defined TORRENT_ASIO_DEBUGGING add_outstanding_async("timeout_handler::timeout_callback"); #endif error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait(boost::bind( &timeout_handler::timeout_callback, self(), _1)); } void timeout_handler::restart_read_timeout() { m_read_time = time_now_hires(); } void timeout_handler::cancel() { m_abort = true; m_completion_timeout = 0; error_code ec; m_timeout.cancel(ec); } void timeout_handler::timeout_callback(error_code const& error) { #if defined TORRENT_ASIO_DEBUGGING complete_async("timeout_handler::timeout_callback"); #endif if (m_abort) return; ptime now = time_now_hires(); time_duration receive_timeout = now - m_read_time; time_duration completion_timeout = now - m_start_time; if ((m_read_timeout && m_read_timeout <= total_seconds(receive_timeout)) || (m_completion_timeout && m_completion_timeout <= total_seconds(completion_timeout)) || error) { on_timeout(error); return; } int timeout = 0; if (m_read_timeout > 0) timeout = m_read_timeout; if (m_completion_timeout > 0) { timeout = timeout == 0 ? m_completion_timeout - total_seconds(m_read_time - m_start_time) : (std::min)(m_completion_timeout - total_seconds(m_read_time - m_start_time), timeout); } #if defined TORRENT_ASIO_DEBUGGING add_outstanding_async("timeout_handler::timeout_callback"); #endif error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait( boost::bind(&timeout_handler::timeout_callback, self(), _1)); } tracker_connection::tracker_connection( tracker_manager& man , tracker_request const& req , io_service& ios , boost::weak_ptr<request_callback> r) : timeout_handler(ios) , m_requester(r) , m_man(man) , m_req(req) {} boost::shared_ptr<request_callback> tracker_connection::requester() const { return m_requester.lock(); } void tracker_connection::fail(error_code const& ec, int code , char const* msg, int interval, int min_interval) { boost::shared_ptr<request_callback> cb = requester(); if (cb) cb->tracker_request_error(m_req, code, ec, msg , interval == 0 ? min_interval : interval); close(); } void tracker_connection::sent_bytes(int bytes) { m_man.sent_bytes(bytes); } void tracker_connection::received_bytes(int bytes) { m_man.received_bytes(bytes); } void tracker_connection::close() { cancel(); m_man.remove_request(this); } tracker_manager::~tracker_manager() { TORRENT_ASSERT(m_abort); abort_all_requests(true); } void tracker_manager::sent_bytes(int bytes) { TORRENT_ASSERT(m_ses.is_network_thread()); m_ses.m_stat.sent_tracker_bytes(bytes); } void tracker_manager::received_bytes(int bytes) { TORRENT_ASSERT(m_ses.is_network_thread()); m_ses.m_stat.received_tracker_bytes(bytes); } void tracker_manager::remove_request(tracker_connection const* c) { mutex_t::scoped_lock l(m_mutex); tracker_connections_t::iterator i = std::find(m_connections.begin() , m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c)); if (i == m_connections.end()) return; m_connections.erase(i); } void tracker_manager::queue_request( io_service& ios , connection_queue& cc , tracker_request req , std::string const& auth , boost::weak_ptr<request_callback> c) { mutex_t::scoped_lock l(m_mutex); TORRENT_ASSERT(req.num_want >= 0); TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped); if (m_abort && req.event != tracker_request::stopped) return; if (req.event == tracker_request::stopped) req.num_want = 0; TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped); if (m_abort && req.event != tracker_request::stopped) return; std::string protocol = req.url.substr(0, req.url.find(':')); boost::intrusive_ptr<tracker_connection> con; #ifdef TORRENT_USE_OPENSSL if (protocol == "http" || protocol == "https") #else if (protocol == "http") #endif { con = new http_tracker_connection( ios, cc, *this, req, c , m_ses, m_proxy, auth #if TORRENT_USE_I2P , &m_ses.m_i2p_conn #endif ); } else if (protocol == "udp") { con = new udp_tracker_connection( ios, cc, *this, req , c, m_ses , m_proxy); } else { // we need to post the error to avoid deadlock if (boost::shared_ptr<request_callback> r = c.lock()) ios.post(boost::bind(&request_callback::tracker_request_error, r, req , -1, error_code(errors::unsupported_url_protocol) , "", 0)); return; } m_connections.push_back(con); boost::shared_ptr<request_callback> cb = con->requester(); if (cb) cb->m_manager = this; con->start(); } bool tracker_manager::incoming_packet(error_code const& e , udp::endpoint const& ep, char const* buf, int size) { // m_ses.m_stat.received_tracker_bytes(len + 28); for (tracker_connections_t::iterator i = m_connections.begin(); i != m_connections.end();) { boost::intrusive_ptr<tracker_connection> p = *i; ++i; // on_receive() may remove the tracker connection from the list if (p->on_receive(e, ep, buf, size)) return true; } return false; } bool tracker_manager::incoming_packet(error_code const& e , char const* hostname, char const* buf, int size) { // m_ses.m_stat.received_tracker_bytes(len + 28); for (tracker_connections_t::iterator i = m_connections.begin(); i != m_connections.end();) { boost::intrusive_ptr<tracker_connection> p = *i; ++i; // on_receive() may remove the tracker connection from the list if (p->on_receive_hostname(e, hostname, buf, size)) return true; } return false; } void tracker_manager::abort_all_requests(bool all) { // removes all connections from m_connections // except 'event=stopped'-requests mutex_t::scoped_lock l(m_mutex); m_abort = true; tracker_connections_t close_connections; for (tracker_connections_t::iterator i = m_connections.begin() , end(m_connections.end()); i != end; ++i) { intrusive_ptr<tracker_connection> c = *i; tracker_request const& req = c->tracker_req(); if (req.event == tracker_request::stopped && !all) continue; close_connections.push_back(c); #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING boost::shared_ptr<request_callback> rc = c->requester(); if (rc) rc->debug_log("aborting: %s", req.url.c_str()); #endif } l.unlock(); for (tracker_connections_t::iterator i = close_connections.begin() , end(close_connections.end()); i != end; ++i) { (*i)->close(); } } bool tracker_manager::empty() const { mutex_t::scoped_lock l(m_mutex); return m_connections.empty(); } int tracker_manager::num_requests() const { mutex_t::scoped_lock l(m_mutex); return m_connections.size(); } } <commit_msg>fix ambiguity invoking min<commit_after>/* Copyright (c) 2003-2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <vector> #include <cctype> #include <boost/bind.hpp> #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/aux_/session_impl.hpp" using boost::tuples::make_tuple; using boost::tuples::tuple; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; } namespace libtorrent { timeout_handler::timeout_handler(io_service& ios) : m_start_time(time_now_hires()) , m_read_time(m_start_time) , m_timeout(ios) , m_completion_timeout(0) , m_read_timeout(0) , m_abort(false) {} void timeout_handler::set_timeout(int completion_timeout, int read_timeout) { m_completion_timeout = completion_timeout; m_read_timeout = read_timeout; m_start_time = m_read_time = time_now_hires(); TORRENT_ASSERT(completion_timeout > 0 || read_timeout > 0); if (m_abort) return; int timeout = 0; if (m_read_timeout > 0) timeout = m_read_timeout; if (m_completion_timeout > 0) { timeout = timeout == 0 ? m_completion_timeout : (std::min)(m_completion_timeout, timeout); } #if defined TORRENT_ASIO_DEBUGGING add_outstanding_async("timeout_handler::timeout_callback"); #endif error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait(boost::bind( &timeout_handler::timeout_callback, self(), _1)); } void timeout_handler::restart_read_timeout() { m_read_time = time_now_hires(); } void timeout_handler::cancel() { m_abort = true; m_completion_timeout = 0; error_code ec; m_timeout.cancel(ec); } void timeout_handler::timeout_callback(error_code const& error) { #if defined TORRENT_ASIO_DEBUGGING complete_async("timeout_handler::timeout_callback"); #endif if (m_abort) return; ptime now = time_now_hires(); time_duration receive_timeout = now - m_read_time; time_duration completion_timeout = now - m_start_time; if ((m_read_timeout && m_read_timeout <= total_seconds(receive_timeout)) || (m_completion_timeout && m_completion_timeout <= total_seconds(completion_timeout)) || error) { on_timeout(error); return; } int timeout = 0; if (m_read_timeout > 0) timeout = m_read_timeout; if (m_completion_timeout > 0) { timeout = timeout == 0 ? m_completion_timeout - total_seconds(m_read_time - m_start_time) : (std::min)(int(m_completion_timeout - total_seconds(m_read_time - m_start_time)), timeout); } #if defined TORRENT_ASIO_DEBUGGING add_outstanding_async("timeout_handler::timeout_callback"); #endif error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait( boost::bind(&timeout_handler::timeout_callback, self(), _1)); } tracker_connection::tracker_connection( tracker_manager& man , tracker_request const& req , io_service& ios , boost::weak_ptr<request_callback> r) : timeout_handler(ios) , m_requester(r) , m_man(man) , m_req(req) {} boost::shared_ptr<request_callback> tracker_connection::requester() const { return m_requester.lock(); } void tracker_connection::fail(error_code const& ec, int code , char const* msg, int interval, int min_interval) { boost::shared_ptr<request_callback> cb = requester(); if (cb) cb->tracker_request_error(m_req, code, ec, msg , interval == 0 ? min_interval : interval); close(); } void tracker_connection::sent_bytes(int bytes) { m_man.sent_bytes(bytes); } void tracker_connection::received_bytes(int bytes) { m_man.received_bytes(bytes); } void tracker_connection::close() { cancel(); m_man.remove_request(this); } tracker_manager::~tracker_manager() { TORRENT_ASSERT(m_abort); abort_all_requests(true); } void tracker_manager::sent_bytes(int bytes) { TORRENT_ASSERT(m_ses.is_network_thread()); m_ses.m_stat.sent_tracker_bytes(bytes); } void tracker_manager::received_bytes(int bytes) { TORRENT_ASSERT(m_ses.is_network_thread()); m_ses.m_stat.received_tracker_bytes(bytes); } void tracker_manager::remove_request(tracker_connection const* c) { mutex_t::scoped_lock l(m_mutex); tracker_connections_t::iterator i = std::find(m_connections.begin() , m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c)); if (i == m_connections.end()) return; m_connections.erase(i); } void tracker_manager::queue_request( io_service& ios , connection_queue& cc , tracker_request req , std::string const& auth , boost::weak_ptr<request_callback> c) { mutex_t::scoped_lock l(m_mutex); TORRENT_ASSERT(req.num_want >= 0); TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped); if (m_abort && req.event != tracker_request::stopped) return; if (req.event == tracker_request::stopped) req.num_want = 0; TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped); if (m_abort && req.event != tracker_request::stopped) return; std::string protocol = req.url.substr(0, req.url.find(':')); boost::intrusive_ptr<tracker_connection> con; #ifdef TORRENT_USE_OPENSSL if (protocol == "http" || protocol == "https") #else if (protocol == "http") #endif { con = new http_tracker_connection( ios, cc, *this, req, c , m_ses, m_proxy, auth #if TORRENT_USE_I2P , &m_ses.m_i2p_conn #endif ); } else if (protocol == "udp") { con = new udp_tracker_connection( ios, cc, *this, req , c, m_ses , m_proxy); } else { // we need to post the error to avoid deadlock if (boost::shared_ptr<request_callback> r = c.lock()) ios.post(boost::bind(&request_callback::tracker_request_error, r, req , -1, error_code(errors::unsupported_url_protocol) , "", 0)); return; } m_connections.push_back(con); boost::shared_ptr<request_callback> cb = con->requester(); if (cb) cb->m_manager = this; con->start(); } bool tracker_manager::incoming_packet(error_code const& e , udp::endpoint const& ep, char const* buf, int size) { // m_ses.m_stat.received_tracker_bytes(len + 28); for (tracker_connections_t::iterator i = m_connections.begin(); i != m_connections.end();) { boost::intrusive_ptr<tracker_connection> p = *i; ++i; // on_receive() may remove the tracker connection from the list if (p->on_receive(e, ep, buf, size)) return true; } return false; } bool tracker_manager::incoming_packet(error_code const& e , char const* hostname, char const* buf, int size) { // m_ses.m_stat.received_tracker_bytes(len + 28); for (tracker_connections_t::iterator i = m_connections.begin(); i != m_connections.end();) { boost::intrusive_ptr<tracker_connection> p = *i; ++i; // on_receive() may remove the tracker connection from the list if (p->on_receive_hostname(e, hostname, buf, size)) return true; } return false; } void tracker_manager::abort_all_requests(bool all) { // removes all connections from m_connections // except 'event=stopped'-requests mutex_t::scoped_lock l(m_mutex); m_abort = true; tracker_connections_t close_connections; for (tracker_connections_t::iterator i = m_connections.begin() , end(m_connections.end()); i != end; ++i) { intrusive_ptr<tracker_connection> c = *i; tracker_request const& req = c->tracker_req(); if (req.event == tracker_request::stopped && !all) continue; close_connections.push_back(c); #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING boost::shared_ptr<request_callback> rc = c->requester(); if (rc) rc->debug_log("aborting: %s", req.url.c_str()); #endif } l.unlock(); for (tracker_connections_t::iterator i = close_connections.begin() , end(close_connections.end()); i != end; ++i) { (*i)->close(); } } bool tracker_manager::empty() const { mutex_t::scoped_lock l(m_mutex); return m_connections.empty(); } int tracker_manager::num_requests() const { mutex_t::scoped_lock l(m_mutex); return m_connections.size(); } } <|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. ==============================================================================*/ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { ArrayDataType CommonDataTypeOfAllInputs(const Model& model, const Operator& op) { CHECK_GT(op.inputs.size(), 0); const ArrayDataType data_type = model.GetArray(op.inputs[0]).data_type; for (const auto& input : op.inputs) { const auto& array = model.GetArray(input); CHECK(array.data_type == data_type) << " Unexpected: this operator has inputs with different data types."; } return data_type; } void SetDataTypeForAllOutputs(Model* model, Operator* op, ArrayDataType data_type) { for (const auto& output : op->outputs) { model->arrays[output]->data_type = data_type; } } } // namespace bool PropagateArrayDataTypes::Run(Model* model, std::size_t op_index) { auto it = model->operators.begin() + op_index; auto* op = it->get(); // If the data type of some input is unknown, we need to yield. for (const auto& input : op->inputs) { if (model->arrays[input]->data_type == ArrayDataType::kNone) { return false; } } // Record data types of output before processing, so we can see at the // end if we changed anything, and return the correct boolean value. std::unordered_map<string, ArrayDataType> old_output_data_types; for (const auto& output : op->outputs) { old_output_data_types[output] = model->arrays[output]->data_type; } // Do the actual output data types propagation. if (op->type == OperatorType::kDequantize || op->type == OperatorType::kResizeBilinear) { // These operators unconditionally produce float outputs SetDataTypeForAllOutputs(model, op, ArrayDataType::kFloat); } else if (op->type == OperatorType::kTensorFlowLess || op->type == OperatorType::kTensorFlowLessEqual || op->type == OperatorType::kTensorFlowGreater || op->type == OperatorType::kTensorFlowGreaterEqual) { // These operators unconditionally produce bool outputs SetDataTypeForAllOutputs(model, op, ArrayDataType::kBool); } else if (op->type == OperatorType::kTensorFlowShape) { // These operators are assumed to produce int32 outputs. SetDataTypeForAllOutputs(model, op, ArrayDataType::kInt32); } else if (op->type == OperatorType::kAveragePool || op->type == OperatorType::kMaxPool || op->type == OperatorType::kL2Pool || op->type == OperatorType::kConv || op->type == OperatorType::kDepthwiseConv || op->type == OperatorType::kFullyConnected || op->type == OperatorType::kTensorFlowMax || op->type == OperatorType::kTensorFlowMin || op->type == OperatorType::kPad || op->type == OperatorType::kStridedSlice || op->type == OperatorType::kTensorFlowReshape || op->type == OperatorType::kSlice || op->type == OperatorType::kSqueeze || op->type == OperatorType::kTensorFlowSum || op->type == OperatorType::kTensorFlowSwitch || op->type == OperatorType::kTensorFlowTile || op->type == OperatorType::kTensorFlowAll || op->type == OperatorType::kReorderAxes || op->type == OperatorType::kTensorFlowConcatV2 || op->type == OperatorType::kFloor || op->type == OperatorType::kGather || op->type == OperatorType::kSpaceToBatchND || op->type == OperatorType::kBatchToSpaceND || op->type == OperatorType::kMean) { // These operators produce outputs with the same type as their 1st input CHECK_GT(op->inputs.size(), 0); const ArrayDataType data_type = model->arrays[op->inputs[0]]->data_type; SetDataTypeForAllOutputs(model, op, data_type); } else if (op->type == OperatorType::kTensorFlowSplit || op->type == OperatorType::kTensorFlowConcat) { // These operators produce an output with the same type as their 2nd input CHECK_GT(op->inputs.size(), 1); const ArrayDataType data_type = model->arrays[op->inputs[1]]->data_type; SetDataTypeForAllOutputs(model, op, data_type); } else if (op->type == OperatorType::kCast) { // Data type of the Cast op is specified. CHECK_EQ(op->outputs.size(), 1); auto* cast_op = static_cast<CastOperator*>(op); model->arrays[op->outputs[0]]->data_type = cast_op->dst_data_type; } else if (op->type == OperatorType::kTensorFlowUnsupported) { auto* unsupported_op = static_cast<TensorFlowUnsupportedOperator*>(op); if (unsupported_op->output_data_types.size() != op->outputs.size()) { return false; } for (int i = 0; i < unsupported_op->output_data_types.size(); ++i) { auto output = op->outputs[i]; auto data_type = unsupported_op->output_data_types[i]; model->arrays[output]->data_type = data_type; } } else { // These operators produce an output with the same type as any of their // inputs, which must always have the same type. const ArrayDataType data_type = CommonDataTypeOfAllInputs(*model, *op); SetDataTypeForAllOutputs(model, op, data_type); } // Return true if any output data type changed, false if none changed. for (const auto& output : op->outputs) { if (old_output_data_types[output] != model->arrays[output]->data_type) { return true; } } return false; } } // namespace toco <commit_msg>Simplification of propagate_array_data_types: No need to distinguish between ops for which we propagate the type of the first input, and ops for which we require all inputs to have the same type then propagate that type. Doing only the former is a mild relaxation of what we've been doing, allows to drop much code, and makes this code far less frequently needing to be updated again in the future as we drop a long non-canonical list of operator types being special-cased.<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. ==============================================================================*/ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { void SetDataTypeForAllOutputs(Model* model, Operator* op, ArrayDataType data_type) { for (const auto& output : op->outputs) { model->arrays[output]->data_type = data_type; } } } // namespace bool PropagateArrayDataTypes::Run(Model* model, std::size_t op_index) { auto it = model->operators.begin() + op_index; auto* op = it->get(); // If the data type of some input is unknown, we need to yield. for (const auto& input : op->inputs) { if (model->arrays[input]->data_type == ArrayDataType::kNone) { return false; } } // Record data types of output before processing, so we can see at the // end if we changed anything, and return the correct boolean value. std::unordered_map<string, ArrayDataType> old_output_data_types; for (const auto& output : op->outputs) { old_output_data_types[output] = model->arrays[output]->data_type; } // Do the actual output data types propagation. if (op->type == OperatorType::kDequantize || op->type == OperatorType::kResizeBilinear) { // These operators unconditionally produce float outputs SetDataTypeForAllOutputs(model, op, ArrayDataType::kFloat); } else if (op->type == OperatorType::kTensorFlowLess || op->type == OperatorType::kTensorFlowLessEqual || op->type == OperatorType::kTensorFlowGreater || op->type == OperatorType::kTensorFlowGreaterEqual) { // These operators unconditionally produce bool outputs SetDataTypeForAllOutputs(model, op, ArrayDataType::kBool); } else if (op->type == OperatorType::kTensorFlowShape) { // These operators are assumed to produce int32 outputs. SetDataTypeForAllOutputs(model, op, ArrayDataType::kInt32); } else if (op->type == OperatorType::kTensorFlowSplit || op->type == OperatorType::kTensorFlowConcat) { // These operators produce an output with the same type as their 2nd input CHECK_GT(op->inputs.size(), 1); const ArrayDataType data_type = model->arrays[op->inputs[1]]->data_type; SetDataTypeForAllOutputs(model, op, data_type); } else if (op->type == OperatorType::kCast) { // Data type of the Cast op is specified. CHECK_EQ(op->outputs.size(), 1); auto* cast_op = static_cast<CastOperator*>(op); model->arrays[op->outputs[0]]->data_type = cast_op->dst_data_type; } else if (op->type == OperatorType::kTensorFlowUnsupported) { auto* unsupported_op = static_cast<TensorFlowUnsupportedOperator*>(op); if (unsupported_op->output_data_types.size() != op->outputs.size()) { return false; } for (int i = 0; i < unsupported_op->output_data_types.size(); ++i) { auto output = op->outputs[i]; auto data_type = unsupported_op->output_data_types[i]; model->arrays[output]->data_type = data_type; } } else { // These operators produce outputs with the same type as their 1st input CHECK_GT(op->inputs.size(), 0); const ArrayDataType data_type = model->arrays[op->inputs[0]]->data_type; SetDataTypeForAllOutputs(model, op, data_type); } // Return true if any output data type changed, false if none changed. for (const auto& output : op->outputs) { if (old_output_data_types[output] != model->arrays[output]->data_type) { return true; } } return false; } } // namespace toco <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "AbaqusUMATStress.h" #include "Factory.h" #include "MooseMesh.h" #include "RankTwoTensor.h" #include "RankFourTensor.h" #include "libmesh/int_range.h" #include <string.h> #include <algorithm> #define QUOTE(macro) stringifyName(macro) MooseEnum AbaqusUMATStress::decompositionType() { return MooseEnum("TaylorExpansion EigenSolution HughesWinget", "TaylorExpansion"); } registerMooseObject("TensorMechanicsApp", AbaqusUMATStress); InputParameters AbaqusUMATStress::validParams() { InputParameters params = ComputeStressBase::validParams(); params.addClassDescription("Coupling material to use Abaqus UMAT models in MOOSE"); params.addRequiredParam<FileName>( "plugin", "The path to the compiled dynamic library for the plugin you want to use"); params.addRequiredParam<bool>( "use_one_based_indexing", "Parameter to control whether indexing for element and integration points as presented to " "UMAT models is based on 1 (true) or 0 (false). This does not affect internal MOOSE " "numbering. The option to use 0-based numbering is deprecated and will be removed soon."); params.addRequiredParam<std::vector<Real>>( "constant_properties", "Constant mechanical and thermal material properties (PROPS)"); params.addRequiredParam<unsigned int>("num_state_vars", "The number of state variables this UMAT is going to use"); params.addCoupledVar("temperature", 0.0, "Coupled temperature"); params.addCoupledVar("external_fields", "The external fields that can be used in the UMAT subroutine"); params.addParam<std::vector<MaterialPropertyName>>("external_properties", ""); params.addParam<MooseEnum>("decomposition_method", AbaqusUMATStress::decompositionType(), "Method to calcualte the strain kinematics."); return params; } #ifndef METHOD #error "The METHOD preprocessor symbol must be supplied by the build system." #endif AbaqusUMATStress::AbaqusUMATStress(const InputParameters & parameters) : ComputeStressBase(parameters), _plugin(getParam<FileName>("plugin")), _library(_plugin + std::string("-") + QUOTE(METHOD) + ".plugin"), _umat(_library.getFunction<umat_t>("umat_")), _aqNSTATV(getParam<unsigned int>("num_state_vars")), _aqSTATEV(_aqNSTATV), _aqPROPS(getParam<std::vector<Real>>("constant_properties")), _aqNPROPS(_aqPROPS.size()), _stress_old(getMaterialPropertyOld<RankTwoTensor>(_base_name + "stress")), _total_strain_old(getMaterialPropertyOld<RankTwoTensor>(_base_name + "total_strain")), _strain_increment(getOptionalMaterialProperty<RankTwoTensor>(_base_name + "strain_increment")), _jacobian_mult(declareProperty<RankFourTensor>(_base_name + "Jacobian_mult")), _Fbar(getOptionalMaterialProperty<RankTwoTensor>(_base_name + "deformation_gradient")), _Fbar_old(getOptionalMaterialPropertyOld<RankTwoTensor>(_base_name + "deformation_gradient")), _state_var(declareProperty<std::vector<Real>>(_base_name + "state_var")), _state_var_old(getMaterialPropertyOld<std::vector<Real>>(_base_name + "state_var")), _elastic_strain_energy(declareProperty<Real>(_base_name + "elastic_strain_energy")), _plastic_dissipation(declareProperty<Real>(_base_name + "plastic_dissipation")), _creep_dissipation(declareProperty<Real>(_base_name + "creep_dissipation")), _material_timestep(declareProperty<Real>(_base_name + "material_timestep_limit")), _rotation_increment( getOptionalMaterialProperty<RankTwoTensor>(_base_name + "rotation_increment")), _temperature(coupledValue("temperature")), _temperature_old(coupledValueOld("temperature")), _external_fields(coupledValues("external_fields")), _external_fields_old(coupledValuesOld("external_fields")), _number_external_fields(_external_fields.size()), _external_property_names(getParam<std::vector<MaterialPropertyName>>("external_properties")), _number_external_properties(_external_property_names.size()), _external_properties(_number_external_properties), _external_properties_old(_number_external_properties), _use_one_based_indexing(getParam<bool>("use_one_based_indexing")), _decomposition_method(getParam<MooseEnum>("decomposition_method").getEnum<DecompMethod>()) { if (!_use_one_based_indexing) mooseDeprecated( "AbaqusUMATStress has transitioned to 1-based indexing in the element (NOEL) and " "integration point (NPT) numbers to ensure maximum compatibility with legacy UMAT files. " "Please ensure that any new UMAT plugins using these quantities are using the correct " "indexing. 0-based indexing will be deprecated soon."); // get material properties for (std::size_t i = 0; i < _number_external_properties; ++i) { _external_properties[i] = &getMaterialProperty<Real>(_external_property_names[i]); _external_properties_old[i] = &getMaterialPropertyOld<Real>(_external_property_names[i]); } // Read mesh dimension and size UMAT arrays (we always size for full 3D) _aqNTENS = 6; // Size of the stress or strain component array (NDI+NSHR) _aqNSHR = 3; // Number of engineering shear stress components _aqNDI = 3; // Number of direct stress components (always 3) _aqDDSDDT.resize(_aqNTENS); _aqDRPLDE.resize(_aqNTENS); _aqSTRAN.resize(_aqNTENS); _aqDFGRD0.resize(9); _aqDFGRD1.resize(9); _aqDROT.resize(9); _aqSTRESS.resize(_aqNTENS); _aqDDSDDE.resize(_aqNTENS * _aqNTENS); _aqDSTRAN.resize(_aqNTENS); _aqPREDEF.resize(_number_external_fields + _number_external_properties); _aqDPRED.resize(_number_external_fields + _number_external_properties); } void AbaqusUMATStress::initialSetup() { // The _Fbar, _Fbar_old, and _rotation_increment optional properties are only available when an // incremental strain formulation is used. If they are not avaliable we advide the user to // select an incremental formulation. if (!_strain_increment || !_Fbar || !_Fbar_old || !_rotation_increment) mooseError("AbaqusUMATStress '", name(), "': Incremental strain quantities are not available. You likely are using a total " "strain formulation. Specify `incremental = true` in the tensor mechanics action, " "or use ComputeIncrementalSmallStrain in your input file."); } void AbaqusUMATStress::initQpStatefulProperties() { ComputeStressBase::initQpStatefulProperties(); // Initialize state variable vector _state_var[_qp].resize(_aqNSTATV); for (const auto i : make_range(_aqNSTATV)) _state_var[_qp][i] = 0.0; } void AbaqusUMATStress::computeProperties() { // current element "number" _aqNOEL = _current_elem->id() + (_use_one_based_indexing ? 1 : 0); // characteristic element length _aqCELENT = std::pow(_current_elem->volume(), 1.0 / _current_elem->dim()); // For now, total time and step time mean the exact same thing // Value of step time at the beginning of the current increment _aqTIME[0] = _t - _dt; // Value of total time at the beginning of the current increment _aqTIME[1] = _t - _dt; // Time increment _aqDTIME = _dt; // Fill unused characters with spaces (Fortran) std::fill(_aqCMNAME, _aqCMNAME + 80, ' '); std::memcpy(_aqCMNAME, name().c_str(), name().size()); ComputeStressBase::computeProperties(); } void AbaqusUMATStress::computeQpStress() { const Real * myDFGRD0 = &(_Fbar_old[_qp](0, 0)); const Real * myDFGRD1 = &(_Fbar[_qp](0, 0)); const Real * myDROT = &(_rotation_increment[_qp](0, 0)); // copy because UMAT does not guarantee constness for (const auto i : make_range(9)) { _aqDFGRD0[i] = myDFGRD0[i]; _aqDFGRD1[i] = myDFGRD1[i]; _aqDROT[i] = myDROT[i]; } // Recover "old" state variables for (const auto i : make_range(_aqNSTATV)) _aqSTATEV[i] = _state_var_old[_qp][i]; // Pass through updated stress, total strain, and strain increment arrays static const std::array<Real, 6> strain_factor{{1, 1, 1, 2, 2, 2}}; // Account for difference in vector order convention: yz, xz, xy (MOOSE) vs xy, xz, yz // (commercial software) static const std::array<std::pair<unsigned int, unsigned int>, 6> component{ {{0, 0}, {1, 1}, {2, 2}, {0, 1}, {0, 2}, {1, 2}}}; // rotate old stress if HughesWinget RankTwoTensor stress_old = _stress_old[_qp]; if (_decomposition_method == DecompMethod::HughesWinget) stress_old.rotate(_rotation_increment[_qp]); for (const auto i : make_range(_aqNTENS)) { const auto a = component[i].first; const auto b = component[i].second; _aqSTRESS[i] = stress_old(a, b); _aqSTRAN[i] = _total_strain_old[_qp](a, b) * strain_factor[i]; _aqDSTRAN[i] = _strain_increment[_qp](a, b) * strain_factor[i]; } // current coordinates for (const auto i : make_range(Moose::dim)) _aqCOORDS[i] = _q_point[_qp](i); // zero out Jacobian contribution for (const auto i : make_range(_aqNTENS * _aqNTENS)) _aqDDSDDE[i] = 0.0; // Set PNEWDT initially to a large value _aqPNEWDT = std::numeric_limits<Real>::max(); // Temperature _aqTEMP = _temperature_old[_qp]; // Temperature increment _aqDTEMP = _temperature[_qp] - _temperature_old[_qp]; for (const auto i : make_range(_number_external_fields)) { // External field at this step _aqPREDEF[i] = (*_external_fields_old[i])[_qp]; // External field increments _aqDPRED[i] = (*_external_fields[i])[_qp] - (*_external_fields_old[i])[_qp]; } for (const auto i : make_range(_number_external_properties)) { // External property at this step _aqPREDEF[i + _number_external_fields] = (*_external_properties_old[i])[_qp]; // External property increments _aqDPRED[i + _number_external_fields] = (*_external_properties[i])[_qp] - (*_external_properties_old[i])[_qp]; } // Layer number (not supported) _aqLAYER = -1; // Section point number within the layer (not supported) _aqKSPT = -1; // Increment number _aqKINC = _t_step; _aqKSTEP = 1; // integration point number _aqNPT = _qp + (_use_one_based_indexing ? 1 : 0); // Connection to extern statement _umat(_aqSTRESS.data(), _aqSTATEV.data(), _aqDDSDDE.data(), &_elastic_strain_energy[_qp], &_plastic_dissipation[_qp], &_creep_dissipation[_qp], &_aqRPL, _aqDDSDDT.data(), _aqDRPLDE.data(), &_aqDRPLDT, _aqSTRAN.data(), _aqDSTRAN.data(), _aqTIME.data(), &_aqDTIME, &_aqTEMP, &_aqDTEMP, _aqPREDEF.data(), _aqDPRED.data(), _aqCMNAME, &_aqNDI, &_aqNSHR, &_aqNTENS, &_aqNSTATV, _aqPROPS.data(), &_aqNPROPS, _aqCOORDS.data(), _aqDROT.data(), &_aqPNEWDT, &_aqCELENT, _aqDFGRD0.data(), _aqDFGRD1.data(), &_aqNOEL, &_aqNPT, &_aqLAYER, &_aqKSPT, &_aqKSTEP, &_aqKINC); // Update state variables for (int i = 0; i < _aqNSTATV; ++i) _state_var[_qp][i] = _aqSTATEV[i]; // Here, we apply UMAT convention: Always multiply _dt by PNEWDT to determine the material time // step MOOSE time stepper will choose the most limiting of all material time step increments // provided _material_timestep[_qp] = _aqPNEWDT * _dt; // Get new stress tensor - UMAT should update stress // Account for difference in vector order convention: yz, xz, xy (MOOSE) vs xy, xz, yz // (commercial software) _stress[_qp] = RankTwoTensor( _aqSTRESS[0], _aqSTRESS[1], _aqSTRESS[2], _aqSTRESS[5], _aqSTRESS[4], _aqSTRESS[3]); // Rotate the stress state to the current configuration, unless HughesWinget if (_decomposition_method != DecompMethod::HughesWinget) _stress[_qp].rotate(_rotation_increment[_qp]); // Build Jacobian matrix from UMAT's Voigt non-standard order to fourth order tensor. const unsigned int N = Moose::dim; const unsigned int ntens = N * (N + 1) / 2; const int nskip = N - 1; for (const auto i : make_range(N)) for (const auto j : make_range(N)) for (const auto k : make_range(N)) for (const auto l : make_range(N)) { if (i == j) _jacobian_mult[_qp](i, j, k, l) = k == l ? _aqDDSDDE[i * ntens + k] : _aqDDSDDE[i * ntens + k + nskip + l]; else // i!=j _jacobian_mult[_qp](i, j, k, l) = k == l ? _aqDDSDDE[(nskip + i + j) * ntens + k] : _aqDDSDDE[(nskip + i + j) * ntens + k + nskip + l]; } } <commit_msg>Fixed column vs row major bug in UMAT interface<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "AbaqusUMATStress.h" #include "Factory.h" #include "MooseMesh.h" #include "RankTwoTensor.h" #include "RankFourTensor.h" #include "libmesh/int_range.h" #include <string.h> #include <algorithm> #define QUOTE(macro) stringifyName(macro) MooseEnum AbaqusUMATStress::decompositionType() { return MooseEnum("TaylorExpansion EigenSolution HughesWinget", "TaylorExpansion"); } registerMooseObject("TensorMechanicsApp", AbaqusUMATStress); InputParameters AbaqusUMATStress::validParams() { InputParameters params = ComputeStressBase::validParams(); params.addClassDescription("Coupling material to use Abaqus UMAT models in MOOSE"); params.addRequiredParam<FileName>( "plugin", "The path to the compiled dynamic library for the plugin you want to use"); params.addRequiredParam<bool>( "use_one_based_indexing", "Parameter to control whether indexing for element and integration points as presented to " "UMAT models is based on 1 (true) or 0 (false). This does not affect internal MOOSE " "numbering. The option to use 0-based numbering is deprecated and will be removed soon."); params.addRequiredParam<std::vector<Real>>( "constant_properties", "Constant mechanical and thermal material properties (PROPS)"); params.addRequiredParam<unsigned int>("num_state_vars", "The number of state variables this UMAT is going to use"); params.addCoupledVar("temperature", 0.0, "Coupled temperature"); params.addCoupledVar("external_fields", "The external fields that can be used in the UMAT subroutine"); params.addParam<std::vector<MaterialPropertyName>>("external_properties", ""); params.addParam<MooseEnum>("decomposition_method", AbaqusUMATStress::decompositionType(), "Method to calcualte the strain kinematics."); return params; } #ifndef METHOD #error "The METHOD preprocessor symbol must be supplied by the build system." #endif AbaqusUMATStress::AbaqusUMATStress(const InputParameters & parameters) : ComputeStressBase(parameters), _plugin(getParam<FileName>("plugin")), _library(_plugin + std::string("-") + QUOTE(METHOD) + ".plugin"), _umat(_library.getFunction<umat_t>("umat_")), _aqNSTATV(getParam<unsigned int>("num_state_vars")), _aqSTATEV(_aqNSTATV), _aqPROPS(getParam<std::vector<Real>>("constant_properties")), _aqNPROPS(_aqPROPS.size()), _stress_old(getMaterialPropertyOld<RankTwoTensor>(_base_name + "stress")), _total_strain_old(getMaterialPropertyOld<RankTwoTensor>(_base_name + "total_strain")), _strain_increment(getOptionalMaterialProperty<RankTwoTensor>(_base_name + "strain_increment")), _jacobian_mult(declareProperty<RankFourTensor>(_base_name + "Jacobian_mult")), _Fbar(getOptionalMaterialProperty<RankTwoTensor>(_base_name + "deformation_gradient")), _Fbar_old(getOptionalMaterialPropertyOld<RankTwoTensor>(_base_name + "deformation_gradient")), _state_var(declareProperty<std::vector<Real>>(_base_name + "state_var")), _state_var_old(getMaterialPropertyOld<std::vector<Real>>(_base_name + "state_var")), _elastic_strain_energy(declareProperty<Real>(_base_name + "elastic_strain_energy")), _plastic_dissipation(declareProperty<Real>(_base_name + "plastic_dissipation")), _creep_dissipation(declareProperty<Real>(_base_name + "creep_dissipation")), _material_timestep(declareProperty<Real>(_base_name + "material_timestep_limit")), _rotation_increment( getOptionalMaterialProperty<RankTwoTensor>(_base_name + "rotation_increment")), _temperature(coupledValue("temperature")), _temperature_old(coupledValueOld("temperature")), _external_fields(coupledValues("external_fields")), _external_fields_old(coupledValuesOld("external_fields")), _number_external_fields(_external_fields.size()), _external_property_names(getParam<std::vector<MaterialPropertyName>>("external_properties")), _number_external_properties(_external_property_names.size()), _external_properties(_number_external_properties), _external_properties_old(_number_external_properties), _use_one_based_indexing(getParam<bool>("use_one_based_indexing")), _decomposition_method(getParam<MooseEnum>("decomposition_method").getEnum<DecompMethod>()) { if (!_use_one_based_indexing) mooseDeprecated( "AbaqusUMATStress has transitioned to 1-based indexing in the element (NOEL) and " "integration point (NPT) numbers to ensure maximum compatibility with legacy UMAT files. " "Please ensure that any new UMAT plugins using these quantities are using the correct " "indexing. 0-based indexing will be deprecated soon."); // get material properties for (std::size_t i = 0; i < _number_external_properties; ++i) { _external_properties[i] = &getMaterialProperty<Real>(_external_property_names[i]); _external_properties_old[i] = &getMaterialPropertyOld<Real>(_external_property_names[i]); } // Read mesh dimension and size UMAT arrays (we always size for full 3D) _aqNTENS = 6; // Size of the stress or strain component array (NDI+NSHR) _aqNSHR = 3; // Number of engineering shear stress components _aqNDI = 3; // Number of direct stress components (always 3) _aqDDSDDT.resize(_aqNTENS); _aqDRPLDE.resize(_aqNTENS); _aqSTRAN.resize(_aqNTENS); _aqDFGRD0.resize(9); _aqDFGRD1.resize(9); _aqDROT.resize(9); _aqSTRESS.resize(_aqNTENS); _aqDDSDDE.resize(_aqNTENS * _aqNTENS); _aqDSTRAN.resize(_aqNTENS); _aqPREDEF.resize(_number_external_fields + _number_external_properties); _aqDPRED.resize(_number_external_fields + _number_external_properties); } void AbaqusUMATStress::initialSetup() { // The _Fbar, _Fbar_old, and _rotation_increment optional properties are only available when an // incremental strain formulation is used. If they are not avaliable we advide the user to // select an incremental formulation. if (!_strain_increment || !_Fbar || !_Fbar_old || !_rotation_increment) mooseError("AbaqusUMATStress '", name(), "': Incremental strain quantities are not available. You likely are using a total " "strain formulation. Specify `incremental = true` in the tensor mechanics action, " "or use ComputeIncrementalSmallStrain in your input file."); } void AbaqusUMATStress::initQpStatefulProperties() { ComputeStressBase::initQpStatefulProperties(); // Initialize state variable vector _state_var[_qp].resize(_aqNSTATV); for (const auto i : make_range(_aqNSTATV)) _state_var[_qp][i] = 0.0; } void AbaqusUMATStress::computeProperties() { // current element "number" _aqNOEL = _current_elem->id() + (_use_one_based_indexing ? 1 : 0); // characteristic element length _aqCELENT = std::pow(_current_elem->volume(), 1.0 / _current_elem->dim()); // For now, total time and step time mean the exact same thing // Value of step time at the beginning of the current increment _aqTIME[0] = _t - _dt; // Value of total time at the beginning of the current increment _aqTIME[1] = _t - _dt; // Time increment _aqDTIME = _dt; // Fill unused characters with spaces (Fortran) std::fill(_aqCMNAME, _aqCMNAME + 80, ' '); std::memcpy(_aqCMNAME, name().c_str(), name().size()); ComputeStressBase::computeProperties(); } void AbaqusUMATStress::computeQpStress() { // C uses row-major, whereas Fortran uses column major // therefore, all unsymmetric matrices must be transposed before passing them to Fortran RankTwoTensor FBar_old_fortran = _Fbar_old[_qp].transpose(); RankTwoTensor FBar_fortran = _Fbar[_qp].transpose(); RankTwoTensor DROT_fortran = _rotation_increment[_qp].transpose(); const Real * myDFGRD0 = &(FBar_old_fortran(0, 0)); const Real * myDFGRD1 = &(FBar_fortran(0, 0)); const Real * myDROT = &(DROT_fortran(0, 0)); // copy because UMAT does not guarantee constness for (const auto i : make_range(9)) { _aqDFGRD0[i] = myDFGRD0[i]; _aqDFGRD1[i] = myDFGRD1[i]; _aqDROT[i] = myDROT[i]; } // Recover "old" state variables for (const auto i : make_range(_aqNSTATV)) _aqSTATEV[i] = _state_var_old[_qp][i]; // Pass through updated stress, total strain, and strain increment arrays static const std::array<Real, 6> strain_factor{{1, 1, 1, 2, 2, 2}}; // Account for difference in vector order convention: yz, xz, xy (MOOSE) vs xy, xz, yz // (commercial software) static const std::array<std::pair<unsigned int, unsigned int>, 6> component{ {{0, 0}, {1, 1}, {2, 2}, {0, 1}, {0, 2}, {1, 2}}}; // rotate old stress if HughesWinget RankTwoTensor stress_old = _stress_old[_qp]; if (_decomposition_method == DecompMethod::HughesWinget) stress_old.rotate(_rotation_increment[_qp]); for (const auto i : make_range(_aqNTENS)) { const auto a = component[i].first; const auto b = component[i].second; _aqSTRESS[i] = stress_old(a, b); _aqSTRAN[i] = _total_strain_old[_qp](a, b) * strain_factor[i]; _aqDSTRAN[i] = _strain_increment[_qp](a, b) * strain_factor[i]; } // current coordinates for (const auto i : make_range(Moose::dim)) _aqCOORDS[i] = _q_point[_qp](i); // zero out Jacobian contribution for (const auto i : make_range(_aqNTENS * _aqNTENS)) _aqDDSDDE[i] = 0.0; // Set PNEWDT initially to a large value _aqPNEWDT = std::numeric_limits<Real>::max(); // Temperature _aqTEMP = _temperature_old[_qp]; // Temperature increment _aqDTEMP = _temperature[_qp] - _temperature_old[_qp]; for (const auto i : make_range(_number_external_fields)) { // External field at this step _aqPREDEF[i] = (*_external_fields_old[i])[_qp]; // External field increments _aqDPRED[i] = (*_external_fields[i])[_qp] - (*_external_fields_old[i])[_qp]; } for (const auto i : make_range(_number_external_properties)) { // External property at this step _aqPREDEF[i + _number_external_fields] = (*_external_properties_old[i])[_qp]; // External property increments _aqDPRED[i + _number_external_fields] = (*_external_properties[i])[_qp] - (*_external_properties_old[i])[_qp]; } // Layer number (not supported) _aqLAYER = -1; // Section point number within the layer (not supported) _aqKSPT = -1; // Increment number _aqKINC = _t_step; _aqKSTEP = 1; // integration point number _aqNPT = _qp + (_use_one_based_indexing ? 1 : 0); // Connection to extern statement _umat(_aqSTRESS.data(), _aqSTATEV.data(), _aqDDSDDE.data(), &_elastic_strain_energy[_qp], &_plastic_dissipation[_qp], &_creep_dissipation[_qp], &_aqRPL, _aqDDSDDT.data(), _aqDRPLDE.data(), &_aqDRPLDT, _aqSTRAN.data(), _aqDSTRAN.data(), _aqTIME.data(), &_aqDTIME, &_aqTEMP, &_aqDTEMP, _aqPREDEF.data(), _aqDPRED.data(), _aqCMNAME, &_aqNDI, &_aqNSHR, &_aqNTENS, &_aqNSTATV, _aqPROPS.data(), &_aqNPROPS, _aqCOORDS.data(), _aqDROT.data(), &_aqPNEWDT, &_aqCELENT, _aqDFGRD0.data(), _aqDFGRD1.data(), &_aqNOEL, &_aqNPT, &_aqLAYER, &_aqKSPT, &_aqKSTEP, &_aqKINC); // Update state variables for (int i = 0; i < _aqNSTATV; ++i) _state_var[_qp][i] = _aqSTATEV[i]; // Here, we apply UMAT convention: Always multiply _dt by PNEWDT to determine the material time // step MOOSE time stepper will choose the most limiting of all material time step increments // provided _material_timestep[_qp] = _aqPNEWDT * _dt; // Get new stress tensor - UMAT should update stress // Account for difference in vector order convention: yz, xz, xy (MOOSE) vs xy, xz, yz // (commercial software) _stress[_qp] = RankTwoTensor( _aqSTRESS[0], _aqSTRESS[1], _aqSTRESS[2], _aqSTRESS[5], _aqSTRESS[4], _aqSTRESS[3]); // Rotate the stress state to the current configuration, unless HughesWinget if (_decomposition_method != DecompMethod::HughesWinget) _stress[_qp].rotate(_rotation_increment[_qp]); // Build Jacobian matrix from UMAT's Voigt non-standard order to fourth order tensor. const unsigned int N = Moose::dim; const unsigned int ntens = N * (N + 1) / 2; const int nskip = N - 1; for (const auto i : make_range(N)) for (const auto j : make_range(N)) for (const auto k : make_range(N)) for (const auto l : make_range(N)) { if (i == j) _jacobian_mult[_qp](i, j, k, l) = k == l ? _aqDDSDDE[i * ntens + k] : _aqDDSDDE[i * ntens + k + nskip + l]; else // i!=j _jacobian_mult[_qp](i, j, k, l) = k == l ? _aqDDSDDE[(nskip + i + j) * ntens + k] : _aqDDSDDE[(nskip + i + j) * ntens + k + nskip + l]; } } <|endoftext|>
<commit_before>#include <itkImageRegionConstIterator.h> #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkFDKConeBeamReconstructionFilter.h" #include "rtkConstantImageSource.h" #include "rtkDisplacedDetectorImageFilter.h" template<class TImage> void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (2.0-ErrorPerPixel)/2.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 0.061) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 0.06." << std::endl; exit( EXIT_FAILURE); } if (PSNR < 24.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 24." << std::endl; exit( EXIT_FAILURE); } } int main(int argc, char* argv[]) { const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; const unsigned int NumberOfProjectionImages = 180; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New(); origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; size[0] = 128; size[1] = 128; size[2] = 128; spacing[0] = 2.; spacing[1] = 2.; spacing[2] = 2.; tomographySource->SetOrigin( origin ); tomographySource->SetSpacing( spacing ); tomographySource->SetSize( size ); tomographySource->SetConstant( 0. ); ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -254.; origin[1] = -254.; origin[2] = -254.; size[0] = 128; size[1] = 128; size[2] = NumberOfProjectionImages; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); // Shepp Logan projections filter typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType; SLPType::Pointer slp=SLPType::New(); slp->SetInput( projectionsSource->GetOutput() ); // Displaced detector weighting typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType; DDFType::Pointer ddf = DDFType::New(); ddf->SetInput( slp->GetOutput() ); // Create a reference object (in this case a 3D phantom reference). typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->SetInput( tomographySource->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() ); // FDK reconstruction filtering typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; FDKCPUType::Pointer feldkamp = FDKCPUType::New(); feldkamp->SetInput( 0, tomographySource->GetOutput() ); feldkamp->SetInput( 1, ddf->GetOutput() ); std::cout << "\n\n****** Case 1: positive offset in geometry ******" << std::endl; typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 120., 0.); slp->Update(); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 2: negative offset in geometry ******" << std::endl; geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, -120., 0.); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 3: no displacement ******" << std::endl; geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); projectionsSource->SetOrigin(origin); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 4: negative offset in origin ******" << std::endl; geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); origin[0] = -400; projectionsSource->SetOrigin(origin); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 5: positive offset in origin ******" << std::endl; origin[0] = -100; projectionsSource->SetOrigin(origin); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; exit(EXIT_SUCCESS); } <commit_msg>Coding style adapted to ITK convention<commit_after>#include <itkImageRegionConstIterator.h> #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkFDKConeBeamReconstructionFilter.h" #include "rtkConstantImageSource.h" #include "rtkDisplacedDetectorImageFilter.h" template<class TImage> void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (2.0-ErrorPerPixel)/2.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 0.061) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 0.06." << std::endl; exit( EXIT_FAILURE); } if (PSNR < 24.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 24." << std::endl; exit( EXIT_FAILURE); } } int main(int argc, char* argv[]) { const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; const unsigned int NumberOfProjectionImages = 180; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New(); origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; size[0] = 128; size[1] = 128; size[2] = 128; spacing[0] = 2.; spacing[1] = 2.; spacing[2] = 2.; tomographySource->SetOrigin( origin ); tomographySource->SetSpacing( spacing ); tomographySource->SetSize( size ); tomographySource->SetConstant( 0. ); ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -254.; origin[1] = -254.; origin[2] = -254.; size[0] = 128; size[1] = 128; size[2] = NumberOfProjectionImages; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); // Shepp Logan projections filter typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType; SLPType::Pointer slp = SLPType::New(); slp->SetInput( projectionsSource->GetOutput() ); // Displaced detector weighting typedef rtk::DisplacedDetectorImageFilter<OutputImageType> DDFType; DDFType::Pointer ddf = DDFType::New(); ddf->SetInput( slp->GetOutput() ); // Create a reference object (in this case a 3D phantom reference). typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->SetInput( tomographySource->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() ); // FDK reconstruction filtering typedef rtk::FDKConeBeamReconstructionFilter<OutputImageType> FDKCPUType; FDKCPUType::Pointer feldkamp = FDKCPUType::New(); feldkamp->SetInput( 0, tomographySource->GetOutput() ); feldkamp->SetInput( 1, ddf->GetOutput() ); std::cout << "\n\n****** Case 1: positive offset in geometry ******" << std::endl; typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 120., 0.); slp->Update(); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 2: negative offset in geometry ******" << std::endl; geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, -120., 0.); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 3: no displacement ******" << std::endl; geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); projectionsSource->SetOrigin(origin); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 4: negative offset in origin ******" << std::endl; geometry = GeometryType::New(); slp->SetGeometry(geometry); ddf->SetGeometry( geometry ); feldkamp->SetGeometry( geometry ); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); origin[0] = -400; projectionsSource->SetOrigin(origin); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\n****** Case 5: positive offset in origin ******" << std::endl; origin[0] = -100; projectionsSource->SetOrigin(origin); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include "Block.h" #include "DataSource.h" #include "FilesystemException.h" #include <cerrno> #include <unistd.h> using std::exception; namespace RT11FS { Block::Block(int sector, int count) : sector(sector) , count(count) , dirty(false) , refcount(0) { data.resize(count * SECTOR_SIZE); } /** * Get a byte from the block. * * Throws std::out_of_range if offset is invalid. * * @param offset is the offset of the byte to retrieve. * @return the value of the byte at `offset'. */ auto Block::getByte(int offset) -> uint8_t { return data.at(offset); } // Extract a word from the block in PDP-11 byte order auto Block::extractWord(int offset) -> uint16_t { return data.at(offset) | (data.at(offset + 1) << 8); } // set a byte auto Block::setByte(int offset, uint8_t value) -> void { data.at(offset) = value; dirty = true; } // set a word auto Block::setWord(int offset, uint16_t value) -> void { data.at(offset) = value & 0377; data.at(offset + 1) = (value >> 8) & 0377; dirty = true; } // Read the contents of the file system image into the block. auto Block::read(DataSource *dataSource) -> void { auto toSeek = sector * SECTOR_SIZE; auto toRead = count * SECTOR_SIZE; // Data source is defined to return an error if the entire read cannot // be satisfied int err = dataSource->read(&data[0], toRead, toSeek); if (err < 0) { throw FilesystemException {err, "could not read block"}; } dirty = false; } auto Block::write(DataSource *dataSource) -> void { auto toSeek = sector * SECTOR_SIZE; auto toWrite = count * SECTOR_SIZE; // Data source is defined to return an error if the entire write cannot // be satisfied int err = dataSource->write(&data[0], toWrite, toSeek); if (err < 0) { throw FilesystemException {err, "could not read block"}; } dirty = false; } // Copy some data into an external buffer. The caller is // responsible for ensuring that all the data can be // provided from this block. auto Block::copyOut(int offset, int bytes, char *dest) -> void { if (offset + bytes > data.size()) { throw FilesystemException {-EIO, "read past end of block"}; } memcpy(dest, &data[offset], bytes); } auto Block::copyIn(int offset, int bytes, const char *src) -> void { if (offset + bytes > data.size()) { throw FilesystemException {-EIO, "write past end of block"}; } memcpy(&data[offset], src, bytes); dirty = true; } // Copy data around within the block. Safe even if the ranges overlap. auto Block::copyWithinBlock(int sourceOffset, int destOffset, int count) -> void { if ( // all parameters must be positive sourceOffset < 0 || destOffset < 0 || count <= 0 || // these check for integer overflow sourceOffset + count <= 0 || destOffset + count <= 0 || // can't run off end of block sourceOffset + count > data.size() || destOffset + count > data.size()) { throw FilesystemException {-EIO, "invalid copy ranges for moving data inside block"}; } ::memmove( &data[destOffset], &data[sourceOffset], count); dirty = true; } /** * Copy data from one block to another * * Violating the bounds of either block will cause -EIO to be thrown * * @param source the block to copy data from. * @param sourceOffset the byte offset to copy from in `source'. * @param destOffset the byte offset to copy to in this block. * @param count the number of bytes to copy. */ auto Block::copyFromOtherBlock(Block *source, int sourceOffset, int destOffset, int count) -> void { if ( // all parameters must be positive sourceOffset < 0 || destOffset < 0 || count <= 0 || // these check for integer overflow sourceOffset + count <= 0 || destOffset + count <= 0 || // can't run off end of block sourceOffset + count > source->data.size() || destOffset + count > data.size()) { throw FilesystemException {-EIO, "invalid copy ranges for moving data between blocks"}; } // It's safe to use memcpy here because two blocks can never overlap ::memcpy( &data[destOffset], &source->data[sourceOffset], count); dirty = true; } /** * Zero fill part of a block * * Violating the bounds of the block will cause -EIO to be thrown * * @param offset the offset to start filling at. * @param count the number of bytes to fill with zeroes. */ auto Block::zeroFill(int offset, int count) -> void { if ( offset < 0 || offset + count <= 0 || offset + count > data.size()) { throw FilesystemException {-EIO, "Invalid range for zero filling blocks"}; } ::memset(&data[offset], 0, count); } // Resize the block to a new number of sectors. If the block is // growing, then fill the new space from the file system image. auto Block::resize(int newCount, DataSource *dataSource) -> void { data.resize(newCount * SECTOR_SIZE); if (newCount > count) { auto toSeek = (sector + count) * SECTOR_SIZE; auto toRead = (newCount - count) * SECTOR_SIZE; auto at = count * SECTOR_SIZE; try { int err = dataSource->read(&data[at], toRead, toSeek); if (err < 0) { throw FilesystemException {err, "could not read block"}; } } catch (exception) { data.resize(count); throw; } } } } <commit_msg>Fix: entire directory not written when changed<commit_after>#include "Block.h" #include "DataSource.h" #include "FilesystemException.h" #include <cerrno> #include <unistd.h> using std::exception; namespace RT11FS { Block::Block(int sector, int count) : sector(sector) , count(count) , dirty(false) , refcount(0) { data.resize(count * SECTOR_SIZE); } /** * Get a byte from the block. * * Throws std::out_of_range if offset is invalid. * * @param offset is the offset of the byte to retrieve. * @return the value of the byte at `offset'. */ auto Block::getByte(int offset) -> uint8_t { return data.at(offset); } // Extract a word from the block in PDP-11 byte order auto Block::extractWord(int offset) -> uint16_t { return data.at(offset) | (data.at(offset + 1) << 8); } // set a byte auto Block::setByte(int offset, uint8_t value) -> void { data.at(offset) = value; dirty = true; } // set a word auto Block::setWord(int offset, uint16_t value) -> void { data.at(offset) = value & 0377; data.at(offset + 1) = (value >> 8) & 0377; dirty = true; } // Read the contents of the file system image into the block. auto Block::read(DataSource *dataSource) -> void { auto toSeek = sector * SECTOR_SIZE; auto toRead = count * SECTOR_SIZE; // Data source is defined to return an error if the entire read cannot // be satisfied int err = dataSource->read(&data[0], toRead, toSeek); if (err < 0) { throw FilesystemException {err, "could not read block"}; } dirty = false; } auto Block::write(DataSource *dataSource) -> void { auto toSeek = sector * SECTOR_SIZE; auto toWrite = count * SECTOR_SIZE; // Data source is defined to return an error if the entire write cannot // be satisfied int err = dataSource->write(&data[0], toWrite, toSeek); if (err < 0) { throw FilesystemException {err, "could not read block"}; } dirty = false; } // Copy some data into an external buffer. The caller is // responsible for ensuring that all the data can be // provided from this block. auto Block::copyOut(int offset, int bytes, char *dest) -> void { if (offset + bytes > data.size()) { throw FilesystemException {-EIO, "read past end of block"}; } memcpy(dest, &data[offset], bytes); } auto Block::copyIn(int offset, int bytes, const char *src) -> void { if (offset + bytes > data.size()) { throw FilesystemException {-EIO, "write past end of block"}; } memcpy(&data[offset], src, bytes); dirty = true; } // Copy data around within the block. Safe even if the ranges overlap. auto Block::copyWithinBlock(int sourceOffset, int destOffset, int count) -> void { if ( // all parameters must be positive sourceOffset < 0 || destOffset < 0 || count <= 0 || // these check for integer overflow sourceOffset + count <= 0 || destOffset + count <= 0 || // can't run off end of block sourceOffset + count > data.size() || destOffset + count > data.size()) { throw FilesystemException {-EIO, "invalid copy ranges for moving data inside block"}; } ::memmove( &data[destOffset], &data[sourceOffset], count); dirty = true; } /** * Copy data from one block to another * * Violating the bounds of either block will cause -EIO to be thrown * * @param source the block to copy data from. * @param sourceOffset the byte offset to copy from in `source'. * @param destOffset the byte offset to copy to in this block. * @param count the number of bytes to copy. */ auto Block::copyFromOtherBlock(Block *source, int sourceOffset, int destOffset, int count) -> void { if ( // all parameters must be positive sourceOffset < 0 || destOffset < 0 || count <= 0 || // these check for integer overflow sourceOffset + count <= 0 || destOffset + count <= 0 || // can't run off end of block sourceOffset + count > source->data.size() || destOffset + count > data.size()) { throw FilesystemException {-EIO, "invalid copy ranges for moving data between blocks"}; } // It's safe to use memcpy here because two blocks can never overlap ::memcpy( &data[destOffset], &source->data[sourceOffset], count); dirty = true; } /** * Zero fill part of a block * * Violating the bounds of the block will cause -EIO to be thrown * * @param offset the offset to start filling at. * @param count the number of bytes to fill with zeroes. */ auto Block::zeroFill(int offset, int count) -> void { if ( offset < 0 || offset + count <= 0 || offset + count > data.size()) { throw FilesystemException {-EIO, "Invalid range for zero filling blocks"}; } ::memset(&data[offset], 0, count); dirty = true; } // Resize the block to a new number of sectors. If the block is // growing, then fill the new space from the file system image. auto Block::resize(int newCount, DataSource *dataSource) -> void { data.resize(newCount * SECTOR_SIZE); if (newCount > count) { auto toSeek = (sector + count) * SECTOR_SIZE; auto toRead = (newCount - count) * SECTOR_SIZE; auto at = count * SECTOR_SIZE; try { int err = dataSource->read(&data[at], toRead, toSeek); if (err < 0) { throw FilesystemException {err, "could not read block"}; } } catch (exception) { data.resize(count); throw; } } count = newCount; } } <|endoftext|>
<commit_before>#include "IdDictionary.hpp" #include <ros/console.h> using namespace std; IdDictionary::IdDictionary() { translated = false; } bool IdDictionary::contains(int n) { mutex.lock(); for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++) { if (*it = n) { mutex.unlock(); return true; } } mutex.unlock(); return false; } void IdDictionary::insert(int n) { if (translated) { ROS_ERROR("insert: Ids already translated!"); } if (contains(n)) { return; } mutex.lock(); ids.push_back(n); mutex.unlock(); } int IdDictionary::size() { return ids.size(); } void IdDictionary::translateIds() { if (translated) { return; } mutex.lock(); translated = true; std::sort(ids.begin(), ids.end()); int id = 0; for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++, id++) { forward[id] = *it; backward[*it] = id; } mutex.unlock(); } bool IdDictionary::isTranslated() { return translated; } int IdDictionary::getForward(int n) { if (!translated) { ROS_ERROR("getForward: Ids not translated!"); } mutex.lock(); if (forward.count(n)) { return forward[n]; } else { ROS_ERROR("getForward: Unknown id %d", n); return -1; } mutex.unlock(); } int IdDictionary::getBackward(int n) { if (!translated) { ROS_ERROR("getBackward: Ids not translated!"); } mutex.lock(); if (backward.count(n)) { return backward[n]; } else { ROS_ERROR("getBackward: Unknown id %d", n); return -1; } mutex.unlock(); }<commit_msg>Fixed: Ignore ids that were already added, even after translation<commit_after>#include "IdDictionary.hpp" #include <ros/console.h> using namespace std; IdDictionary::IdDictionary() { translated = false; } bool IdDictionary::contains(int n) { mutex.lock(); for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++) { if (*it = n) { mutex.unlock(); return true; } } mutex.unlock(); return false; } void IdDictionary::insert(int n) { if (contains(n)) { return; } if (translated) { ROS_ERROR("insert: Ids already translated!"); } mutex.lock(); ids.push_back(n); mutex.unlock(); } int IdDictionary::size() { return ids.size(); } void IdDictionary::translateIds() { if (translated) { return; } mutex.lock(); translated = true; std::sort(ids.begin(), ids.end()); int id = 0; for (vector<int>::iterator it = ids.begin(); it != ids.end(); it++, id++) { forward[id] = *it; backward[*it] = id; } mutex.unlock(); } bool IdDictionary::isTranslated() { return translated; } int IdDictionary::getForward(int n) { if (!translated) { ROS_ERROR("getForward: Ids not translated!"); } mutex.lock(); if (forward.count(n)) { return forward[n]; } else { ROS_ERROR("getForward: Unknown id %d", n); return -1; } mutex.unlock(); } int IdDictionary::getBackward(int n) { if (!translated) { ROS_ERROR("getBackward: Ids not translated!"); } mutex.lock(); if (backward.count(n)) { return backward[n]; } else { ROS_ERROR("getBackward: Unknown id %d", n); return -1; } mutex.unlock(); }<|endoftext|>
<commit_before>#include "config.h" #include <iostream> #include "ed/connectors/geopal_parser.h" #include "utils/timer.h" #include "utils/init.h" #include <fstream> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include "utils/exception.h" #include "ed_persistor.h" namespace po = boost::program_options; namespace pt = boost::posix_time; int main(int argc, char * argv[]) { navitia::init_app(); auto logger = log4cplus::Logger::getInstance("log"); std::string input, date, connection_string; uint32_t coord_system; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Affiche l'aide") ("input,i", po::value<std::string>(&input), "Repertoire d'entrée") ("version,v", "Affiche la version") ("config-file", po::value<std::string>(), "chemin vers le fichier de configuration") ("coord-system,c", po::value<uint32_t>(&coord_system)->default_value(27572), "Système de coordonnée: 27572 pour lambert 2 Etendu") ("connection-string", po::value<std::string>(&connection_string)->required(), "parametres de connexion à la base de données: host=localhost user=navitia dbname=navitia password=navitia"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("version")){ LOG4CPLUS_INFO(logger, argv[0] << " V" << NAVITIA_VERSION << " " << NAVITIA_BUILD_TYPE); return 0; } if(vm.count("config-file")){ std::ifstream stream; stream.open(vm["config-file"].as<std::string>()); if(!stream.is_open()){ throw navitia::exception("loading config file failed"); }else{ po::store(po::parse_config_file(stream, desc), vm); } } if(vm.count("help") || !vm.count("input")) { std::cout << desc << "\n"; return 1; } po::notify(vm); pt::ptime start; start = pt::microsec_clock::local_time(); ed::Georef data(coord_system); ed::connectors::GeopalParser geopal_parser(input); geopal_parser.fill(data); // ed::connectors::FusioParser fusio_parser(input); // fusio_parser.fill(data, date); // read = (pt::microsec_clock::local_time() - start).total_milliseconds(); // start = pt::microsec_clock::local_time(); ed::EdPersistor p(connection_string); p.persist(data); std::cout<<std::endl<<"temps :"<<(pt::microsec_clock::local_time() - start).total_milliseconds()<<std::endl; return 0; } <commit_msg>ed : ajout de la gestion d'exception<commit_after>#include "config.h" #include <iostream> #include "ed/connectors/geopal_parser.h" #include "utils/timer.h" #include "utils/init.h" #include <fstream> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include "utils/exception.h" #include "ed_persistor.h" namespace po = boost::program_options; namespace pt = boost::posix_time; int main(int argc, char * argv[]) { navitia::init_app(); auto logger = log4cplus::Logger::getInstance("log"); std::string input, date, connection_string; uint32_t coord_system; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Affiche l'aide") ("input,i", po::value<std::string>(&input), "Repertoire d'entrée") ("version,v", "Affiche la version") ("config-file", po::value<std::string>(), "chemin vers le fichier de configuration") ("coord-system,c", po::value<uint32_t>(&coord_system)->default_value(27572), "Système de coordonnée: 27572 pour lambert 2 Etendu") ("connection-string", po::value<std::string>(&connection_string)->required(), "parametres de connexion à la base de données: host=localhost user=navitia dbname=navitia password=navitia"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("version")){ LOG4CPLUS_INFO(logger, argv[0] << " V" << NAVITIA_VERSION << " " << NAVITIA_BUILD_TYPE); return 0; } if(vm.count("config-file")){ std::ifstream stream; stream.open(vm["config-file"].as<std::string>()); if(!stream.is_open()){ throw navitia::exception("loading config file failed"); }else{ po::store(po::parse_config_file(stream, desc), vm); } } if(vm.count("help") || !vm.count("input")) { std::cout << desc << "\n"; return 1; } po::notify(vm); pt::ptime start; start = pt::microsec_clock::local_time(); ed::Georef data(coord_system); ed::connectors::GeopalParser geopal_parser(input); try{ geopal_parser.fill(data); }catch(const ed::connectors::GeopalParserException& e){ LOG4CPLUS_FATAL(logger, "Erreur :"+ e.message); return 0; } ed::EdPersistor p(connection_string); p.persist(data); std::cout<<std::endl<<"temps :"<<(pt::microsec_clock::local_time() - start).total_milliseconds()<<std::endl; return 0; } <|endoftext|>
<commit_before>/* * Convert any file descriptor to a pipe by splicing. * * author: Max Kellermann <mk@cm4all.com> */ #ifdef __linux #include "istream_pipe.hxx" #include "istream_internal.hxx" #include "fd_util.h" #include "direct.hxx" #include "pipe_stock.hxx" #include "stock.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Cast.hxx" #include <daemon/log.h> #include <assert.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <unistd.h> struct istream_pipe { struct istream output; struct istream *input; Stock *stock; StockItem *stock_item; int fds[2]; size_t piped; }; static void pipe_close(struct istream_pipe *p) { if (p->stock != nullptr) { if (p->stock_item != nullptr) /* reuse the pipe only if it's empty */ stock_put(*p->stock_item, p->piped > 0); } else { if (p->fds[0] >= 0) { close(p->fds[0]); p->fds[0] = -1; } if (p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } } } static void pipe_abort(struct istream_pipe *p, GError *error) { pipe_close(p); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit_abort(&p->output, error); } static ssize_t pipe_consume(struct istream_pipe *p) { assert(p->fds[0] >= 0); assert(p->piped > 0); assert(p->stock_item != nullptr || p->stock == nullptr); ssize_t nbytes = istream_invoke_direct(&p->output, FdType::FD_PIPE, p->fds[0], p->piped); if (unlikely(nbytes == ISTREAM_RESULT_BLOCKING || nbytes == ISTREAM_RESULT_CLOSED)) /* handler blocks (-2) or pipe was closed (-3) */ return nbytes; if (unlikely(nbytes == ISTREAM_RESULT_ERRNO && errno != EAGAIN)) { GError *error = new_error_errno_msg("read from pipe failed"); pipe_abort(p, error); return ISTREAM_RESULT_CLOSED; } if (nbytes > 0) { assert((size_t)nbytes <= p->piped); p->piped -= (size_t)nbytes; if (p->piped == 0 && p->stock != nullptr) { /* if the pipe was drained, return it to the stock, to make it available to other streams */ stock_put(*p->stock_item, false); p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; } if (p->piped == 0 && p->input == nullptr) { /* p->input has already reported EOF, and we have been waiting for the pipe buffer to become empty */ pipe_close(p); istream_deinit_eof(&p->output); return ISTREAM_RESULT_CLOSED; } } return nbytes; } /* * istream handler * */ static size_t pipe_input_data(const void *data, size_t length, void *ctx) { struct istream_pipe *p = (struct istream_pipe *)ctx; assert(p->output.handler != nullptr); if (p->piped > 0) { ssize_t nbytes = pipe_consume(p); if (nbytes == ISTREAM_RESULT_CLOSED) return 0; if (p->piped > 0 || p->output.handler == nullptr) return 0; } assert(p->piped == 0); return istream_invoke_data(&p->output, data, length); } static bool pipe_create(struct istream_pipe *p) { assert(p->fds[0] < 0); assert(p->fds[1] < 0); if (p->stock != nullptr) { assert(p->stock_item == nullptr); GError *error = nullptr; p->stock_item = stock_get_now(*p->stock, *p->output.pool, nullptr, &error); if (p->stock_item == nullptr) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } pipe_stock_item_get(p->stock_item, p->fds); } else { if (pipe_cloexec_nonblock(p->fds) < 0) { daemon_log(1, "pipe() failed: %s\n", strerror(errno)); return false; } } return true; } static ssize_t pipe_input_direct(FdType type, int fd, size_t max_length, void *ctx) { struct istream_pipe *p = (struct istream_pipe *)ctx; assert(p->output.handler != nullptr); assert(p->output.handler->direct != nullptr); assert(istream_check_direct(&p->output, FdType::FD_PIPE)); if (p->piped > 0) { ssize_t nbytes = pipe_consume(p); if (nbytes <= 0) return nbytes; if (p->piped > 0) /* if the pipe still isn't empty, we can't start reading new input */ return ISTREAM_RESULT_BLOCKING; } if (istream_check_direct(&p->output, type)) /* already supported by handler (maybe already a pipe) - no need for wrapping it into a pipe */ return istream_invoke_direct(&p->output, type, fd, max_length); assert((type & ISTREAM_TO_PIPE) == type); if (p->fds[1] < 0 && !pipe_create(p)) return ISTREAM_RESULT_CLOSED; ssize_t nbytes = splice(fd, nullptr, p->fds[1], nullptr, max_length, SPLICE_F_NONBLOCK | SPLICE_F_MOVE); /* don't check EAGAIN here (and don't return -2). We assume that splicing to the pipe cannot possibly block, since we flushed the pipe; assume that it can only be the source file which is blocking */ if (nbytes <= 0) return nbytes; assert(p->piped == 0); p->piped = (size_t)nbytes; if (pipe_consume(p) == ISTREAM_RESULT_CLOSED) return ISTREAM_RESULT_CLOSED; return nbytes; } static void pipe_input_eof(void *ctx) { struct istream_pipe *p = (struct istream_pipe *)ctx; p->input = nullptr; if (p->stock == nullptr && p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } if (p->piped == 0) { pipe_close(p); istream_deinit_eof(&p->output); } } static void pipe_input_abort(GError *error, void *ctx) { struct istream_pipe *p = (struct istream_pipe *)ctx; pipe_close(p); p->input = nullptr; istream_deinit_abort(&p->output, error); } static const struct istream_handler pipe_input_handler = { .data = pipe_input_data, .direct = pipe_input_direct, .eof = pipe_input_eof, .abort = pipe_input_abort, }; /* * istream implementation * */ static inline struct istream_pipe * istream_to_pipe(struct istream *istream) { return &ContainerCast2(*istream, &istream_pipe::output); } static off_t istream_pipe_available(struct istream *istream, bool partial) { struct istream_pipe *p = istream_to_pipe(istream); if (likely(p->input != nullptr)) { off_t available = istream_available(p->input, partial); if (p->piped > 0) { if (available != -1) available += p->piped; else if (partial) available = p->piped; } return available; } else { assert(p->piped > 0); return p->piped; } } static void istream_pipe_read(struct istream *istream) { struct istream_pipe *p = istream_to_pipe(istream); if (p->piped > 0 && (pipe_consume(p) <= 0 || p->piped > 0)) return; /* at this point, the pipe must be flushed - if the pipe is flushed, this stream is either closed or there must be an input stream */ assert(p->input != nullptr); auto mask = p->output.handler_direct; if (mask & FdType::FD_PIPE) /* if the handler supports the pipe, we offer our services */ mask |= ISTREAM_TO_PIPE; istream_handler_set_direct(p->input, mask); istream_read(p->input); } static int istream_pipe_as_fd(struct istream *istream) { struct istream_pipe *p = istream_to_pipe(istream); if (p->piped > 0) /* need to flush the pipe buffer first */ return -1; int fd = istream_as_fd(p->input); if (fd >= 0) { pipe_close(p); istream_deinit(&p->output); } return fd; } static void istream_pipe_close(struct istream *istream) { struct istream_pipe *p = istream_to_pipe(istream); pipe_close(p); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit(&p->output); } static const struct istream_class istream_pipe = { .available = istream_pipe_available, .read = istream_pipe_read, .as_fd = istream_pipe_as_fd, .close = istream_pipe_close, }; /* * constructor * */ struct istream * istream_pipe_new(struct pool *pool, struct istream *input, Stock *pipe_stock) { assert(input != nullptr); assert(!istream_has_handler(input)); auto *p = NewFromPool<struct istream_pipe>(*pool); istream_init(&p->output, &istream_pipe, pool); p->stock = pipe_stock; p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; p->piped = 0; istream_assign_handler(&p->input, input, &pipe_input_handler, p, 0); return &p->output; } #endif <commit_msg>istream/pipe: rename the struct with CamelCase<commit_after>/* * Convert any file descriptor to a pipe by splicing. * * author: Max Kellermann <mk@cm4all.com> */ #ifdef __linux #include "istream_pipe.hxx" #include "istream_internal.hxx" #include "fd_util.h" #include "direct.hxx" #include "pipe_stock.hxx" #include "stock.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Cast.hxx" #include <daemon/log.h> #include <assert.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <unistd.h> struct PipeIstream { struct istream output; struct istream *input; Stock *stock; StockItem *stock_item; int fds[2]; size_t piped; }; static void pipe_close(PipeIstream *p) { if (p->stock != nullptr) { if (p->stock_item != nullptr) /* reuse the pipe only if it's empty */ stock_put(*p->stock_item, p->piped > 0); } else { if (p->fds[0] >= 0) { close(p->fds[0]); p->fds[0] = -1; } if (p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } } } static void pipe_abort(PipeIstream *p, GError *error) { pipe_close(p); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit_abort(&p->output, error); } static ssize_t pipe_consume(PipeIstream *p) { assert(p->fds[0] >= 0); assert(p->piped > 0); assert(p->stock_item != nullptr || p->stock == nullptr); ssize_t nbytes = istream_invoke_direct(&p->output, FdType::FD_PIPE, p->fds[0], p->piped); if (unlikely(nbytes == ISTREAM_RESULT_BLOCKING || nbytes == ISTREAM_RESULT_CLOSED)) /* handler blocks (-2) or pipe was closed (-3) */ return nbytes; if (unlikely(nbytes == ISTREAM_RESULT_ERRNO && errno != EAGAIN)) { GError *error = new_error_errno_msg("read from pipe failed"); pipe_abort(p, error); return ISTREAM_RESULT_CLOSED; } if (nbytes > 0) { assert((size_t)nbytes <= p->piped); p->piped -= (size_t)nbytes; if (p->piped == 0 && p->stock != nullptr) { /* if the pipe was drained, return it to the stock, to make it available to other streams */ stock_put(*p->stock_item, false); p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; } if (p->piped == 0 && p->input == nullptr) { /* p->input has already reported EOF, and we have been waiting for the pipe buffer to become empty */ pipe_close(p); istream_deinit_eof(&p->output); return ISTREAM_RESULT_CLOSED; } } return nbytes; } /* * istream handler * */ static size_t pipe_input_data(const void *data, size_t length, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; assert(p->output.handler != nullptr); if (p->piped > 0) { ssize_t nbytes = pipe_consume(p); if (nbytes == ISTREAM_RESULT_CLOSED) return 0; if (p->piped > 0 || p->output.handler == nullptr) return 0; } assert(p->piped == 0); return istream_invoke_data(&p->output, data, length); } static bool pipe_create(PipeIstream *p) { assert(p->fds[0] < 0); assert(p->fds[1] < 0); if (p->stock != nullptr) { assert(p->stock_item == nullptr); GError *error = nullptr; p->stock_item = stock_get_now(*p->stock, *p->output.pool, nullptr, &error); if (p->stock_item == nullptr) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } pipe_stock_item_get(p->stock_item, p->fds); } else { if (pipe_cloexec_nonblock(p->fds) < 0) { daemon_log(1, "pipe() failed: %s\n", strerror(errno)); return false; } } return true; } static ssize_t pipe_input_direct(FdType type, int fd, size_t max_length, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; assert(p->output.handler != nullptr); assert(p->output.handler->direct != nullptr); assert(istream_check_direct(&p->output, FdType::FD_PIPE)); if (p->piped > 0) { ssize_t nbytes = pipe_consume(p); if (nbytes <= 0) return nbytes; if (p->piped > 0) /* if the pipe still isn't empty, we can't start reading new input */ return ISTREAM_RESULT_BLOCKING; } if (istream_check_direct(&p->output, type)) /* already supported by handler (maybe already a pipe) - no need for wrapping it into a pipe */ return istream_invoke_direct(&p->output, type, fd, max_length); assert((type & ISTREAM_TO_PIPE) == type); if (p->fds[1] < 0 && !pipe_create(p)) return ISTREAM_RESULT_CLOSED; ssize_t nbytes = splice(fd, nullptr, p->fds[1], nullptr, max_length, SPLICE_F_NONBLOCK | SPLICE_F_MOVE); /* don't check EAGAIN here (and don't return -2). We assume that splicing to the pipe cannot possibly block, since we flushed the pipe; assume that it can only be the source file which is blocking */ if (nbytes <= 0) return nbytes; assert(p->piped == 0); p->piped = (size_t)nbytes; if (pipe_consume(p) == ISTREAM_RESULT_CLOSED) return ISTREAM_RESULT_CLOSED; return nbytes; } static void pipe_input_eof(void *ctx) { PipeIstream *p = (PipeIstream *)ctx; p->input = nullptr; if (p->stock == nullptr && p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } if (p->piped == 0) { pipe_close(p); istream_deinit_eof(&p->output); } } static void pipe_input_abort(GError *error, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; pipe_close(p); p->input = nullptr; istream_deinit_abort(&p->output, error); } static const struct istream_handler pipe_input_handler = { .data = pipe_input_data, .direct = pipe_input_direct, .eof = pipe_input_eof, .abort = pipe_input_abort, }; /* * istream implementation * */ static inline PipeIstream * istream_to_pipe(struct istream *istream) { return &ContainerCast2(*istream, &PipeIstream::output); } static off_t istream_pipe_available(struct istream *istream, bool partial) { PipeIstream *p = istream_to_pipe(istream); if (likely(p->input != nullptr)) { off_t available = istream_available(p->input, partial); if (p->piped > 0) { if (available != -1) available += p->piped; else if (partial) available = p->piped; } return available; } else { assert(p->piped > 0); return p->piped; } } static void istream_pipe_read(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); if (p->piped > 0 && (pipe_consume(p) <= 0 || p->piped > 0)) return; /* at this point, the pipe must be flushed - if the pipe is flushed, this stream is either closed or there must be an input stream */ assert(p->input != nullptr); auto mask = p->output.handler_direct; if (mask & FdType::FD_PIPE) /* if the handler supports the pipe, we offer our services */ mask |= ISTREAM_TO_PIPE; istream_handler_set_direct(p->input, mask); istream_read(p->input); } static int istream_pipe_as_fd(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); if (p->piped > 0) /* need to flush the pipe buffer first */ return -1; int fd = istream_as_fd(p->input); if (fd >= 0) { pipe_close(p); istream_deinit(&p->output); } return fd; } static void istream_pipe_close(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); pipe_close(p); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit(&p->output); } static const struct istream_class istream_pipe = { .available = istream_pipe_available, .read = istream_pipe_read, .as_fd = istream_pipe_as_fd, .close = istream_pipe_close, }; /* * constructor * */ struct istream * istream_pipe_new(struct pool *pool, struct istream *input, Stock *pipe_stock) { assert(input != nullptr); assert(!istream_has_handler(input)); auto *p = NewFromPool<PipeIstream>(*pool); istream_init(&p->output, &istream_pipe, pool); p->stock = pipe_stock; p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; p->piped = 0; istream_assign_handler(&p->input, input, &pipe_input_handler, p, 0); return &p->output; } #endif <|endoftext|>
<commit_before> #include "app/gibbs/gibbs_sampling.h" #include "app/gibbs/single_node_sampler.h" #include "io/pb_parser.h" #include "common.h" #include <unistd.h> #include <fstream> #include "timer.h" void load_fg(dd::FactorGraph * const _p_fg, const dd::CmdParser & cmd, const int & nodeid){ std::cout << "LOADING FACTOR GRAPH ON NODE " << nodeid << std::endl; numa_run_on_node(nodeid); numa_set_localalloc(); _p_fg->load(cmd); } /*! * \brief In this function, the factor graph is located to each NUMA node. * * TODO: in the near future, this allocation should be abstracted * into a higher-level class to avoid writing similar things * for Gibbs, NN, SGD etc. However, this is the task of next pass * of refactoring. */ void dd::GibbsSampling::prepare(){ n_numa_nodes = numa_max_node(); n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_nodes+1); std::vector<std::thread> loaders; for(int i=0;i<=n_numa_nodes;i++){ numa_run_on_node(i); numa_set_localalloc(); dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); } for(int i=0;i<=n_numa_nodes;i++){ dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); loaders.push_back(std::thread(load_fg, &factorgraphs[i], *p_cmd_parser, i)); } for(int i=0;i<=n_numa_nodes;i++){ loaders[i].join(); } } void dd::GibbsSampling::inference(const int & n_epoch){ Timer t_total; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers[i].clear_variabletally(); } for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "INFERENCE EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); for(int i=0;i<nnode;i++){ single_node_samplers[i].sample(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait(); } double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec." ; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec" << std::endl; } double elapsed = t_total.elapsed(); std::cout << "TOTAL INFERENCE TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::learn(const int & n_epoch, const int & n_sample_per_epoch, const double & stepsize, const double & decay){ Timer t_total; double current_stepsize = stepsize; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; int nweight = this->factorgraphs[0].weights.size(); std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } double * ori_weights = new double[nweight]; for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "LEARNING EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); memcpy(ori_weights, &this->factorgraphs[0].infrs->weight_values, sizeof(double)*nweight); for(int i=0;i<nnode;i++){ single_node_samplers[i].p_fg->stepsize = current_stepsize; } for(int i=0;i<nnode;i++){ single_node_samplers[i].sample_sgd(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait_sgd(); } FactorGraph & cfg = this->factorgraphs[0]; for(int i=1;i<=n_numa_nodes;i++){ FactorGraph & cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] += cfg_other.infrs->weight_values[j]; } } for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] /= nnode; cfg.infrs->weight_values[j] *= (1.0/(1.0+0.01*current_stepsize)); } for(int i=1;i<=n_numa_nodes;i++){ FactorGraph &cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ if(cfg.infrs->weights_isfixed[j] == false){ cfg_other.infrs->weight_values[j] = cfg.infrs->weight_values[j]; } } } double lmax = -1000000; double l2=0.0; for(int i=0;i<nweight;i++){ double diff = fabs(ori_weights[i] - cfg.infrs->weight_values[i]); l2 += diff*diff; if(lmax < diff){ lmax = diff; } } lmax = lmax/current_stepsize; double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec."; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec." << ",stepsize=" << current_stepsize << ",lmax=" << lmax << ",l2=" << sqrt(l2)/current_stepsize << std::endl; //std::cout << " " << this->compact_factors[0].fg_mutable->weights[0] << std::endl; current_stepsize = current_stepsize * decay; } double elapsed = t_total.elapsed(); std::cout << "TOTAL LEARNING TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::dump_weights(){ std::cout << "LEARNING SNIPPETS (QUERY WEIGHTS):" << std::endl; FactorGraph const & cfg = this->factorgraphs[0]; int ct = 0; for(size_t i=0;i<cfg.infrs->nweights;i++){ ct ++; std::cout << " " << i << " " << cfg.infrs->weight_values[i] << std::endl; if(ct % 10 == 0){ break; } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::WeightInferenceResult msg; for(size_t i=0;i<cfg.infrs->nweights;i++){ fout_text << i << " " << cfg.infrs->weight_values[i] << std::endl; msg.set_id(i); msg.set_value(cfg.infrs->weight_values[i]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); } void dd::GibbsSampling::dump(){ double * agg_means = new double[factorgraphs[0].variables.size()]; double * agg_nsamples = new double[factorgraphs[0].variables.size()]; for(long i=0;i<factorgraphs[0].variables.size();i++){ agg_means[i] = 0; agg_nsamples[i] = 0; } for(int i=0;i<=n_numa_nodes;i++){ const FactorGraph & cfg = factorgraphs[i]; for(auto & variable : cfg.variables){ agg_means[variable.id] += cfg.infrs->agg_means[variable.id]; agg_nsamples[variable.id] += cfg.infrs->agg_nsamples[variable.id]; } } std::cout << "INFERENCE SNIPPETS (QUERY VARIABLES):" << std::endl; int ct = 0; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == false){ ct ++; std::cout << " " << variable.id << " " << agg_means[variable.id]/agg_nsamples[variable.id] << " @ " << agg_nsamples[variable.id] << std::endl; if(ct % 10 == 0){ break; } } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::VariableInferenceResult msg; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } if(variable.domain_type != DTYPE_BOOLEAN){ std::cout << "ERROR: Only support boolean variables for now!" << std::endl; assert(false); } fout_text << variable.id << " " << (agg_means[variable.id]/agg_nsamples[variable.id]) << std::endl; msg.set_id(variable.id); msg.set_category(1.0); msg.set_expectation(agg_means[variable.id]/agg_nsamples[variable.id]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); std::cout << "INFERENCE CALIBRATION (QUERY BINS):" << std::endl; std::vector<int> abc; for(int i=0;i<=10;i++){ abc.push_back(0); } int bad = 0; for(const auto & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } int bin = (int)(agg_means[variable.id]/agg_nsamples[variable.id]*10); if(bin >= 0 && bin <=10){ abc[bin] ++; }else{ //std::cout << variable.id << " " << variable.agg_mean << " " << variable.n_sample << std::endl; bad ++; } } abc[9] += abc[10]; for(int i=0;i<10;i++){ std::cout << "PROB BIN 0." << i << "~0." << (i+1) << " --> # " << abc[i] << std::endl; } } <commit_msg>parallel load<commit_after> #include "app/gibbs/gibbs_sampling.h" #include "app/gibbs/single_node_sampler.h" #include "io/pb_parser.h" #include "common.h" #include <unistd.h> #include <fstream> #include "timer.h" void load_fg(dd::FactorGraph * const _p_fg, const dd::CmdParser & cmd, const int & nodeid){ std::cout << "LOADING FACTOR GRAPH ON NODE " << nodeid << std::endl; numa_run_on_node(nodeid); numa_set_localalloc(); _p_fg->load(cmd); } /*! * \brief In this function, the factor graph is located to each NUMA node. * * TODO: in the near future, this allocation should be abstracted * into a higher-level class to avoid writing similar things * for Gibbs, NN, SGD etc. However, this is the task of next pass * of refactoring. */ void dd::GibbsSampling::prepare(){ n_numa_nodes = numa_max_node(); n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_nodes+1); std::vector<std::thread> loaders; for(int i=0;i<=n_numa_nodes;i++){ numa_run_on_node(i); numa_set_localalloc(); dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); } for(int i=0;i<=n_numa_nodes;i++){ dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); //loaders.push_back(std::thread(load_fg, &factorgraphs[i], *p_cmd_parser, i)); numa_run_on_node(i); numa_set_localalloc(); load_fg(&factorgraphs[i], *p_cmd_parser, i); } //for(int i=0;i<=n_numa_nodes;i++){ // loaders[i].join(); //} } void dd::GibbsSampling::inference(const int & n_epoch){ Timer t_total; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers[i].clear_variabletally(); } for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "INFERENCE EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); for(int i=0;i<nnode;i++){ single_node_samplers[i].sample(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait(); } double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec." ; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec" << std::endl; } double elapsed = t_total.elapsed(); std::cout << "TOTAL INFERENCE TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::learn(const int & n_epoch, const int & n_sample_per_epoch, const double & stepsize, const double & decay){ Timer t_total; double current_stepsize = stepsize; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; int nweight = this->factorgraphs[0].weights.size(); std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } double * ori_weights = new double[nweight]; for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "LEARNING EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); memcpy(ori_weights, &this->factorgraphs[0].infrs->weight_values, sizeof(double)*nweight); for(int i=0;i<nnode;i++){ single_node_samplers[i].p_fg->stepsize = current_stepsize; } for(int i=0;i<nnode;i++){ single_node_samplers[i].sample_sgd(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait_sgd(); } FactorGraph & cfg = this->factorgraphs[0]; for(int i=1;i<=n_numa_nodes;i++){ FactorGraph & cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] += cfg_other.infrs->weight_values[j]; } } for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] /= nnode; cfg.infrs->weight_values[j] *= (1.0/(1.0+0.01*current_stepsize)); } for(int i=1;i<=n_numa_nodes;i++){ FactorGraph &cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ if(cfg.infrs->weights_isfixed[j] == false){ cfg_other.infrs->weight_values[j] = cfg.infrs->weight_values[j]; } } } double lmax = -1000000; double l2=0.0; for(int i=0;i<nweight;i++){ double diff = fabs(ori_weights[i] - cfg.infrs->weight_values[i]); l2 += diff*diff; if(lmax < diff){ lmax = diff; } } lmax = lmax/current_stepsize; double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec."; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec." << ",stepsize=" << current_stepsize << ",lmax=" << lmax << ",l2=" << sqrt(l2)/current_stepsize << std::endl; //std::cout << " " << this->compact_factors[0].fg_mutable->weights[0] << std::endl; current_stepsize = current_stepsize * decay; } double elapsed = t_total.elapsed(); std::cout << "TOTAL LEARNING TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::dump_weights(){ std::cout << "LEARNING SNIPPETS (QUERY WEIGHTS):" << std::endl; FactorGraph const & cfg = this->factorgraphs[0]; int ct = 0; for(size_t i=0;i<cfg.infrs->nweights;i++){ ct ++; std::cout << " " << i << " " << cfg.infrs->weight_values[i] << std::endl; if(ct % 10 == 0){ break; } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::WeightInferenceResult msg; for(size_t i=0;i<cfg.infrs->nweights;i++){ fout_text << i << " " << cfg.infrs->weight_values[i] << std::endl; msg.set_id(i); msg.set_value(cfg.infrs->weight_values[i]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); } void dd::GibbsSampling::dump(){ double * agg_means = new double[factorgraphs[0].variables.size()]; double * agg_nsamples = new double[factorgraphs[0].variables.size()]; for(long i=0;i<factorgraphs[0].variables.size();i++){ agg_means[i] = 0; agg_nsamples[i] = 0; } for(int i=0;i<=n_numa_nodes;i++){ const FactorGraph & cfg = factorgraphs[i]; for(auto & variable : cfg.variables){ agg_means[variable.id] += cfg.infrs->agg_means[variable.id]; agg_nsamples[variable.id] += cfg.infrs->agg_nsamples[variable.id]; } } std::cout << "INFERENCE SNIPPETS (QUERY VARIABLES):" << std::endl; int ct = 0; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == false){ ct ++; std::cout << " " << variable.id << " " << agg_means[variable.id]/agg_nsamples[variable.id] << " @ " << agg_nsamples[variable.id] << std::endl; if(ct % 10 == 0){ break; } } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::VariableInferenceResult msg; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } if(variable.domain_type != DTYPE_BOOLEAN){ std::cout << "ERROR: Only support boolean variables for now!" << std::endl; assert(false); } fout_text << variable.id << " " << (agg_means[variable.id]/agg_nsamples[variable.id]) << std::endl; msg.set_id(variable.id); msg.set_category(1.0); msg.set_expectation(agg_means[variable.id]/agg_nsamples[variable.id]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); std::cout << "INFERENCE CALIBRATION (QUERY BINS):" << std::endl; std::vector<int> abc; for(int i=0;i<=10;i++){ abc.push_back(0); } int bad = 0; for(const auto & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } int bin = (int)(agg_means[variable.id]/agg_nsamples[variable.id]*10); if(bin >= 0 && bin <=10){ abc[bin] ++; }else{ //std::cout << variable.id << " " << variable.agg_mean << " " << variable.n_sample << std::endl; bad ++; } } abc[9] += abc[10]; for(int i=0;i<10;i++){ std::cout << "PROB BIN 0." << i << "~0." << (i+1) << " --> # " << abc[i] << std::endl; } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief dispatcher thread /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 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 Dr. Frank Celler /// @author Martin Schoenert /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2009-2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "DispatcherThread.h" #include <iostream> #include "Basics/ConditionLocker.h" #include "Basics/Exceptions.h" #include "Basics/logging.h" #include "Dispatcher/Dispatcher.h" #include "Dispatcher/DispatcherQueue.h" #include "Dispatcher/Job.h" #include "Dispatcher/RequeueTask.h" #include "Scheduler/Scheduler.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; // ----------------------------------------------------------------------------- // --SECTION-- class DispatcherThread // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- thread local variables // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief a global, but thread-local place to hold the current dispatcher /// thread. If we are not in a dispatcher thread this is set to nullptr. //////////////////////////////////////////////////////////////////////////////// thread_local DispatcherThread* DispatcherThread::currentDispatcherThread = nullptr; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a dispatcher thread //////////////////////////////////////////////////////////////////////////////// DispatcherThread::DispatcherThread (DispatcherQueue* queue) : Thread("dispat"+ (queue->_id == Dispatcher::STANDARD_QUEUE ? std::string("_std") : std::string("_aql"))), _queue(queue) { allowAsynchronousCancelation(); } // ----------------------------------------------------------------------------- // --SECTION-- Thread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief main loop //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::run () { currentDispatcherThread = this; double worked = 0; double grace = 0.1; // iterate until we are shutting down while (! _queue->_stopping.load(memory_order_relaxed)) { double now = TRI_microtime(); // drain the job queue { Job* job = nullptr; while (_queue->_readyJobs.pop(job)) { if (job != nullptr) { worked = now; handleJob(job); } } // we need to check again if more work has arrived after we have // aquired the lock. The lockfree queue and _nrWaiting are accessed // using "memory_order_seq_cst", this guaranties that we do not // miss a signal. if (worked + grace < now) { ++_queue->_nrWaiting; CONDITION_LOCKER(guard, _queue->_waitLock); if (! _queue->_readyJobs.empty()) { --_queue->_nrWaiting; continue; } // wait at most 100ms _queue->_waitLock.wait(100 * 1000); --_queue->_nrWaiting; // there is a chance, that we created more threads than necessary because // we ignore race conditions for the statistic variables if (_queue->tooManyThreads()) { break; } } else if (worked < now) { uintptr_t n = (uintptr_t) this; usleep((n >> 2) % 100); } } } LOG_TRACE("dispatcher thread has finished"); // this will delete the thread _queue->removeStartedThread(this); } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief indicates that thread is doing a blocking operation //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::block () { _queue->blockThread(); } //////////////////////////////////////////////////////////////////////////////// /// @brief indicates that thread has resumed work //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::unblock () { _queue->unblockThread(); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief do the real work //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::handleJob (Job* job) { // set running job LOG_DEBUG("starting to run job: %s", job->getName().c_str()); // do the work (this might change the job type) Job::status_t status(Job::JOB_FAILED); try { RequestStatisticsAgentSetQueueEnd(job); // set current thread job->setDispatcherThread(this); // and do all the dirty work status = job->work(); } catch (Exception const& ex) { try { job->handleError(ex); } catch (Exception const& ex) { LOG_WARNING("caught error while handling error: %s", ex.what()); } catch (std::exception const& ex) { LOG_WARNING("caught error while handling error: %s", ex.what()); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } catch (std::bad_alloc const& ex) { try { Exception ex2(TRI_ERROR_OUT_OF_MEMORY, string("job failed with bad_alloc: ") + ex.what(), __FILE__, __LINE__); job->handleError(ex2); LOG_WARNING("caught exception in work(): %s", ex2.what()); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } catch (std::exception const& ex) { try { Exception ex2(TRI_ERROR_INTERNAL, string("job failed with error: ") + ex.what(), __FILE__, __LINE__); job->handleError(ex2); LOG_WARNING("caught exception in work(): %s", ex2.what()); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } catch (...) { #ifdef TRI_HAVE_POSIX_THREADS if (_queue->_stopping.load(memory_order_relaxed)) { LOG_WARNING("caught cancellation exception during work"); throw; } #endif try { Exception ex(TRI_ERROR_INTERNAL, "job failed with unknown error", __FILE__, __LINE__); job->handleError(ex); LOG_WARNING("caught unknown exception in work()"); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } // finish jobs try { job->setDispatcherThread(nullptr); if (status.status == Job::JOB_DONE || status.status == Job::JOB_FAILED) { job->cleanup(_queue); } else if (status.status == Job::JOB_REQUEUE) { if (0.0 < status.sleep) { _queue->_scheduler->registerTask( new RequeueTask(_queue->_scheduler, _queue->_dispatcher, status.sleep, job)); } else { _queue->_dispatcher->addJob(job); } } } catch (...) { #ifdef TRI_HAVE_POSIX_THREADS if (_queue->_stopping.load(memory_order_relaxed)) { LOG_WARNING("caught cancellation exception during cleanup"); throw; } #endif LOG_WARNING("caught error while cleaning up!"); } } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>small grace<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief dispatcher thread /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 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 Dr. Frank Celler /// @author Martin Schoenert /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2009-2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "DispatcherThread.h" #include <iostream> #include "Basics/ConditionLocker.h" #include "Basics/Exceptions.h" #include "Basics/logging.h" #include "Dispatcher/Dispatcher.h" #include "Dispatcher/DispatcherQueue.h" #include "Dispatcher/Job.h" #include "Dispatcher/RequeueTask.h" #include "Scheduler/Scheduler.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; // ----------------------------------------------------------------------------- // --SECTION-- class DispatcherThread // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- thread local variables // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief a global, but thread-local place to hold the current dispatcher /// thread. If we are not in a dispatcher thread this is set to nullptr. //////////////////////////////////////////////////////////////////////////////// thread_local DispatcherThread* DispatcherThread::currentDispatcherThread = nullptr; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructs a dispatcher thread //////////////////////////////////////////////////////////////////////////////// DispatcherThread::DispatcherThread (DispatcherQueue* queue) : Thread("dispat"+ (queue->_id == Dispatcher::STANDARD_QUEUE ? std::string("_std") : std::string("_aql"))), _queue(queue) { allowAsynchronousCancelation(); } // ----------------------------------------------------------------------------- // --SECTION-- Thread methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief main loop //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::run () { currentDispatcherThread = this; double worked = 0; double grace = 0.2; // iterate until we are shutting down while (! _queue->_stopping.load(memory_order_relaxed)) { double now = TRI_microtime(); // drain the job queue { Job* job = nullptr; while (_queue->_readyJobs.pop(job)) { if (job != nullptr) { worked = now; handleJob(job); } } // we need to check again if more work has arrived after we have // aquired the lock. The lockfree queue and _nrWaiting are accessed // using "memory_order_seq_cst", this guaranties that we do not // miss a signal. if (worked + grace < now) { ++_queue->_nrWaiting; CONDITION_LOCKER(guard, _queue->_waitLock); if (! _queue->_readyJobs.empty()) { --_queue->_nrWaiting; continue; } // wait at most 100ms _queue->_waitLock.wait(100 * 1000); --_queue->_nrWaiting; // there is a chance, that we created more threads than necessary because // we ignore race conditions for the statistic variables if (_queue->tooManyThreads()) { break; } } else if (worked < now) { uintptr_t n = (uintptr_t) this; usleep(1 + ((n >> 2) % 20)); } } } LOG_TRACE("dispatcher thread has finished"); // this will delete the thread _queue->removeStartedThread(this); } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief indicates that thread is doing a blocking operation //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::block () { _queue->blockThread(); } //////////////////////////////////////////////////////////////////////////////// /// @brief indicates that thread has resumed work //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::unblock () { _queue->unblockThread(); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief do the real work //////////////////////////////////////////////////////////////////////////////// void DispatcherThread::handleJob (Job* job) { // set running job LOG_DEBUG("starting to run job: %s", job->getName().c_str()); // do the work (this might change the job type) Job::status_t status(Job::JOB_FAILED); try { RequestStatisticsAgentSetQueueEnd(job); // set current thread job->setDispatcherThread(this); // and do all the dirty work status = job->work(); } catch (Exception const& ex) { try { job->handleError(ex); } catch (Exception const& ex) { LOG_WARNING("caught error while handling error: %s", ex.what()); } catch (std::exception const& ex) { LOG_WARNING("caught error while handling error: %s", ex.what()); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } catch (std::bad_alloc const& ex) { try { Exception ex2(TRI_ERROR_OUT_OF_MEMORY, string("job failed with bad_alloc: ") + ex.what(), __FILE__, __LINE__); job->handleError(ex2); LOG_WARNING("caught exception in work(): %s", ex2.what()); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } catch (std::exception const& ex) { try { Exception ex2(TRI_ERROR_INTERNAL, string("job failed with error: ") + ex.what(), __FILE__, __LINE__); job->handleError(ex2); LOG_WARNING("caught exception in work(): %s", ex2.what()); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } catch (...) { #ifdef TRI_HAVE_POSIX_THREADS if (_queue->_stopping.load(memory_order_relaxed)) { LOG_WARNING("caught cancellation exception during work"); throw; } #endif try { Exception ex(TRI_ERROR_INTERNAL, "job failed with unknown error", __FILE__, __LINE__); job->handleError(ex); LOG_WARNING("caught unknown exception in work()"); } catch (...) { LOG_WARNING("caught unknown error while handling error!"); } status = Job::status_t(Job::JOB_FAILED); } // finish jobs try { job->setDispatcherThread(nullptr); if (status.status == Job::JOB_DONE || status.status == Job::JOB_FAILED) { job->cleanup(_queue); } else if (status.status == Job::JOB_REQUEUE) { if (0.0 < status.sleep) { _queue->_scheduler->registerTask( new RequeueTask(_queue->_scheduler, _queue->_dispatcher, status.sleep, job)); } else { _queue->_dispatcher->addJob(job); } } } catch (...) { #ifdef TRI_HAVE_POSIX_THREADS if (_queue->_stopping.load(memory_order_relaxed)) { LOG_WARNING("caught cancellation exception during cleanup"); throw; } #endif LOG_WARNING("caught error while cleaning up!"); } } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>/* * This file is part of signon * * Copyright (C) 2009-2011 Nokia Corporation. * * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com> * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "blobiohandler.h" #include <QBuffer> #include <QDebug> #include "SignOn/signonplugincommon.h" #define SIGNON_IPC_BUFFER_PAGE_SIZE 16384 using namespace SignOn; BlobIOHandler::BlobIOHandler(QIODevice *readChannel, QIODevice *writeChannel, QObject *parent): QObject(parent), m_readChannel(readChannel), m_writeChannel(writeChannel), m_readNotifier(0), m_blobSize(-1) { } void BlobIOHandler::setReadChannelSocketNotifier(QSocketNotifier *notifier) { if (notifier == 0) return; m_readNotifier = notifier; } bool BlobIOHandler::sendData(const QVariantMap &map) { if (m_writeChannel == 0) { TRACE() << "NULL write channel."; return false; } QDataStream stream(m_writeChannel); QByteArray ba = variantMapToByteArray(map); stream << ba.size(); QVector<QByteArray> pages = pageByteArray(ba); for (int i = 0; i < pages.count(); ++i) stream << pages[i]; return true; } void BlobIOHandler::setReadNotificationEnabled(bool enabled) { if (enabled) { if (m_readNotifier != 0) { m_readNotifier->setEnabled(true); connect(m_readNotifier, SIGNAL(activated(int)), this, SLOT(readBlob())); } else { connect(m_readChannel, SIGNAL(readyRead()), this, SLOT(readBlob())); } } else { if (m_readNotifier != 0) { disconnect(m_readNotifier, SIGNAL(activated(int)), this, SLOT(readBlob())); m_readNotifier->setEnabled(false); } else { disconnect(m_readChannel, SIGNAL(readyRead()), this, SLOT(readBlob())); } } } void BlobIOHandler::receiveData(int expectedDataSize) { m_blobBuffer.clear(); m_blobSize = expectedDataSize; //Enable read notification only if more than 1 BLOB page is to be received //This does not allow duplicate read attempts if only 1 page is available if (m_blobSize > SIGNON_IPC_BUFFER_PAGE_SIZE) setReadNotificationEnabled(true); readBlob(); } void BlobIOHandler::readBlob() { QDataStream in(m_readChannel); QByteArray fractionBa; in >> fractionBa; m_blobBuffer.append(fractionBa); //Avoid infinite loops if the other party behaves badly if ((fractionBa.size() == 0) && (m_blobBuffer.size() < m_blobSize)) { setReadNotificationEnabled(false); emit error(); return; } if (m_blobBuffer.size() == m_blobSize) { QVariantMap sessionDataMap; sessionDataMap = byteArrayToVariantMap(m_blobBuffer); if (m_blobSize > SIGNON_IPC_BUFFER_PAGE_SIZE) setReadNotificationEnabled(false); emit dataReceived(sessionDataMap); } } QByteArray BlobIOHandler::variantMapToByteArray(const QVariantMap &map) { QBuffer buffer; if (!buffer.open(QIODevice::WriteOnly)) BLAME() << "Buffer opening failed."; QDataStream stream(&buffer); stream << map; buffer.close(); return buffer.data(); } QVariantMap BlobIOHandler::byteArrayToVariantMap(const QByteArray &array) { QByteArray nonConst = array; QBuffer buffer(&nonConst); if (!buffer.open(QIODevice::ReadOnly)) BLAME() << "Buffer opening failed."; buffer.reset(); QDataStream stream(&buffer); QVariantMap map; stream >> map; buffer.close(); return map; } QVector<QByteArray> BlobIOHandler::pageByteArray(const QByteArray &array) { QVector<QByteArray> dataPages; QByteArray ba = array; QBuffer pagingBuffer(&ba); if (!pagingBuffer.open(QIODevice::ReadOnly)) BLAME() << "Error while paging BLOB. Buffer opening failed."; while (!pagingBuffer.atEnd()) { QByteArray page = pagingBuffer.read(SIGNON_IPC_BUFFER_PAGE_SIZE); dataPages.append(page); } pagingBuffer.close(); return dataPages; } <commit_msg>signond: Don't send QDBusArguments to plugins<commit_after>/* * This file is part of signon * * Copyright (C) 2009-2011 Nokia Corporation. * * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com> * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "blobiohandler.h" #include <QBuffer> #include <QDebug> #include "SignOn/signonplugincommon.h" #define SIGNON_IPC_BUFFER_PAGE_SIZE 16384 using namespace SignOn; BlobIOHandler::BlobIOHandler(QIODevice *readChannel, QIODevice *writeChannel, QObject *parent): QObject(parent), m_readChannel(readChannel), m_writeChannel(writeChannel), m_readNotifier(0), m_blobSize(-1) { } void BlobIOHandler::setReadChannelSocketNotifier(QSocketNotifier *notifier) { if (notifier == 0) return; m_readNotifier = notifier; } bool BlobIOHandler::sendData(const QVariantMap &map) { if (m_writeChannel == 0) { TRACE() << "NULL write channel."; return false; } QDataStream stream(m_writeChannel); QByteArray ba = variantMapToByteArray(map); stream << ba.size(); QVector<QByteArray> pages = pageByteArray(ba); for (int i = 0; i < pages.count(); ++i) stream << pages[i]; return true; } void BlobIOHandler::setReadNotificationEnabled(bool enabled) { if (enabled) { if (m_readNotifier != 0) { m_readNotifier->setEnabled(true); connect(m_readNotifier, SIGNAL(activated(int)), this, SLOT(readBlob())); } else { connect(m_readChannel, SIGNAL(readyRead()), this, SLOT(readBlob())); } } else { if (m_readNotifier != 0) { disconnect(m_readNotifier, SIGNAL(activated(int)), this, SLOT(readBlob())); m_readNotifier->setEnabled(false); } else { disconnect(m_readChannel, SIGNAL(readyRead()), this, SLOT(readBlob())); } } } void BlobIOHandler::receiveData(int expectedDataSize) { m_blobBuffer.clear(); m_blobSize = expectedDataSize; //Enable read notification only if more than 1 BLOB page is to be received //This does not allow duplicate read attempts if only 1 page is available if (m_blobSize > SIGNON_IPC_BUFFER_PAGE_SIZE) setReadNotificationEnabled(true); readBlob(); } void BlobIOHandler::readBlob() { QDataStream in(m_readChannel); QByteArray fractionBa; in >> fractionBa; m_blobBuffer.append(fractionBa); //Avoid infinite loops if the other party behaves badly if ((fractionBa.size() == 0) && (m_blobBuffer.size() < m_blobSize)) { setReadNotificationEnabled(false); emit error(); return; } if (m_blobBuffer.size() == m_blobSize) { QVariantMap sessionDataMap; sessionDataMap = byteArrayToVariantMap(m_blobBuffer); if (m_blobSize > SIGNON_IPC_BUFFER_PAGE_SIZE) setReadNotificationEnabled(false); emit dataReceived(sessionDataMap); } } static QVariantMap filterOutComplexTypes(const QVariantMap &map) { QVariantMap filteredMap; QVariantMap::const_iterator i; for (i = map.constBegin(); i != map.constEnd(); i++) { /* QDBusArgument are complex types; there is no QDataStream * serialization for them, so keeping them in the map would make the * serialization fail for the whole map. * Therefore, skip them. */ if (qstrcmp(i.value().typeName(), "QDBusArgument") == 0) { BLAME() << "Found QDBusArgument in map; skipping."; continue; } filteredMap.insert(i.key(), i.value()); } return filteredMap; } QByteArray BlobIOHandler::variantMapToByteArray(const QVariantMap &map) { QBuffer buffer; if (!buffer.open(QIODevice::WriteOnly)) BLAME() << "Buffer opening failed."; QDataStream stream(&buffer); stream << filterOutComplexTypes(map); buffer.close(); return buffer.data(); } QVariantMap BlobIOHandler::byteArrayToVariantMap(const QByteArray &array) { QByteArray nonConst = array; QBuffer buffer(&nonConst); if (!buffer.open(QIODevice::ReadOnly)) BLAME() << "Buffer opening failed."; buffer.reset(); QDataStream stream(&buffer); QVariantMap map; stream >> map; buffer.close(); return map; } QVector<QByteArray> BlobIOHandler::pageByteArray(const QByteArray &array) { QVector<QByteArray> dataPages; QByteArray ba = array; QBuffer pagingBuffer(&ba); if (!pagingBuffer.open(QIODevice::ReadOnly)) BLAME() << "Error while paging BLOB. Buffer opening failed."; while (!pagingBuffer.atEnd()) { QByteArray page = pagingBuffer.read(SIGNON_IPC_BUFFER_PAGE_SIZE); dataPages.append(page); } pagingBuffer.close(); return dataPages; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_TOOLS_HH #define DUNE_STUFF_TEST_TOOLS_HH #include "config.h" #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/float_cmp.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/fvector.hh> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/fmatrix.hh> # include <dune/common/tuples.hh> # include <dune/common/tupleutility.hh> # include <dune/common/parallel/mpihelper.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/logging.hh> #if HAVE_DUNE_FEM # include <dune/stuff/common/disable_warnings.hh> # include <dune/fem/misc/mpimanager.hh> # include <dune/stuff/common/reenable_warnings.hh> #endif #include <dune/stuff/common/disable_warnings.hh> # include <gtest.h> #include <dune/stuff/common/reenable_warnings.hh> #include <random> #include <fstream> #include <sys/time.h> #include <dune/stuff/fem/namespace.hh> template < template <class> class Test > struct TestRunner { struct Visitor { template <class T> void visit(const T&) { Test<T>().run(); } }; template < class Tuple > static void run() { Tuple t; Dune::ForEachValue<Tuple> fe(t); Visitor v; fe.apply(v); } }; template < int i > struct Int { static const int value = i; }; //! where sleep only counts toward wall time, this wastes actual cpu time void busywait(const int ms) { // "round" up to next full 10 ms to align with native timer res const int milliseconds = (ms/10)*10 + 10; timeval start, end; gettimeofday(&start, NULL); do { gettimeofday(&end, NULL); } while( ((end.tv_sec - start.tv_sec )*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds * 1000 ); } typedef Dune::tuple<double, float, //Dune::bigunsignedint, int, unsigned int, unsigned long, long long, char> BasicTypes; void test_init(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); DSC_CONFIG.readOptions(argc, argv); #if HAVE_DUNE_FEM Dune::Fem::MPIManager::initialize(argc, argv); #else Dune::MPIHelper::instance(argc, argv); #endif DSC::Logger().create(DSC::LOG_CONSOLE | DSC::LOG_ERROR); } #endif // DUNE_STUFF_TEST_TOOLS_HH <commit_msg>[test] added errors_are_not_as_expected exception<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_TOOLS_HH #define DUNE_STUFF_TEST_TOOLS_HH #include "config.h" #include <random> #include <fstream> #include <sys/time.h> #include <dune/stuff/common/disable_warnings.hh> # include <gtest.h> # include <dune/common/float_cmp.hh> # include <dune/common/fvector.hh> # include <dune/common/fmatrix.hh> # include <dune/common/tuples.hh> # include <dune/common/tupleutility.hh> # include <dune/common/parallel/mpihelper.hh> # if HAVE_DUNE_FEM # include <dune/fem/misc/mpimanager.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/fem/namespace.hh> class errors_are_not_as_expected : public Dune::Exception {}; template < template <class> class Test > struct TestRunner { struct Visitor { template <class T> void visit(const T&) { Test<T>().run(); } }; template < class Tuple > static void run() { Tuple t; Dune::ForEachValue<Tuple> fe(t); Visitor v; fe.apply(v); } }; template < int i > struct Int { static const int value = i; }; //! where sleep only counts toward wall time, this wastes actual cpu time void busywait(const int ms) { // "round" up to next full 10 ms to align with native timer res const int milliseconds = (ms/10)*10 + 10; timeval start, end; gettimeofday(&start, NULL); do { gettimeofday(&end, NULL); } while( ((end.tv_sec - start.tv_sec )*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds * 1000 ); } typedef Dune::tuple<double, float, //Dune::bigunsignedint, int, unsigned int, unsigned long, long long, char> BasicTypes; void test_init(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); DSC_CONFIG.readOptions(argc, argv); #if HAVE_DUNE_FEM Dune::Fem::MPIManager::initialize(argc, argv); #else Dune::MPIHelper::instance(argc, argv); #endif DSC::Logger().create(DSC::LOG_CONSOLE | DSC::LOG_ERROR); } #endif // DUNE_STUFF_TEST_TOOLS_HH <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE "test_serialize_file" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml.hpp> #include <iostream> #include <fstream> BOOST_AUTO_TEST_CASE(test_example) { const auto data = toml::parse("toml/tests/example.toml"); { std::ofstream ofs("tmp1.toml"); ofs << data; } auto serialized = toml::parse("tmp1.toml"); { auto& owner = toml::get<toml::table>(serialized.at("owner")); auto& bio = toml::get<std::string>(owner.at("bio")); const auto CR = std::find(bio.begin(), bio.end(), '\r'); if(CR != bio.end()) { bio.erase(CR); } } BOOST_CHECK(data == serialized); } BOOST_AUTO_TEST_CASE(test_fruit) { const auto data = toml::parse("toml/tests/fruit.toml"); { std::ofstream ofs("tmp2.toml"); ofs << data; } const auto serialized = toml::parse("tmp2.toml"); BOOST_CHECK(data == serialized); } BOOST_AUTO_TEST_CASE(test_hard_example) { const auto data = toml::parse("toml/tests/hard_example.toml"); { std::ofstream ofs("tmp3.toml"); ofs << data; } const auto serialized = toml::parse("tmp3.toml"); BOOST_CHECK(data == serialized); } <commit_msg>test: set width in test_serialize<commit_after>#define BOOST_TEST_MODULE "test_serialize_file" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml.hpp> #include <iostream> #include <fstream> BOOST_AUTO_TEST_CASE(test_example) { const auto data = toml::parse("toml/tests/example.toml"); { std::ofstream ofs("tmp1.toml"); ofs << std::setw(80) << data; } auto serialized = toml::parse("tmp1.toml"); { auto& owner = toml::get<toml::table>(serialized.at("owner")); auto& bio = toml::get<std::string>(owner.at("bio")); const auto CR = std::find(bio.begin(), bio.end(), '\r'); if(CR != bio.end()) { bio.erase(CR); } } BOOST_CHECK(data == serialized); } BOOST_AUTO_TEST_CASE(test_fruit) { const auto data = toml::parse("toml/tests/fruit.toml"); { std::ofstream ofs("tmp2.toml"); ofs << std::setw(80) << data; } const auto serialized = toml::parse("tmp2.toml"); BOOST_CHECK(data == serialized); } BOOST_AUTO_TEST_CASE(test_hard_example) { const auto data = toml::parse("toml/tests/hard_example.toml"); { std::ofstream ofs("tmp3.toml"); ofs << std::setw(80) << data; } const auto serialized = toml::parse("tmp3.toml"); BOOST_CHECK(data == serialized); } <|endoftext|>
<commit_before>/** * This is code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * * (c) Daniel Lemire, http://lemire.me/en/ */ #include <vector> #include "maropuparser.h" #include "util.h" #include "entropy.h" #include "deltaio.h" void message(const char * prog) { cerr << " usage : " << prog << " scheme maropubinaryfile " << endl; cerr << "By default, is assumes that the original data is made of " "sorted distinct integers, to process the more general case," "add the -notdgaps flag." << endl; cerr << "The -nodelta flag disables delta coding." << endl; cerr << "The -minlength ignores all arrays smaller than a threshold." << endl; } int main(int argc, char **argv) { uint32_t MAXCOUNTER = 1U << 31; if (argc < 4) { message(argv[0]); return -1; } int mode = DeltaIO::DeltaDGapMode; uint32_t MINLENGTH = 2; int argindex = 1; while (true) { if (strcmp(argv[argindex], "-minlength") == 0) { ++argindex; MINLENGTH = atoi(argv[argindex++]); } else if (strcmp(argv[argindex], "-nodelta") == 0) { mode = DeltaIO::NoDeltaMode; ++argindex; } else if (strcmp(argv[argindex], "-notdgaps") == 0) { mode = DeltaIO::DeltaMode; ++argindex; } else break; } cout <<"# computing entropy" <<endl; string filename = argv[argindex++]; if (argindex < argc) MAXCOUNTER = atoi(argv[argindex++]); cout << "# parsing " << filename << endl; MaropuGapReader reader(filename); vector<uint32_t, cacheallocator> rawdata; reader.open(); size_t counter = 0; size_t integers = 0; EntropyRecorder er; while (reader.loadIntegers(rawdata)) { if (rawdata.size() < MINLENGTH) continue; DeltaIO::inplacedeltas(rawdata,mode); er.eat(&rawdata[0],rawdata.size()); ++counter; integers += rawdata.size(); if (counter >= MAXCOUNTER) { cout << "#breaking early" << endl; break; } } reader.close(); cout << "# integers = " << integers << endl; cout << "# arrays = " << counter << endl; cout << "# next line is shannon entropy and data bits" << endl; cout << er.computeShannon() << "\t" << er.computeDataBits() <<endl; } <commit_msg>Minor typo<commit_after>/** * This is code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * * (c) Daniel Lemire, http://lemire.me/en/ */ #include <vector> #include "maropuparser.h" #include "util.h" #include "entropy.h" #include "deltaio.h" void message(const char * prog) { cerr << " usage : " << prog << " maropubinaryfile " << endl; cerr << "By default, is assumes that the original data is made of " "sorted distinct integers, to process the more general case," "add the -notdgaps flag." << endl; cerr << "The -nodelta flag disables delta coding." << endl; cerr << "The -minlength ignores all arrays smaller than a threshold." << endl; } int main(int argc, char **argv) { uint32_t MAXCOUNTER = 1U << 31; if (argc < 2) { message(argv[0]); return -1; } int mode = DeltaIO::DeltaDGapMode; uint32_t MINLENGTH = 2; int argindex = 1; while (true) { if (strcmp(argv[argindex], "-minlength") == 0) { ++argindex; MINLENGTH = atoi(argv[argindex++]); } else if (strcmp(argv[argindex], "-nodelta") == 0) { mode = DeltaIO::NoDeltaMode; ++argindex; } else if (strcmp(argv[argindex], "-notdgaps") == 0) { mode = DeltaIO::DeltaMode; ++argindex; } else break; } cout <<"# computing entropy" <<endl; string filename = argv[argindex++]; if (argindex < argc) MAXCOUNTER = atoi(argv[argindex++]); cout << "# parsing " << filename << endl; MaropuGapReader reader(filename); vector<uint32_t, cacheallocator> rawdata; reader.open(); size_t counter = 0; size_t integers = 0; EntropyRecorder er; while (reader.loadIntegers(rawdata)) { if (rawdata.size() < MINLENGTH) continue; DeltaIO::inplacedeltas(rawdata,mode); er.eat(&rawdata[0],rawdata.size()); ++counter; integers += rawdata.size(); if (counter >= MAXCOUNTER) { cout << "#breaking early" << endl; break; } } reader.close(); cout << "# integers = " << integers << endl; cout << "# arrays = " << counter << endl; cout << "# next line is shannon entropy and data bits" << endl; cout << er.computeShannon() << "\t" << er.computeDataBits() <<endl; } <|endoftext|>
<commit_before>#include <algorithm> #include <map> #include <string> #include "Prefetch.h" #include "IRMutator.h" #include "Bounds.h" #include "Scope.h" #include "Util.h" namespace Halide { namespace Internal { using std::map; using std::string; using std::vector; namespace { // We need to be able to make loads from a buffer that refer to the // same original image/param/etc. This visitor finds a load to the // buffer we want to load from, and generates a similar load, but with // different args. class MakeSimilarLoad : public IRVisitor { public: const std::string &buf_name; const std::vector<Expr> &args; Expr load; MakeSimilarLoad(std::string name, const std::vector<Expr> &args) : buf_name(name), args(args) {} private: using IRVisitor::visit; void visit(const Call *op) { if (op->name == buf_name) { load = Call::make(op->type, op->name, args, op->call_type, op->func, op->value_index, op->image, op->param); } else { IRVisitor::visit(op); } } }; Expr make_similar_load(Stmt s, const std::string &name, const std::vector<Expr> &args) { MakeSimilarLoad v(name, args); s.accept(&v); return v.load; } // Build a Box representing the bounds of a buffer. Box buffer_bounds(const string &buf_name, int dims) { Box bounds; for (int i = 0; i < dims; i++) { string dim_name = std::to_string(i); Expr buf_min_i = Variable::make(Int(32), buf_name + ".min." + dim_name); Expr buf_extent_i = Variable::make(Int(32), buf_name + ".extent." + dim_name); Expr buf_max_i = buf_min_i + buf_extent_i - 1; bounds.push_back(Interval(buf_min_i, buf_max_i)); } return bounds; } class InjectPrefetch : public IRMutator { public: InjectPrefetch(const map<string, Function> &e) : env(e) { } private: const map<string, Function> &env; const vector<Prefetch> *prefetches = nullptr; Scope<Interval> bounds; private: using IRMutator::visit; void visit(const Let *op) { Interval in = bounds_of_expr_in_scope(op->value, bounds); bounds.push(op->name, in); IRMutator::visit(op); bounds.pop(op->name); } void visit(const LetStmt *op) { Interval in = bounds_of_expr_in_scope(op->value, bounds); bounds.push(op->name, in); IRMutator::visit(op); bounds.pop(op->name); } void visit(const ProducerConsumer *op) { const vector<Prefetch> *old_prefetches = prefetches; map<string, Function>::const_iterator iter = env.find(op->name); internal_assert(iter != env.end()) << "function not in environment.\n"; prefetches = &iter->second.schedule().prefetches(); IRMutator::visit(op); prefetches = old_prefetches; } Stmt add_prefetch(const string &buf_name, const Box &box, Stmt body) { // Construct the bounds to be prefetched. vector<Expr> prefetch_min; vector<Expr> prefetch_extent; for (size_t i = 0; i < box.size(); i++) { prefetch_min.push_back(box[i].min); prefetch_extent.push_back(box[i].max - box[i].min + 1); } // Construct an array of index expressions to construct // address_of calls with. The first 2 dimensions are handled // by (up to) 2D prefetches, the rest we will generate loops // to define. vector<string> index_names(box.size()); vector<Expr> indices(box.size()); for (size_t i = 0; i < box.size(); i++) { index_names[i] = "prefetch_" + buf_name + "." + std::to_string(i); indices[i] = i < 2 ? prefetch_min[i] : Variable::make(Int(32), index_names[i]); } // Make a load at the index and get the address. Expr prefetch_load = make_similar_load(body, buf_name, indices); internal_assert(prefetch_load.defined()); Type type = prefetch_load.type(); Expr prefetch_addr = Call::make(Handle(), Call::address_of, {prefetch_load}, Call::Intrinsic); Stmt prefetch; Expr stride_0 = Variable::make(Int(32), buf_name + ".stride.0"); // TODO: This is only correct if stride_0 is 1. We need to assert that this is true. Expr extent_0_bytes = prefetch_extent[0] * type.bytes(); if (box.size() == 1) { // The prefetch is only 1 dimensional, just emit a flat prefetch. prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch, {prefetch_addr, extent_0_bytes}, Call::PureIntrinsic)); } else { // Make a 2D prefetch. Expr stride_1 = Variable::make(Int(32), buf_name + ".stride.1"); Expr stride_1_bytes = stride_1 * type.bytes(); prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_2d, {prefetch_addr, extent_0_bytes, prefetch_extent[1], stride_1_bytes}, Call::PureIntrinsic)); // Make loops for the rest of the dimensions (possibly zero). for (size_t i = 2; i < box.size(); i++) { prefetch = For::make(index_names[i], prefetch_min[i], prefetch_extent[i], ForType::Serial, DeviceAPI::None, prefetch); } } // We should only prefetch buffers that are used. if (box.maybe_unused()) { prefetch = IfThenElse::make(box.used, prefetch); } return Block::make({prefetch, body}); } void visit(const For *op) { // Add loop variable to interval scope for any inner loop prefetch Expr loop_var = Variable::make(Int(32), op->name); bounds.push(op->name, Interval(loop_var, loop_var)); Stmt body = mutate(op->body); bounds.pop(op->name); if (prefetches) { for (const Prefetch &p : *prefetches) { if (!ends_with(op->name, "." + p.var)) { continue; } // Add loop variable + prefetch offset to interval scope for box computation Expr fetch_at = loop_var + p.offset; bounds.push(op->name, Interval(fetch_at, fetch_at)); map<string, Box> boxes_read = boxes_required(body, bounds); bounds.pop(op->name); // Don't prefetch buffers that are written to. We assume that these already // have good locality. // TODO: This is not a good assumption. It would be better to have the // prefetch directive specify the buffer that we want to prefetch, instead // of trying to figure out which buffers should be prefetched. This would also // mean that we don't need the "make_similar_load" hack, because we can make // calls the standard way (using the ImageParam/Function object referenced in // the prefetch). map<string, Box> boxes_written = boxes_provided(body, bounds); for (const auto &b : boxes_written) { auto it = boxes_read.find(b.first); if (it != boxes_read.end()) { debug(2) << "Not prefetching buffer " << it->first << " also written in loop " << op->name << "\n"; boxes_read.erase(it); } } // TODO: Only prefetch the newly accessed data from the previous iteration. // This should use boxes_touched (instead of boxes_required) so we exclude memory // either read or written. for (const auto &b : boxes_read) { const std::string &buf_name = b.first; // Only prefetch the region that is in bounds. Box bounds = buffer_bounds(buf_name, b.second.size()); Box prefetch_box = box_intersection(b.second, bounds); body = add_prefetch(buf_name, prefetch_box, body); } } } if (!body.same_as(op->body)) { stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body); } else { stmt = op; } } }; } // namespace Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env) { return InjectPrefetch(env).mutate(s); } } } <commit_msg>Fix reference to temporary.<commit_after>#include <algorithm> #include <map> #include <string> #include "Prefetch.h" #include "IRMutator.h" #include "Bounds.h" #include "Scope.h" #include "Util.h" namespace Halide { namespace Internal { using std::map; using std::string; using std::vector; namespace { // We need to be able to make loads from a buffer that refer to the // same original image/param/etc. This visitor finds a load to the // buffer we want to load from, and generates a similar load, but with // different args. class MakeSimilarLoad : public IRVisitor { public: const std::string &buf_name; const std::vector<Expr> &args; Expr load; MakeSimilarLoad(const std::string &name, const std::vector<Expr> &args) : buf_name(name), args(args) {} private: using IRVisitor::visit; void visit(const Call *op) { if (op->name == buf_name) { load = Call::make(op->type, op->name, args, op->call_type, op->func, op->value_index, op->image, op->param); } else { IRVisitor::visit(op); } } }; Expr make_similar_load(Stmt s, const std::string &name, const std::vector<Expr> &args) { MakeSimilarLoad v(name, args); s.accept(&v); return v.load; } // Build a Box representing the bounds of a buffer. Box buffer_bounds(const string &buf_name, int dims) { Box bounds; for (int i = 0; i < dims; i++) { string dim_name = std::to_string(i); Expr buf_min_i = Variable::make(Int(32), buf_name + ".min." + dim_name); Expr buf_extent_i = Variable::make(Int(32), buf_name + ".extent." + dim_name); Expr buf_max_i = buf_min_i + buf_extent_i - 1; bounds.push_back(Interval(buf_min_i, buf_max_i)); } return bounds; } class InjectPrefetch : public IRMutator { public: InjectPrefetch(const map<string, Function> &e) : env(e) { } private: const map<string, Function> &env; const vector<Prefetch> *prefetches = nullptr; Scope<Interval> bounds; private: using IRMutator::visit; void visit(const Let *op) { Interval in = bounds_of_expr_in_scope(op->value, bounds); bounds.push(op->name, in); IRMutator::visit(op); bounds.pop(op->name); } void visit(const LetStmt *op) { Interval in = bounds_of_expr_in_scope(op->value, bounds); bounds.push(op->name, in); IRMutator::visit(op); bounds.pop(op->name); } void visit(const ProducerConsumer *op) { const vector<Prefetch> *old_prefetches = prefetches; map<string, Function>::const_iterator iter = env.find(op->name); internal_assert(iter != env.end()) << "function not in environment.\n"; prefetches = &iter->second.schedule().prefetches(); IRMutator::visit(op); prefetches = old_prefetches; } Stmt add_prefetch(const string &buf_name, const Box &box, Stmt body) { // Construct the bounds to be prefetched. vector<Expr> prefetch_min; vector<Expr> prefetch_extent; for (size_t i = 0; i < box.size(); i++) { prefetch_min.push_back(box[i].min); prefetch_extent.push_back(box[i].max - box[i].min + 1); } // Construct an array of index expressions to construct // address_of calls with. The first 2 dimensions are handled // by (up to) 2D prefetches, the rest we will generate loops // to define. vector<string> index_names(box.size()); vector<Expr> indices(box.size()); for (size_t i = 0; i < box.size(); i++) { index_names[i] = "prefetch_" + buf_name + "." + std::to_string(i); indices[i] = i < 2 ? prefetch_min[i] : Variable::make(Int(32), index_names[i]); } // Make a load at the index and get the address. Expr prefetch_load = make_similar_load(body, buf_name, indices); internal_assert(prefetch_load.defined()); Type type = prefetch_load.type(); Expr prefetch_addr = Call::make(Handle(), Call::address_of, {prefetch_load}, Call::Intrinsic); Stmt prefetch; Expr stride_0 = Variable::make(Int(32), buf_name + ".stride.0"); // TODO: This is only correct if stride_0 is 1. We need to assert that this is true. Expr extent_0_bytes = prefetch_extent[0] * type.bytes(); if (box.size() == 1) { // The prefetch is only 1 dimensional, just emit a flat prefetch. prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch, {prefetch_addr, extent_0_bytes}, Call::PureIntrinsic)); } else { // Make a 2D prefetch. Expr stride_1 = Variable::make(Int(32), buf_name + ".stride.1"); Expr stride_1_bytes = stride_1 * type.bytes(); prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_2d, {prefetch_addr, extent_0_bytes, prefetch_extent[1], stride_1_bytes}, Call::PureIntrinsic)); // Make loops for the rest of the dimensions (possibly zero). for (size_t i = 2; i < box.size(); i++) { prefetch = For::make(index_names[i], prefetch_min[i], prefetch_extent[i], ForType::Serial, DeviceAPI::None, prefetch); } } // We should only prefetch buffers that are used. if (box.maybe_unused()) { prefetch = IfThenElse::make(box.used, prefetch); } return Block::make({prefetch, body}); } void visit(const For *op) { // Add loop variable to interval scope for any inner loop prefetch Expr loop_var = Variable::make(Int(32), op->name); bounds.push(op->name, Interval(loop_var, loop_var)); Stmt body = mutate(op->body); bounds.pop(op->name); if (prefetches) { for (const Prefetch &p : *prefetches) { if (!ends_with(op->name, "." + p.var)) { continue; } // Add loop variable + prefetch offset to interval scope for box computation Expr fetch_at = loop_var + p.offset; bounds.push(op->name, Interval(fetch_at, fetch_at)); map<string, Box> boxes_read = boxes_required(body, bounds); bounds.pop(op->name); // Don't prefetch buffers that are written to. We assume that these already // have good locality. // TODO: This is not a good assumption. It would be better to have the // prefetch directive specify the buffer that we want to prefetch, instead // of trying to figure out which buffers should be prefetched. This would also // mean that we don't need the "make_similar_load" hack, because we can make // calls the standard way (using the ImageParam/Function object referenced in // the prefetch). map<string, Box> boxes_written = boxes_provided(body, bounds); for (const auto &b : boxes_written) { auto it = boxes_read.find(b.first); if (it != boxes_read.end()) { debug(2) << "Not prefetching buffer " << it->first << " also written in loop " << op->name << "\n"; boxes_read.erase(it); } } // TODO: Only prefetch the newly accessed data from the previous iteration. // This should use boxes_touched (instead of boxes_required) so we exclude memory // either read or written. for (const auto &b : boxes_read) { const std::string &buf_name = b.first; // Only prefetch the region that is in bounds. Box bounds = buffer_bounds(buf_name, b.second.size()); Box prefetch_box = box_intersection(b.second, bounds); body = add_prefetch(buf_name, prefetch_box, body); } } } if (!body.same_as(op->body)) { stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body); } else { stmt = op; } } }; } // namespace Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env) { return InjectPrefetch(env).mutate(s); } } } <|endoftext|>
<commit_before>// Copyright (c) 2019 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 "net/third_party/quiche/src/quic/core/quic_bandwidth.h" #include "net/third_party/quiche/src/quic/core/quic_time.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h" #include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h" #include "net/third_party/quiche/src/quic/platform/api/quic_test.h" #include "net/third_party/quiche/src/quic/quartc/simulated_packet_transport.h" #include "net/third_party/quiche/src/quic/quartc/test/bidi_test_runner.h" #include "net/third_party/quiche/src/quic/quartc/test/quartc_competing_endpoint.h" #include "net/third_party/quiche/src/quic/quartc/test/quic_trace_interceptor.h" #include "net/third_party/quiche/src/quic/quartc/test/random_packet_filter.h" #include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/link.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/quic_endpoint.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/simulator.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/switch.h" namespace quic { namespace test { namespace { class QuartcBidiTest : public QuicTest { protected: QuartcBidiTest() { uint64_t seed = QuicRandom::GetInstance()->RandUint64(); QUIC_LOG(INFO) << "Setting random seed to " << seed; random_.set_seed(seed); simulator_.set_random_generator(&random_); client_trace_interceptor_ = QuicMakeUnique<QuicTraceInterceptor>("client"); server_trace_interceptor_ = QuicMakeUnique<QuicTraceInterceptor>("server"); } void CreateTransports(QuicBandwidth bandwidth, QuicTime::Delta propagation_delay, QuicByteCount queue_length, int loss_percent) { // Endpoints which serve as the transports for client and server. client_transport_ = QuicMakeUnique<simulator::SimulatedQuartcPacketTransport>( &simulator_, "client_transport", "server_transport", queue_length); server_transport_ = QuicMakeUnique<simulator::SimulatedQuartcPacketTransport>( &simulator_, "server_transport", "client_transport", queue_length); // Filters on each of the endpoints facilitate random packet loss. client_filter_ = QuicMakeUnique<simulator::RandomPacketFilter>( &simulator_, "client_filter", client_transport_.get()); server_filter_ = QuicMakeUnique<simulator::RandomPacketFilter>( &simulator_, "server_filter", server_transport_.get()); client_filter_->set_loss_percent(loss_percent); server_filter_->set_loss_percent(loss_percent); // Each endpoint connects directly to a switch. client_switch_ = QuicMakeUnique<simulator::Switch>( &simulator_, "client_switch", /*port_count=*/8, 2 * queue_length); server_switch_ = QuicMakeUnique<simulator::Switch>( &simulator_, "server_switch", /*port_count=*/8, 2 * queue_length); // Links to the switch have significantly higher bandwdith than the // bottleneck and insignificant propagation delay. client_link_ = QuicMakeUnique<simulator::SymmetricLink>( client_filter_.get(), client_switch_->port(1), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); server_link_ = QuicMakeUnique<simulator::SymmetricLink>( server_filter_.get(), server_switch_->port(1), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); // The bottleneck link connects the two switches with the bandwidth and // propagation delay specified by the test case. bottleneck_link_ = QuicMakeUnique<simulator::SymmetricLink>( client_switch_->port(2), server_switch_->port(2), bandwidth, propagation_delay); } void SetupCompetingEndpoints(QuicBandwidth bandwidth, QuicTime::Delta send_interval, QuicByteCount bytes_per_interval) { competing_client_ = QuicMakeUnique<QuartcCompetingEndpoint>( &simulator_, send_interval, bytes_per_interval, "competing_client", "competing_server", quic::Perspective::IS_CLIENT, quic::test::TestConnectionId(3)); competing_server_ = QuicMakeUnique<QuartcCompetingEndpoint>( &simulator_, send_interval, bytes_per_interval, "competing_server", "competing_client", quic::Perspective::IS_SERVER, quic::test::TestConnectionId(3)); competing_client_link_ = QuicMakeUnique<quic::simulator::SymmetricLink>( competing_client_->endpoint(), client_switch_->port(3), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); competing_server_link_ = QuicMakeUnique<quic::simulator::SymmetricLink>( competing_server_->endpoint(), server_switch_->port(3), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); } simulator::Simulator simulator_; SimpleRandom random_; std::unique_ptr<simulator::SimulatedQuartcPacketTransport> client_transport_; std::unique_ptr<simulator::SimulatedQuartcPacketTransport> server_transport_; std::unique_ptr<simulator::RandomPacketFilter> client_filter_; std::unique_ptr<simulator::RandomPacketFilter> server_filter_; std::unique_ptr<simulator::Switch> client_switch_; std::unique_ptr<simulator::Switch> server_switch_; std::unique_ptr<simulator::SymmetricLink> client_link_; std::unique_ptr<simulator::SymmetricLink> server_link_; std::unique_ptr<simulator::SymmetricLink> bottleneck_link_; std::unique_ptr<QuartcCompetingEndpoint> competing_client_; std::unique_ptr<QuartcCompetingEndpoint> competing_server_; std::unique_ptr<simulator::SymmetricLink> competing_client_link_; std::unique_ptr<simulator::SymmetricLink> competing_server_link_; std::unique_ptr<QuicTraceInterceptor> client_trace_interceptor_; std::unique_ptr<QuicTraceInterceptor> server_trace_interceptor_; }; TEST_F(QuartcBidiTest, Basic300kbps200ms) { CreateTransports(QuicBandwidth::FromKBitsPerSecond(300), QuicTime::Delta::FromMilliseconds(200), 10 * kDefaultMaxPacketSize, /*loss_percent=*/0); BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } TEST_F(QuartcBidiTest, 300kbps200ms2PercentLoss) { CreateTransports(QuicBandwidth::FromKBitsPerSecond(300), QuicTime::Delta::FromMilliseconds(200), 10 * kDefaultMaxPacketSize, /*loss_percent=*/2); BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } TEST_F(QuartcBidiTest, 300kbps200ms2PercentLossCompetingBurst) { QuicBandwidth bandwidth = QuicBandwidth::FromKBitsPerSecond(300); CreateTransports(bandwidth, QuicTime::Delta::FromMilliseconds(200), 10 * quic::kDefaultMaxPacketSize, /*loss_percent=*/2); SetupCompetingEndpoints(bandwidth, QuicTime::Delta::FromSeconds(15), /*bytes_per_interval=*/50 * 1024); quic::test::BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } } // namespace } // namespace test } // namespace quic <commit_msg>Add QuicBidiTest cases for aggregation and small, frequent competing bursts.<commit_after>// Copyright (c) 2019 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 "net/third_party/quiche/src/quic/core/quic_bandwidth.h" #include "net/third_party/quiche/src/quic/core/quic_time.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h" #include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h" #include "net/third_party/quiche/src/quic/platform/api/quic_test.h" #include "net/third_party/quiche/src/quic/quartc/simulated_packet_transport.h" #include "net/third_party/quiche/src/quic/quartc/test/bidi_test_runner.h" #include "net/third_party/quiche/src/quic/quartc/test/quartc_competing_endpoint.h" #include "net/third_party/quiche/src/quic/quartc/test/quic_trace_interceptor.h" #include "net/third_party/quiche/src/quic/quartc/test/random_packet_filter.h" #include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/link.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/quic_endpoint.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/simulator.h" #include "net/third_party/quiche/src/quic/test_tools/simulator/switch.h" namespace quic { namespace test { namespace { class QuartcBidiTest : public QuicTest { protected: QuartcBidiTest() { uint64_t seed = QuicRandom::GetInstance()->RandUint64(); QUIC_LOG(INFO) << "Setting random seed to " << seed; random_.set_seed(seed); simulator_.set_random_generator(&random_); client_trace_interceptor_ = QuicMakeUnique<QuicTraceInterceptor>("client"); server_trace_interceptor_ = QuicMakeUnique<QuicTraceInterceptor>("server"); } void CreateTransports(QuicBandwidth bandwidth, QuicTime::Delta propagation_delay, QuicByteCount queue_length, int loss_percent) { // Endpoints which serve as the transports for client and server. client_transport_ = QuicMakeUnique<simulator::SimulatedQuartcPacketTransport>( &simulator_, "client_transport", "server_transport", queue_length); server_transport_ = QuicMakeUnique<simulator::SimulatedQuartcPacketTransport>( &simulator_, "server_transport", "client_transport", queue_length); // Filters on each of the endpoints facilitate random packet loss. client_filter_ = QuicMakeUnique<simulator::RandomPacketFilter>( &simulator_, "client_filter", client_transport_.get()); server_filter_ = QuicMakeUnique<simulator::RandomPacketFilter>( &simulator_, "server_filter", server_transport_.get()); client_filter_->set_loss_percent(loss_percent); server_filter_->set_loss_percent(loss_percent); // Each endpoint connects directly to a switch. client_switch_ = QuicMakeUnique<simulator::Switch>( &simulator_, "client_switch", /*port_count=*/8, 2 * queue_length); server_switch_ = QuicMakeUnique<simulator::Switch>( &simulator_, "server_switch", /*port_count=*/8, 2 * queue_length); // Links to the switch have significantly higher bandwdith than the // bottleneck and insignificant propagation delay. client_link_ = QuicMakeUnique<simulator::SymmetricLink>( client_filter_.get(), client_switch_->port(1), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); server_link_ = QuicMakeUnique<simulator::SymmetricLink>( server_filter_.get(), server_switch_->port(1), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); // The bottleneck link connects the two switches with the bandwidth and // propagation delay specified by the test case. bottleneck_link_ = QuicMakeUnique<simulator::SymmetricLink>( client_switch_->port(2), server_switch_->port(2), bandwidth, propagation_delay); } void SetupCompetingEndpoints(QuicBandwidth bandwidth, QuicTime::Delta send_interval, QuicByteCount bytes_per_interval) { competing_client_ = QuicMakeUnique<QuartcCompetingEndpoint>( &simulator_, send_interval, bytes_per_interval, "competing_client", "competing_server", quic::Perspective::IS_CLIENT, quic::test::TestConnectionId(3)); competing_server_ = QuicMakeUnique<QuartcCompetingEndpoint>( &simulator_, send_interval, bytes_per_interval, "competing_server", "competing_client", quic::Perspective::IS_SERVER, quic::test::TestConnectionId(3)); competing_client_link_ = QuicMakeUnique<quic::simulator::SymmetricLink>( competing_client_->endpoint(), client_switch_->port(3), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); competing_server_link_ = QuicMakeUnique<quic::simulator::SymmetricLink>( competing_server_->endpoint(), server_switch_->port(3), 10 * bandwidth, QuicTime::Delta::FromMicroseconds(1)); } simulator::Simulator simulator_; SimpleRandom random_; std::unique_ptr<simulator::SimulatedQuartcPacketTransport> client_transport_; std::unique_ptr<simulator::SimulatedQuartcPacketTransport> server_transport_; std::unique_ptr<simulator::RandomPacketFilter> client_filter_; std::unique_ptr<simulator::RandomPacketFilter> server_filter_; std::unique_ptr<simulator::Switch> client_switch_; std::unique_ptr<simulator::Switch> server_switch_; std::unique_ptr<simulator::SymmetricLink> client_link_; std::unique_ptr<simulator::SymmetricLink> server_link_; std::unique_ptr<simulator::SymmetricLink> bottleneck_link_; std::unique_ptr<QuartcCompetingEndpoint> competing_client_; std::unique_ptr<QuartcCompetingEndpoint> competing_server_; std::unique_ptr<simulator::SymmetricLink> competing_client_link_; std::unique_ptr<simulator::SymmetricLink> competing_server_link_; std::unique_ptr<QuicTraceInterceptor> client_trace_interceptor_; std::unique_ptr<QuicTraceInterceptor> server_trace_interceptor_; }; TEST_F(QuartcBidiTest, Basic300kbps200ms) { CreateTransports(QuicBandwidth::FromKBitsPerSecond(300), QuicTime::Delta::FromMilliseconds(200), 10 * kDefaultMaxPacketSize, /*loss_percent=*/0); BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } TEST_F(QuartcBidiTest, 300kbps200ms2PercentLoss) { CreateTransports(QuicBandwidth::FromKBitsPerSecond(300), QuicTime::Delta::FromMilliseconds(200), 10 * kDefaultMaxPacketSize, /*loss_percent=*/2); BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } TEST_F(QuartcBidiTest, 300kbps200ms2PercentLossCompetingBurst) { QuicBandwidth bandwidth = QuicBandwidth::FromKBitsPerSecond(300); CreateTransports(bandwidth, QuicTime::Delta::FromMilliseconds(200), 10 * quic::kDefaultMaxPacketSize, /*loss_percent=*/2); SetupCompetingEndpoints(bandwidth, QuicTime::Delta::FromSeconds(15), /*bytes_per_interval=*/50 * 1024); quic::test::BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } TEST_F(QuartcBidiTest, 300kbps200ms2PercentLossSmallCompetingSpikes) { QuicBandwidth bandwidth = QuicBandwidth::FromKBitsPerSecond(300); CreateTransports(bandwidth, QuicTime::Delta::FromMilliseconds(200), 10 * quic::kDefaultMaxPacketSize, /*loss_percent=*/2); // Competition sends a small amount of data (10 kb) every 2 seconds. SetupCompetingEndpoints(bandwidth, QuicTime::Delta::FromSeconds(2), /*bytes_per_interval=*/10 * 1024); quic::test::BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } TEST_F(QuartcBidiTest, 300kbps200ms2PercentLossAggregation) { QuicBandwidth bandwidth = QuicBandwidth::FromKBitsPerSecond(300); CreateTransports(bandwidth, QuicTime::Delta::FromMilliseconds(200), 10 * quic::kDefaultMaxPacketSize, /*loss_percent=*/2); // Set aggregation on the queues at either end of the bottleneck. client_switch_->port_queue(2)->EnableAggregation( 10 * 1024, QuicTime::Delta::FromMilliseconds(100)); server_switch_->port_queue(2)->EnableAggregation( 10 * 1024, QuicTime::Delta::FromMilliseconds(100)); quic::test::BidiTestRunner runner(&simulator_, client_transport_.get(), server_transport_.get()); runner.set_client_interceptor(client_trace_interceptor_.get()); runner.set_server_interceptor(server_trace_interceptor_.get()); EXPECT_TRUE(runner.RunTest(QuicTime::Delta::FromSeconds(30))); } } // namespace } // namespace test } // namespace quic <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2005-2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/io/WKBReader.h> #include <geos/io/WKBConstants.h> #include <geos/io/ByteOrderValues.h> #include <geos/io/ParseException.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Coordinate.h> #include <geos/geom/Point.h> #include <geos/geom/LinearRing.h> #include <geos/geom/LineString.h> #include <geos/geom/Polygon.h> #include <geos/geom/MultiPoint.h> #include <geos/geom/MultiLineString.h> #include <geos/geom/MultiPolygon.h> #include <geos/geom/CoordinateSequenceFactory.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/PrecisionModel.h> #include <iomanip> #include <ostream> #include <sstream> #include <string> //#define DEBUG_WKB_READER 1 using namespace std; using namespace geos::geom; namespace geos { namespace io { // geos.io string WKBReader::BAD_GEOM_TYPE_MSG = "bad geometry type encountered in "; WKBReader::WKBReader() : factory(*(GeometryFactory::getDefaultInstance())) {} ostream & WKBReader::printHEX(istream &is, ostream &os) { static const char hex[] = "0123456789ABCDEF"; long pos = is.tellg(); // take note of input stream get pointer is.seekg(0, ios::beg); // rewind input stream char each=0; while(is.read(&each, 1)) { const unsigned char c=each; int low = (c & 0x0F); int high = (c >> 4); os << hex[high] << hex[low]; } is.clear(); // clear input stream eof flag is.seekg(pos); // reset input stream position return os; } Geometry * WKBReader::readHEX(istream &is) { // setup input/output stream stringstream os(ios_base::binary|ios_base::in|ios_base::out); unsigned char high, low, result_high, result_low, value; while(!is.eof())//readsome(&str[0], 2)) { // get the high part of the byte is >> high; // geth the low part of the byte is >> low; switch (high) { case '0' : result_high = 0; break; case '1' : result_high = 1; break; case '2' : result_high = 2; break; case '3' : result_high = 3; break; case '4' : result_high = 4; break; case '5' : result_high = 5; break; case '6' : result_high = 6; break; case '7' : result_high = 7; break; case '8' : result_high = 8; break; case '9' : result_high = 9; break; case 'A' : result_high = 10; break; case 'B' : result_high = 11; break; case 'C' : result_high = 12; break; case 'D' : result_high = 13; break; case 'E' : result_high = 14; break; case 'F' : result_high = 15; break; default: throw ParseException("Invalid HEX char"); } switch (low) { case '0' : result_low = 0; break; case '1' : result_low = 1; break; case '2' : result_low = 2; break; case '3' : result_low = 3; break; case '4' : result_low = 4; break; case '5' : result_low = 5; break; case '6' : result_low = 6; break; case '7' : result_low = 7; break; case '8' : result_low = 8; break; case '9' : result_low = 9; break; case 'A' : result_low = 10; break; case 'B' : result_low = 11; break; case 'C' : result_low = 12; break; case 'D' : result_low = 13; break; case 'E' : result_low = 14; break; case 'F' : result_low = 15; break; default: throw ParseException("Invalid HEX char"); } value = (result_high<<4) + result_low; #if DEBUG_HEX_READER cout<<"HEX "<<high<<low<<" -> DEC "<<(int)value<<endl; #endif // write the value to the output stream os << value; } // now call read to convert the geometry return this->read(os); } Geometry * WKBReader::read(istream &is) { dis.setInStream(&is); // will default to machine endian return readGeometry(); } Geometry * WKBReader::readGeometry() { // determine byte order unsigned char byteOrder = dis.readByte(); #if DEBUG_WKB_READER cout<<"WKB byteOrder: "<<(int)byteOrder<<endl; #endif // default is machine endian if (byteOrder == WKBConstants::wkbNDR) dis.setOrder(ByteOrderValues::ENDIAN_LITTLE); else if (byteOrder == WKBConstants::wkbXDR) dis.setOrder(ByteOrderValues::ENDIAN_BIG); int typeInt = dis.readInt(); int geometryType = typeInt & 0xff; #if DEBUG_WKB_READER cout<<"WKB geometryType: "<<geometryType<<endl; #endif bool hasZ = ((typeInt & 0x80000000) != 0); if (hasZ) inputDimension = 3; else inputDimension = 2; // doesn't handle M currently #if DEBUG_WKB_READER cout<<"WKB hasZ: "<<hasZ<<endl; #endif #if DEBUG_WKB_READER cout<<"WKB dimensions: "<<inputDimension<<endl; #endif bool hasSRID = ((typeInt & 0x20000000) != 0); #if DEBUG_WKB_READER cout<<"WKB hasSRID: "<<hasZ<<endl; #endif int SRID = -1; if (hasSRID) SRID = dis.readInt(); // read SRID // allocate space for ordValues if ( ordValues.size() < inputDimension ) ordValues.resize(inputDimension); Geometry *result; switch (geometryType) { case WKBConstants::wkbPoint : result = readPoint(); break; case WKBConstants::wkbLineString : result = readLineString(); break; case WKBConstants::wkbPolygon : result = readPolygon(); break; case WKBConstants::wkbMultiPoint : result = readMultiPoint(); break; case WKBConstants::wkbMultiLineString : result = readMultiLineString(); break; case WKBConstants::wkbMultiPolygon : result = readMultiPolygon(); break; case WKBConstants::wkbGeometryCollection : result = readGeometryCollection(); break; default: stringstream err; err << "Unknown WKB type " << geometryType; throw ParseException(err.str()); } result->setSRID(SRID); return result; } Point * WKBReader::readPoint() { readCoordinate(); return factory.createPoint(Coordinate(ordValues[0], ordValues[1])); } LineString * WKBReader::readLineString() { int size = dis.readInt(); #if DEBUG_WKB_READER cout<<"WKB npoints: "<<size<<endl; #endif CoordinateSequence *pts = readCoordinateSequence(size); return factory.createLineString(pts); } LinearRing * WKBReader::readLinearRing() { int size = dis.readInt(); #if DEBUG_WKB_READER cout<<"WKB npoints: "<<size<<endl; #endif CoordinateSequence *pts = readCoordinateSequence(size); return factory.createLinearRing(pts); } Polygon * WKBReader::readPolygon() { int numRings = dis.readInt(); #if DEBUG_WKB_READER cout<<"WKB numRings: "<<numRings<<endl; #endif LinearRing *shell = NULL; if( numRings > 0 ) shell = readLinearRing(); vector<Geometry *>*holes=NULL; if ( numRings > 1 ) { try { holes = new vector<Geometry *>(numRings-1); for (int i=0; i<numRings-1; i++) (*holes)[i] = (Geometry *)readLinearRing(); } catch (...) { for (unsigned int i=0; i<holes->size(); i++) delete (*holes)[i]; delete holes; delete shell; throw; } } return factory.createPolygon(shell, holes); } MultiPoint * WKBReader::readMultiPoint() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) { Geometry *g = readGeometry(); if (!dynamic_cast<Point *>(g)) { stringstream err; err << BAD_GEOM_TYPE_MSG << " MultiPoint"; throw ParseException(err.str()); } (*geoms)[i] = g; } } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createMultiPoint(geoms); } MultiLineString * WKBReader::readMultiLineString() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) { Geometry *g = readGeometry(); if (!dynamic_cast<LineString *>(g)) { stringstream err; err << BAD_GEOM_TYPE_MSG << " LineString"; throw ParseException(err.str()); } (*geoms)[i] = g; } } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createMultiLineString(geoms); } MultiPolygon * WKBReader::readMultiPolygon() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) { Geometry *g = readGeometry(); if (!dynamic_cast<Polygon *>(g)) { stringstream err; err << BAD_GEOM_TYPE_MSG << " Polygon"; throw ParseException(err.str()); } (*geoms)[i] = g; } } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createMultiPolygon(geoms); } GeometryCollection * WKBReader::readGeometryCollection() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) (*geoms)[i] = (readGeometry()); } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createGeometryCollection(geoms); } CoordinateSequence * WKBReader::readCoordinateSequence(int size) { CoordinateSequence *seq = factory.getCoordinateSequenceFactory()->create(size, inputDimension); unsigned int targetDim = seq->getDimension(); if ( targetDim > inputDimension ) targetDim = inputDimension; for (int i=0; i<size; i++) { readCoordinate(); for (unsigned int j=0; j<targetDim; j++) { seq->setOrdinate(i, j, ordValues[j]); } } return seq; } void WKBReader::readCoordinate() { const PrecisionModel &pm = *factory.getPrecisionModel(); for (unsigned int i=0; i<inputDimension; ++i) { if ( i <= 1 ) ordValues[i] = pm.makePrecise(dis.readDouble()); else ordValues[i] = dis.readDouble(); } #if DEBUG_WKB_READER cout<<"WKB coordinate: "<<ordValues[0]<<","<<ordValues[1]<<endl; #endif } } // namespace geos.io } // namespace geos <commit_msg>Set unknown SRID values to 0 instead of -1 to be more consistent with the rest of GEOS (srid values are initialized to 0 by default).<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2005-2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/io/WKBReader.h> #include <geos/io/WKBConstants.h> #include <geos/io/ByteOrderValues.h> #include <geos/io/ParseException.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Coordinate.h> #include <geos/geom/Point.h> #include <geos/geom/LinearRing.h> #include <geos/geom/LineString.h> #include <geos/geom/Polygon.h> #include <geos/geom/MultiPoint.h> #include <geos/geom/MultiLineString.h> #include <geos/geom/MultiPolygon.h> #include <geos/geom/CoordinateSequenceFactory.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/PrecisionModel.h> #include <iomanip> #include <ostream> #include <sstream> #include <string> //#define DEBUG_WKB_READER 1 using namespace std; using namespace geos::geom; namespace geos { namespace io { // geos.io string WKBReader::BAD_GEOM_TYPE_MSG = "bad geometry type encountered in "; WKBReader::WKBReader() : factory(*(GeometryFactory::getDefaultInstance())) {} ostream & WKBReader::printHEX(istream &is, ostream &os) { static const char hex[] = "0123456789ABCDEF"; long pos = is.tellg(); // take note of input stream get pointer is.seekg(0, ios::beg); // rewind input stream char each=0; while(is.read(&each, 1)) { const unsigned char c=each; int low = (c & 0x0F); int high = (c >> 4); os << hex[high] << hex[low]; } is.clear(); // clear input stream eof flag is.seekg(pos); // reset input stream position return os; } Geometry * WKBReader::readHEX(istream &is) { // setup input/output stream stringstream os(ios_base::binary|ios_base::in|ios_base::out); unsigned char high, low, result_high, result_low, value; while(!is.eof())//readsome(&str[0], 2)) { // get the high part of the byte is >> high; // geth the low part of the byte is >> low; switch (high) { case '0' : result_high = 0; break; case '1' : result_high = 1; break; case '2' : result_high = 2; break; case '3' : result_high = 3; break; case '4' : result_high = 4; break; case '5' : result_high = 5; break; case '6' : result_high = 6; break; case '7' : result_high = 7; break; case '8' : result_high = 8; break; case '9' : result_high = 9; break; case 'A' : result_high = 10; break; case 'B' : result_high = 11; break; case 'C' : result_high = 12; break; case 'D' : result_high = 13; break; case 'E' : result_high = 14; break; case 'F' : result_high = 15; break; default: throw ParseException("Invalid HEX char"); } switch (low) { case '0' : result_low = 0; break; case '1' : result_low = 1; break; case '2' : result_low = 2; break; case '3' : result_low = 3; break; case '4' : result_low = 4; break; case '5' : result_low = 5; break; case '6' : result_low = 6; break; case '7' : result_low = 7; break; case '8' : result_low = 8; break; case '9' : result_low = 9; break; case 'A' : result_low = 10; break; case 'B' : result_low = 11; break; case 'C' : result_low = 12; break; case 'D' : result_low = 13; break; case 'E' : result_low = 14; break; case 'F' : result_low = 15; break; default: throw ParseException("Invalid HEX char"); } value = (result_high<<4) + result_low; #if DEBUG_HEX_READER cout<<"HEX "<<high<<low<<" -> DEC "<<(int)value<<endl; #endif // write the value to the output stream os << value; } // now call read to convert the geometry return this->read(os); } Geometry * WKBReader::read(istream &is) { dis.setInStream(&is); // will default to machine endian return readGeometry(); } Geometry * WKBReader::readGeometry() { // determine byte order unsigned char byteOrder = dis.readByte(); #if DEBUG_WKB_READER cout<<"WKB byteOrder: "<<(int)byteOrder<<endl; #endif // default is machine endian if (byteOrder == WKBConstants::wkbNDR) dis.setOrder(ByteOrderValues::ENDIAN_LITTLE); else if (byteOrder == WKBConstants::wkbXDR) dis.setOrder(ByteOrderValues::ENDIAN_BIG); int typeInt = dis.readInt(); int geometryType = typeInt & 0xff; #if DEBUG_WKB_READER cout<<"WKB geometryType: "<<geometryType<<endl; #endif bool hasZ = ((typeInt & 0x80000000) != 0); if (hasZ) inputDimension = 3; else inputDimension = 2; // doesn't handle M currently #if DEBUG_WKB_READER cout<<"WKB hasZ: "<<hasZ<<endl; #endif #if DEBUG_WKB_READER cout<<"WKB dimensions: "<<inputDimension<<endl; #endif bool hasSRID = ((typeInt & 0x20000000) != 0); #if DEBUG_WKB_READER cout<<"WKB hasSRID: "<<hasZ<<endl; #endif int SRID = 0; if (hasSRID) SRID = dis.readInt(); // read SRID // allocate space for ordValues if ( ordValues.size() < inputDimension ) ordValues.resize(inputDimension); Geometry *result; switch (geometryType) { case WKBConstants::wkbPoint : result = readPoint(); break; case WKBConstants::wkbLineString : result = readLineString(); break; case WKBConstants::wkbPolygon : result = readPolygon(); break; case WKBConstants::wkbMultiPoint : result = readMultiPoint(); break; case WKBConstants::wkbMultiLineString : result = readMultiLineString(); break; case WKBConstants::wkbMultiPolygon : result = readMultiPolygon(); break; case WKBConstants::wkbGeometryCollection : result = readGeometryCollection(); break; default: stringstream err; err << "Unknown WKB type " << geometryType; throw ParseException(err.str()); } result->setSRID(SRID); return result; } Point * WKBReader::readPoint() { readCoordinate(); return factory.createPoint(Coordinate(ordValues[0], ordValues[1])); } LineString * WKBReader::readLineString() { int size = dis.readInt(); #if DEBUG_WKB_READER cout<<"WKB npoints: "<<size<<endl; #endif CoordinateSequence *pts = readCoordinateSequence(size); return factory.createLineString(pts); } LinearRing * WKBReader::readLinearRing() { int size = dis.readInt(); #if DEBUG_WKB_READER cout<<"WKB npoints: "<<size<<endl; #endif CoordinateSequence *pts = readCoordinateSequence(size); return factory.createLinearRing(pts); } Polygon * WKBReader::readPolygon() { int numRings = dis.readInt(); #if DEBUG_WKB_READER cout<<"WKB numRings: "<<numRings<<endl; #endif LinearRing *shell = NULL; if( numRings > 0 ) shell = readLinearRing(); vector<Geometry *>*holes=NULL; if ( numRings > 1 ) { try { holes = new vector<Geometry *>(numRings-1); for (int i=0; i<numRings-1; i++) (*holes)[i] = (Geometry *)readLinearRing(); } catch (...) { for (unsigned int i=0; i<holes->size(); i++) delete (*holes)[i]; delete holes; delete shell; throw; } } return factory.createPolygon(shell, holes); } MultiPoint * WKBReader::readMultiPoint() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) { Geometry *g = readGeometry(); if (!dynamic_cast<Point *>(g)) { stringstream err; err << BAD_GEOM_TYPE_MSG << " MultiPoint"; throw ParseException(err.str()); } (*geoms)[i] = g; } } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createMultiPoint(geoms); } MultiLineString * WKBReader::readMultiLineString() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) { Geometry *g = readGeometry(); if (!dynamic_cast<LineString *>(g)) { stringstream err; err << BAD_GEOM_TYPE_MSG << " LineString"; throw ParseException(err.str()); } (*geoms)[i] = g; } } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createMultiLineString(geoms); } MultiPolygon * WKBReader::readMultiPolygon() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) { Geometry *g = readGeometry(); if (!dynamic_cast<Polygon *>(g)) { stringstream err; err << BAD_GEOM_TYPE_MSG << " Polygon"; throw ParseException(err.str()); } (*geoms)[i] = g; } } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createMultiPolygon(geoms); } GeometryCollection * WKBReader::readGeometryCollection() { int numGeoms = dis.readInt(); vector<Geometry *> *geoms = new vector<Geometry *>(numGeoms); try { for (int i=0; i<numGeoms; i++) (*geoms)[i] = (readGeometry()); } catch (...) { for (unsigned int i=0; i<geoms->size(); i++) delete (*geoms)[i]; delete geoms; throw; } return factory.createGeometryCollection(geoms); } CoordinateSequence * WKBReader::readCoordinateSequence(int size) { CoordinateSequence *seq = factory.getCoordinateSequenceFactory()->create(size, inputDimension); unsigned int targetDim = seq->getDimension(); if ( targetDim > inputDimension ) targetDim = inputDimension; for (int i=0; i<size; i++) { readCoordinate(); for (unsigned int j=0; j<targetDim; j++) { seq->setOrdinate(i, j, ordValues[j]); } } return seq; } void WKBReader::readCoordinate() { const PrecisionModel &pm = *factory.getPrecisionModel(); for (unsigned int i=0; i<inputDimension; ++i) { if ( i <= 1 ) ordValues[i] = pm.makePrecise(dis.readDouble()); else ordValues[i] = dis.readDouble(); } #if DEBUG_WKB_READER cout<<"WKB coordinate: "<<ordValues[0]<<","<<ordValues[1]<<endl; #endif } } // namespace geos.io } // namespace geos <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics 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. * */ // CLASS HEADER #include <dali/internal/render/gl-resources/texture.h> // EXTERNAL INCLUDES #include <math.h> #include <memory.h> // INTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/internal/render/common/vertex.h> #include <dali/internal/render/gl-resources/context.h> #include <dali/internal/common/image-sampler.h> namespace Dali { namespace Internal { namespace { // These match the GL specification const GLint SYSTEM_MINIFY_DEFAULT = GL_NEAREST_MIPMAP_LINEAR; const GLint SYSTEM_MAGNIFY_DEFAULT = GL_LINEAR; // These are the Dali defaults const GLint DALI_MINIFY_DEFAULT = GL_LINEAR; const GLint DALI_MAGNIFY_DEFAULT = GL_LINEAR; } // namespace /** * @brief Convert a FilterMode to it's corresponding GL type. * * @param[in] filterMode The FilterMode type. * @param[in] defaultfilterMode The filter mode to use if filterMode is DEFAULT. * @param[in] defaultSystemFilterMode The filter mode to use if filterMode is NONE. * @return Return the equivalent GL type. */ GLint FilterModeToGL( FilterMode::Type filterMode, GLint defaultfilterMode, GLint defaultSystemFilterMode ) { switch( filterMode ) { case FilterMode::NEAREST: { return GL_NEAREST; } case FilterMode::LINEAR: { return GL_LINEAR; } case FilterMode::NONE: { return defaultSystemFilterMode; } case FilterMode::DEFAULT: { return defaultfilterMode; } } return GL_LINEAR; } using Dali::Internal::Vertex2D; using Dali::Internal::Vertex3D; using namespace Dali::Pixel; Texture::Texture(Context& context, unsigned int width, unsigned int height, unsigned int imageWidth, unsigned int imageHeight, Pixel::Format pixelFormat) : mContext(context), mId(0), mSamplerBitfield( 0 ), mWidth(width), mHeight(height), mImageWidth(imageWidth), mImageHeight(imageHeight), mPixelFormat(pixelFormat), mDiscarded(false) { } Texture::~Texture() { // GlCleanup() should already have been called by TextureCache ensuring the resource is destroyed // on the render thread. (And avoiding a potentially problematic virtual call in the destructor) } void Texture::SetTextureId(GLuint id) { mId=id; } void Texture::Update(Integration::Bitmap* bitmap) { DALI_ASSERT_DEBUG( "Updating incorrect texture type" == NULL ); } void Texture::UpdateArea( const RectArea& area ) { DALI_ASSERT_DEBUG( "Updating incorrect texture type" == NULL ); } bool Texture::UpdateOnCreate() { return false; } bool Texture::Bind(GLenum target, GLenum textureunit ) { // This is the only supported type at the moment DALI_ASSERT_DEBUG( target == GL_TEXTURE_2D ); bool created = false; if( mId == 0 ) { if( CreateGlTexture() ) { created = true; } } // Bind the texture id mContext.ActiveTexture(textureunit); mContext.Bind2dTexture(mId); return created; } void Texture::GlContextDestroyed() { // texture is gone mId = 0; } void Texture::GlCleanup() { // delete the gl texture if (mId != 0) { mContext.DeleteTextures(1,&mId); mId = 0; } } void Texture::MapUV(unsigned int numVerts,Vertex2D *verts, const PixelArea* pixelArea) { MapUV(numVerts, (float*)(&verts->mU), sizeof(Vertex2D)/sizeof(float), pixelArea); } void Texture::MapUV(unsigned int numVerts,Vertex3D *verts, const PixelArea* pixelArea) { MapUV(numVerts, (float*)(&verts->mU), sizeof(Vertex3D)/sizeof(float), pixelArea); } void Texture::MapUV(unsigned int numVerts, float* verts, unsigned int stride, const PixelArea* pixelArea) { UvRect uv; GetTextureCoordinates(uv, pixelArea); float uScale = fabsf(uv.u2 - uv.u0); float vScale = fabsf(uv.v2 - uv.v0); for (unsigned int i = 0; i < numVerts; ++i) { verts[0] = uv.u0 + verts[0] * uScale; verts[1] = uv.v0 + verts[1] * vScale; verts += stride; } } unsigned int Texture::GetWidth() const { return mWidth; } unsigned int Texture::GetHeight() const { return mHeight; } Pixel::Format Texture::GetPixelFormat() const { return mPixelFormat; } void Texture::GetTextureCoordinates(UvRect& uv, const PixelArea* pixelArea) { if( pixelArea == NULL ) { GetDefaultTextureCoordinates(uv); return; } // pre-calulate the normalized values const float uScale = 1.0f / float(mWidth); const float vScale = 1.0f / float(mHeight); const float x = uScale * float(pixelArea->x); const float y = vScale * float(pixelArea->y); const float width = uScale * float(pixelArea->width); const float height = vScale * float(pixelArea->height); // bottom left uv.u0 = x; uv.v0 = y; // top right uv.u2 = x + width; uv.v2 = y + height; }; void Texture::GetDefaultTextureCoordinates(UvRect& uv) const { if ((mWidth == mImageWidth) && (mHeight == mImageHeight)) { // set the uv's to display 0,0 to 1,1 uv.Reset(); return; } // the texture co-ordinates go from 0 to 1. But the image is smaller than the // texture, so we need to adjust the uv values. float uScale = float(mImageWidth) / float(mWidth); float vScale = float(mImageHeight) / float(mHeight); // bottom left uv.u0 = 0.0f; uv.v0 = 0.0f; // top right uv.u2 = uScale; uv.v2 = vScale; } void Texture::ApplyTextureParameter( GLint filterType, FilterMode::Type currentFilterMode, FilterMode::Type newFilterMode, GLint daliDefault, GLint systemDefault ) { GLint newFilterModeGL = FilterModeToGL( newFilterMode, daliDefault, systemDefault ); GLint currentFilterModeGL = FilterModeToGL( currentFilterMode, daliDefault, systemDefault ); if( newFilterModeGL != currentFilterModeGL ) { mContext.TexParameteri( GL_TEXTURE_2D, filterType, newFilterModeGL ); } } void Texture::ApplySampler( unsigned int samplerBitfield ) { if( mSamplerBitfield != samplerBitfield ) { ApplyTextureParameter( GL_TEXTURE_MIN_FILTER, ImageSampler::GetMinifyFilterMode( mSamplerBitfield ), ImageSampler::GetMinifyFilterMode( samplerBitfield ), DALI_MINIFY_DEFAULT, SYSTEM_MINIFY_DEFAULT ); ApplyTextureParameter( GL_TEXTURE_MAG_FILTER, ImageSampler::GetMagnifyFilterMode( mSamplerBitfield ), ImageSampler::GetMagnifyFilterMode( samplerBitfield ), DALI_MAGNIFY_DEFAULT, SYSTEM_MAGNIFY_DEFAULT ); mSamplerBitfield = samplerBitfield; } } } // namespace Internal } // namespace Dali <commit_msg>reset the sampler state in context loss<commit_after>/* * Copyright (c) 2014 Samsung Electronics 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. * */ // CLASS HEADER #include <dali/internal/render/gl-resources/texture.h> // EXTERNAL INCLUDES #include <math.h> #include <memory.h> // INTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/internal/render/common/vertex.h> #include <dali/internal/render/gl-resources/context.h> #include <dali/internal/common/image-sampler.h> namespace Dali { namespace Internal { namespace { // These match the GL specification const GLint SYSTEM_MINIFY_DEFAULT = GL_NEAREST_MIPMAP_LINEAR; const GLint SYSTEM_MAGNIFY_DEFAULT = GL_LINEAR; // These are the Dali defaults const GLint DALI_MINIFY_DEFAULT = GL_LINEAR; const GLint DALI_MAGNIFY_DEFAULT = GL_LINEAR; } // namespace /** * @brief Convert a FilterMode to it's corresponding GL type. * * @param[in] filterMode The FilterMode type. * @param[in] defaultfilterMode The filter mode to use if filterMode is DEFAULT. * @param[in] defaultSystemFilterMode The filter mode to use if filterMode is NONE. * @return Return the equivalent GL type. */ GLint FilterModeToGL( FilterMode::Type filterMode, GLint defaultfilterMode, GLint defaultSystemFilterMode ) { switch( filterMode ) { case FilterMode::NEAREST: { return GL_NEAREST; } case FilterMode::LINEAR: { return GL_LINEAR; } case FilterMode::NONE: { return defaultSystemFilterMode; } case FilterMode::DEFAULT: { return defaultfilterMode; } } return GL_LINEAR; } using Dali::Internal::Vertex2D; using Dali::Internal::Vertex3D; using namespace Dali::Pixel; Texture::Texture(Context& context, unsigned int width, unsigned int height, unsigned int imageWidth, unsigned int imageHeight, Pixel::Format pixelFormat) : mContext(context), mId(0), mSamplerBitfield( 0 ), mWidth(width), mHeight(height), mImageWidth(imageWidth), mImageHeight(imageHeight), mPixelFormat(pixelFormat), mDiscarded(false) { } Texture::~Texture() { // GlCleanup() should already have been called by TextureCache ensuring the resource is destroyed // on the render thread. (And avoiding a potentially problematic virtual call in the destructor) } void Texture::SetTextureId(GLuint id) { mId=id; } void Texture::Update(Integration::Bitmap* bitmap) { DALI_ASSERT_DEBUG( "Updating incorrect texture type" == NULL ); } void Texture::UpdateArea( const RectArea& area ) { DALI_ASSERT_DEBUG( "Updating incorrect texture type" == NULL ); } bool Texture::UpdateOnCreate() { return false; } bool Texture::Bind(GLenum target, GLenum textureunit ) { // This is the only supported type at the moment DALI_ASSERT_DEBUG( target == GL_TEXTURE_2D ); bool created = false; if( mId == 0 ) { if( CreateGlTexture() ) { created = true; } } // Bind the texture id mContext.ActiveTexture(textureunit); mContext.Bind2dTexture(mId); return created; } void Texture::GlContextDestroyed() { // texture is gone mId = 0; // reset sampler state as well mSamplerBitfield = 0; } void Texture::GlCleanup() { // delete the gl texture if (mId != 0) { mContext.DeleteTextures(1,&mId); mId = 0; } } void Texture::MapUV(unsigned int numVerts,Vertex2D *verts, const PixelArea* pixelArea) { MapUV(numVerts, (float*)(&verts->mU), sizeof(Vertex2D)/sizeof(float), pixelArea); } void Texture::MapUV(unsigned int numVerts,Vertex3D *verts, const PixelArea* pixelArea) { MapUV(numVerts, (float*)(&verts->mU), sizeof(Vertex3D)/sizeof(float), pixelArea); } void Texture::MapUV(unsigned int numVerts, float* verts, unsigned int stride, const PixelArea* pixelArea) { UvRect uv; GetTextureCoordinates(uv, pixelArea); float uScale = fabsf(uv.u2 - uv.u0); float vScale = fabsf(uv.v2 - uv.v0); for (unsigned int i = 0; i < numVerts; ++i) { verts[0] = uv.u0 + verts[0] * uScale; verts[1] = uv.v0 + verts[1] * vScale; verts += stride; } } unsigned int Texture::GetWidth() const { return mWidth; } unsigned int Texture::GetHeight() const { return mHeight; } Pixel::Format Texture::GetPixelFormat() const { return mPixelFormat; } void Texture::GetTextureCoordinates(UvRect& uv, const PixelArea* pixelArea) { if( pixelArea == NULL ) { GetDefaultTextureCoordinates(uv); return; } // pre-calulate the normalized values const float uScale = 1.0f / float(mWidth); const float vScale = 1.0f / float(mHeight); const float x = uScale * float(pixelArea->x); const float y = vScale * float(pixelArea->y); const float width = uScale * float(pixelArea->width); const float height = vScale * float(pixelArea->height); // bottom left uv.u0 = x; uv.v0 = y; // top right uv.u2 = x + width; uv.v2 = y + height; }; void Texture::GetDefaultTextureCoordinates(UvRect& uv) const { if ((mWidth == mImageWidth) && (mHeight == mImageHeight)) { // set the uv's to display 0,0 to 1,1 uv.Reset(); return; } // the texture co-ordinates go from 0 to 1. But the image is smaller than the // texture, so we need to adjust the uv values. float uScale = float(mImageWidth) / float(mWidth); float vScale = float(mImageHeight) / float(mHeight); // bottom left uv.u0 = 0.0f; uv.v0 = 0.0f; // top right uv.u2 = uScale; uv.v2 = vScale; } void Texture::ApplyTextureParameter( GLint filterType, FilterMode::Type currentFilterMode, FilterMode::Type newFilterMode, GLint daliDefault, GLint systemDefault ) { GLint newFilterModeGL = FilterModeToGL( newFilterMode, daliDefault, systemDefault ); GLint currentFilterModeGL = FilterModeToGL( currentFilterMode, daliDefault, systemDefault ); if( newFilterModeGL != currentFilterModeGL ) { mContext.TexParameteri( GL_TEXTURE_2D, filterType, newFilterModeGL ); } } void Texture::ApplySampler( unsigned int samplerBitfield ) { if( mSamplerBitfield != samplerBitfield ) { ApplyTextureParameter( GL_TEXTURE_MIN_FILTER, ImageSampler::GetMinifyFilterMode( mSamplerBitfield ), ImageSampler::GetMinifyFilterMode( samplerBitfield ), DALI_MINIFY_DEFAULT, SYSTEM_MINIFY_DEFAULT ); ApplyTextureParameter( GL_TEXTURE_MAG_FILTER, ImageSampler::GetMagnifyFilterMode( mSamplerBitfield ), ImageSampler::GetMagnifyFilterMode( samplerBitfield ), DALI_MAGNIFY_DEFAULT, SYSTEM_MAGNIFY_DEFAULT ); mSamplerBitfield = samplerBitfield; } } } // namespace Internal } // namespace Dali <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file rdofile.cpp \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Пройдаков Евгений (lord.tiran@gmail.com) \date 07.11.2020 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ----------------------------------------------------------------------- INCLUDES #ifdef COMPILER_VISUAL_STUDIO # include <Windows.h> # include <io.h> #else # include <unistd.h> #endif // COMPILER_VISUAL_STUDIO #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdofile.h" #include "utils/rdocommon.h" #include "utils/rdolocale.h" // -------------------------------------------------------------------------------- OPEN_RDO_NAMESPACE rbool File::create(CREF(tstring) name) { return create(name, ""); } rbool File::create(CREF(tstring) name, CREF(tstring) content) { boost::filesystem::fstream file(rdo::locale::convertToWStr(name).c_str(), std::ios::out | std::ios::binary); file << content << std::endl; file.close(); return true; } rbool File::exist(CREF(tstring) name) { return boost::filesystem::exists(rdo::locale::convertToWStr(name)); } rbool File::read_only(CREF(tstring) name) { #ifdef COMPILER_VISUAL_STUDIO return _access(name.c_str(), 04) == 0 && _access(name.c_str(), 06) == -1; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC return access(name.c_str(), R_OK) == 0 && access(name.c_str(), W_OK) == -1; #endif // COMPILER_GCC } rbool File::unlink(CREF(tstring) name) { return boost::filesystem::remove(rdo::locale::convertToWStr(name)); } rbool File::splitpath(CREF(tstring) name, REF(tstring) fileDir, REF(tstring) fileName, REF(tstring) fileExt) { boost::filesystem::path from(name); boost::filesystem::path parentDir(from.parent_path()); boost::filesystem::path rootName = parentDir.root_name(); boost::filesystem::path rootDirectory = parentDir.root_directory(); if ((rootName.empty() && rootDirectory.empty()) || parentDir != (rootName / rootDirectory)) { parentDir /= boost::filesystem::path("/"); } fileDir = parentDir.make_preferred().string(); fileName = from.stem().string(); fileExt = from.extension().string(); return true; } tstring File::getTempFileName() { #ifdef COMPILER_VISUAL_STUDIO const ruint BUFSIZE = 4096; tchar lpPathBuffer[BUFSIZE]; if (::GetTempPath(BUFSIZE, lpPathBuffer) == 0) { return tstring(); } tchar szTempName[MAX_PATH]; if (::GetTempFileName(lpPathBuffer, NULL, 0, szTempName) == 0) { return tstring(); } return szTempName; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC boost::uuids::random_generator random_gen; tstring tempFileName = tstring("/tmp/rdo_temp_file_num_") + boost::uuids::to_string(random_gen()); create(tempFileName); return tempFileName; #endif // COMPILER_GCC } tstring File::extractFilePath(CREF(tstring) fileName) { boost::filesystem::path fullFileName(fileName); tstring result = (fullFileName.make_preferred().parent_path() / boost::filesystem::path("/").make_preferred()).string(); return result; } rbool File::trimLeft(CREF(tstring) name) { boost::filesystem::ifstream inputStream(rdo::locale::convertToWStr(name).c_str(), std::ios::binary); std::stringstream sstream; if (!inputStream.good()) { return false; } rbool empty = true; while (!inputStream.eof()) { char byte; inputStream.get(byte); if (empty) { if (byte != ' ' && byte != '\t' && byte != '\n' && byte != '\r') { empty = false; } } if (!empty) { sstream.write(&byte, 1); } } inputStream.close(); boost::filesystem::path to(name); try { if (!boost::filesystem::remove(to)) { return false; } boost::filesystem::ofstream outStream(name.c_str(), std::ios::binary); outStream << sstream.str(); } catch (CREF(boost::system::error_code)) { return false; } return true; } CLOSE_RDO_NAMESPACE <commit_msg> - чистка кода<commit_after>/*! \copyright (c) RDO-Team, 2011 \file rdofile.cpp \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Пройдаков Евгений (lord.tiran@gmail.com) \date 07.11.2020 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ----------------------------------------------------------------------- INCLUDES #ifdef COMPILER_VISUAL_STUDIO # include <Windows.h> # include <io.h> #else # include <unistd.h> #endif // COMPILER_VISUAL_STUDIO #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdofile.h" #include "utils/rdocommon.h" #include "utils/rdolocale.h" // -------------------------------------------------------------------------------- OPEN_RDO_NAMESPACE rbool File::create(CREF(tstring) name) { return create(name, ""); } rbool File::create(CREF(tstring) name, CREF(tstring) content) { boost::filesystem::fstream file(rdo::locale::convertToWStr(name), std::ios::out | std::ios::binary); file << content << std::endl; file.close(); return true; } rbool File::exist(CREF(tstring) name) { return boost::filesystem::exists(rdo::locale::convertToWStr(name)); } rbool File::read_only(CREF(tstring) name) { #ifdef COMPILER_VISUAL_STUDIO return _access(name.c_str(), 04) == 0 && _access(name.c_str(), 06) == -1; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC return access(name.c_str(), R_OK) == 0 && access(name.c_str(), W_OK) == -1; #endif // COMPILER_GCC } rbool File::unlink(CREF(tstring) name) { return boost::filesystem::remove(rdo::locale::convertToWStr(name)); } rbool File::splitpath(CREF(tstring) name, REF(tstring) fileDir, REF(tstring) fileName, REF(tstring) fileExt) { boost::filesystem::path from(name); boost::filesystem::path parentDir(from.parent_path()); boost::filesystem::path rootName = parentDir.root_name(); boost::filesystem::path rootDirectory = parentDir.root_directory(); if ((rootName.empty() && rootDirectory.empty()) || parentDir != (rootName / rootDirectory)) { parentDir /= boost::filesystem::path("/"); } fileDir = parentDir.make_preferred().string(); fileName = from.stem().string(); fileExt = from.extension().string(); return true; } tstring File::getTempFileName() { #ifdef COMPILER_VISUAL_STUDIO const ruint BUFSIZE = 4096; tchar lpPathBuffer[BUFSIZE]; if (::GetTempPath(BUFSIZE, lpPathBuffer) == 0) { return tstring(); } tchar szTempName[MAX_PATH]; if (::GetTempFileName(lpPathBuffer, NULL, 0, szTempName) == 0) { return tstring(); } return szTempName; #endif // COMPILER_VISUAL_STUDIO #ifdef COMPILER_GCC boost::uuids::random_generator random_gen; tstring tempFileName = tstring("/tmp/rdo_temp_file_num_") + boost::uuids::to_string(random_gen()); create(tempFileName); return tempFileName; #endif // COMPILER_GCC } tstring File::extractFilePath(CREF(tstring) fileName) { boost::filesystem::path fullFileName(fileName); tstring result = (fullFileName.make_preferred().parent_path() / boost::filesystem::path("/").make_preferred()).string(); return result; } rbool File::trimLeft(CREF(tstring) name) { boost::filesystem::ifstream inputStream(rdo::locale::convertToWStr(name), std::ios::binary); std::stringstream sstream; if (!inputStream.good()) { return false; } rbool empty = true; while (!inputStream.eof()) { char byte; inputStream.get(byte); if (empty) { if (byte != ' ' && byte != '\t' && byte != '\n' && byte != '\r') { empty = false; } } if (!empty) { sstream.write(&byte, 1); } } inputStream.close(); boost::filesystem::path to(name); try { if (!boost::filesystem::remove(to)) { return false; } boost::filesystem::ofstream outStream(name, std::ios::binary); outStream << sstream.str(); } catch (CREF(boost::system::error_code)) { return false; } return true; } CLOSE_RDO_NAMESPACE <|endoftext|>