text
stringlengths
54
60.6k
<commit_before>97681cb8-2e4d-11e5-9284-b827eb9e62be<commit_msg>976d18a8-2e4d-11e5-9284-b827eb9e62be<commit_after>976d18a8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4822defe-2e4d-11e5-9284-b827eb9e62be<commit_msg>4827f7ae-2e4d-11e5-9284-b827eb9e62be<commit_after>4827f7ae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include "stan/math/functions/falling_factorial.hpp" #include <gtest/gtest.h> TEST(MathFunctions, falling_factorial) { using stan::math::falling_factorial; EXPECT_FLOAT_EQ(4, falling_factorial(4.0,3)); EXPECT_FLOAT_EQ(0.25, falling_factorial(3.0,4)); EXPECT_THROW(falling_factorial(-1, 4), std::domain_error); } <commit_msg>added NaN test for falling_factorial<commit_after>#include <stan/math/functions/falling_factorial.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> TEST(MathFunctions, falling_factorial) { using stan::math::falling_factorial; EXPECT_FLOAT_EQ(4, falling_factorial(4.0,3)); EXPECT_FLOAT_EQ(0.25, falling_factorial(3.0,4)); EXPECT_THROW(falling_factorial(-1, 4), std::domain_error); } TEST(MathFunctions, falling_factorial_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(4.0, nan)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(nan, 4.0)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(nan, nan)); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep14/call_proc_exit_cache_contained.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <errl/errludtarget.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> #include <initservice/taskargs.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/util.H> #include <targeting/common/utilFilter.H> #include <sys/mm.h> #include <intr/interrupt.H> #include <isteps/hwpf_reasoncodes.H> using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; namespace ISTEP_14 { void* call_proc_exit_cache_contained (void *io_pArgs) { IStepError l_stepError; TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_exit_cache_contained entry" ); // @@@@@ CUSTOM BLOCK: @@@@@ // figure out what targets we need // customize any other inputs // set up loops to go through all targets (if parallel, spin off a task) // extend the memory space from 8MEG to 32Meg //if mirrored then check that there is going to be memory at that location. //For sapphire with mirrored location flipped and at zero, //this also insures there is memory available to 'exit_cache' to. //Also set ATTR_PAYLOAD_BASE here. TARGETING::Target* l_sys = NULL; targetService().getTopLevelTarget(l_sys); assert( l_sys != NULL ); //@TODO RTC:133831 Commenting out due to missing attributes #if 0 errlHndl_t l_errl = NULL; uint8_t l_mpipl = l_sys->getAttr<ATTR_IS_MPIPL_HB>(); ATTR_PAYLOAD_BASE_type payloadBase = 0; if(!l_mpipl) { ATTR_PAYLOAD_IN_MIRROR_MEM_type l_mirrored = false; // In Sapphire mode disable mirroring for now - @todo-RTC:108314 // and force payload to zero if(!is_sapphire_load()) { payloadBase = l_sys->getAttr<ATTR_PAYLOAD_BASE>(); l_mirrored = l_sys->getAttr<ATTR_PAYLOAD_IN_MIRROR_MEM>(); } if(l_mirrored) { ATTR_MIRROR_BASE_ADDRESS_type l_mirrorBaseAddr = 0; if(!is_sapphire_load()) { uint64_t hrmor_base = l_sys->getAttr<TARGETING::ATTR_HB_HRMOR_NODAL_BASE>(); l_mirrorBaseAddr = l_sys->getAttr<TARGETING::ATTR_MIRROR_BASE_ADDRESS>(); // For single-node systems, the non-master processors can be // in a different logical (powerbus) node. // Need to migrate task to master. task_affinity_pin(); task_affinity_migrate_to_master(); uint64_t this_node = INTR::PIR_t(task_getcpuid()).nodeId; task_affinity_unpin(); l_mirrorBaseAddr += (this_node * hrmor_base)/2; } // Verify there is memory at the mirrored location bool mirroredMemExists = false; TARGETING::TargetHandleList l_procList; getAllChips(l_procList, TYPE_PROC); for (TargetHandleList::const_iterator proc = l_procList.begin(); proc != l_procList.end() && !mirroredMemExists; ++proc) { uint64_t mirrorBase[4]; uint64_t mirrorSize[4]; bool rc = (*proc)-> tryGetAttr<TARGETING::ATTR_PROC_MIRROR_BASES>(mirrorBase); if(false == rc) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Failed to get ATTR_PROC_MIRROR_BASES"); assert(0); } rc = (*proc)-> tryGetAttr<TARGETING::ATTR_PROC_MIRROR_SIZES>(mirrorSize); if(false == rc) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Failed to get ATTR_PROC_MIRROR_SIZES"); assert(0); } for(uint64_t i = 0; i < 4 && !mirroredMemExists; ++i) { if(mirrorSize[i] != 0 && l_mirrorBaseAddr >= mirrorBase[i] && l_mirrorBaseAddr < (mirrorBase[i] + mirrorSize[i])) { mirroredMemExists = true; } } } if (mirroredMemExists) { // ATTR_PAYLOAD_BASE is in MB payloadBase += l_mirrorBaseAddr/MEGABYTE; } else { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK "Request to load payload into mirrored memory," " but no memory exists at address 0x%016lx", l_mirrorBaseAddr); /*@ * @errortype ERRL_SEV_CRITICAL_SYS_TERM * @moduleid fapi::MOD_EXIT_CACHE_CONTAINED, * @reasoncode fapi::RC_NO_MIRRORED_MEMORY, * @userdata1 Mirrored Memory Address * @userdata2 0 * * @devdesc Request given to load payload into mirrored * memory, but no mirrored memory exists at * that location. */ l_errl = new ERRORLOG::ErrlEntry ( ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM, fapi::MOD_EXIT_CACHE_CONTAINED, fapi::RC_NO_MIRRORED_MEMORY, l_mirrorBaseAddr, 0, true); // callout firmware } } // If we're not mirrored, payloadBase is the lowest mem_base. // Note that if we are mirrored, finding the correct mirror // base yields the proper payloadBase. This should also work // for sapphire as a single (working) node will return 0 for // bottom_mem_addr. else { payloadBase += get_bottom_mem_addr()/MEGABYTE; } } if(!l_errl) { if(!l_mpipl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Payload base address is 0x%016lx", payloadBase * MEGABYTE); l_sys->setAttr<ATTR_PAYLOAD_BASE>(payloadBase); } //@TODO RTC:133831 call the HWP with each fapi::Target //FAPI_INVOKE_HWP( l_errl, // proc_exit_cache_contained // ); if ( l_errl ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call_proc_exit_cache_contained, " "errorlog PLID=0x%x", l_errl->plid() ); } // no errors so extend VMM. else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : call_proc_exit_cache_contained" ); // Call the function to extend VMM to 32MEG int rc = mm_extend(); if (rc!=0) { /*@ * @errortype * @moduleid fapi::MOD_EXIT_CACHE_CONTAINED * @reasoncode fapi::RC_MM_EXTEND_FAILED * @userdata1 rc from mm_extend * @userdata2 <UNUSED> * * @devdesc Failure extending memory to 32MEG after * exiting cache contained mode. */ l_errl = new ERRORLOG::ErrlEntry (ERRORLOG::ERRL_SEV_UNRECOVERABLE, fapi::MOD_EXIT_CACHE_CONTAINED, fapi::RC_MM_EXTEND_FAILED, rc, 0); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call_proc_exit_cache_contained" " - extendVMM, rc=0x%x", rc ); } else { // trace out the extend VMM was successful TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : call_proc_exit_cache_contained" " - extendVMM"); } } } if ( l_errl ) { // Create IStep error log and cross reference to error that occurred l_stepError.addErrorDetails( l_errl ); // Commit Error errlCommit( l_errl, HWPF_COMP_ID ); } TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_exit_cache_contained exit" ); #endif // @@@@@ END CUSTOM BLOCK: @@@@@ // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } }; <commit_msg>P9 - Fake trigger for memory expansion<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep14/call_proc_exit_cache_contained.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <errl/errludtarget.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> #include <initservice/taskargs.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/util.H> #include <targeting/common/utilFilter.H> #include <sys/mm.h> #include <intr/interrupt.H> #include <isteps/hwpf_reasoncodes.H> // @TODO RTC:134082 remove below block // Add P9 - Fake trigger for memory expansion #include <kernel/console.H> // printk status #include <devicefw/userif.H> // @TODO RTC:134082 remove above block using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; namespace ISTEP_14 { void* call_proc_exit_cache_contained (void *io_pArgs) { IStepError l_stepError; TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_exit_cache_contained entry" ); // @@@@@ CUSTOM BLOCK: @@@@@ // figure out what targets we need // customize any other inputs // set up loops to go through all targets (if parallel, spin off a task) // extend the memory space from 8MEG to 32Meg //if mirrored then check that there is going to be memory at that location. //For sapphire with mirrored location flipped and at zero, //this also insures there is memory available to 'exit_cache' to. //Also set ATTR_PAYLOAD_BASE here. TARGETING::Target* l_sys = NULL; targetService().getTopLevelTarget(l_sys); assert( l_sys != NULL ); //@TODO RTC:133831 Commenting out due to missing attributes errlHndl_t l_errl = NULL; uint8_t l_mpipl = l_sys->getAttr<ATTR_IS_MPIPL_HB>(); ATTR_PAYLOAD_BASE_type payloadBase = 0; if(!l_mpipl) { ATTR_PAYLOAD_IN_MIRROR_MEM_type l_mirrored = false; // In Sapphire mode disable mirroring for now - @todo-RTC:108314 // and force payload to zero if(!is_sapphire_load()) { payloadBase = l_sys->getAttr<ATTR_PAYLOAD_BASE>(); l_mirrored = l_sys->getAttr<ATTR_PAYLOAD_IN_MIRROR_MEM>(); } if(l_mirrored) { ATTR_MIRROR_BASE_ADDRESS_type l_mirrorBaseAddr = 0; if(!is_sapphire_load()) { uint64_t hrmor_base = l_sys->getAttr<TARGETING::ATTR_HB_HRMOR_NODAL_BASE>(); l_mirrorBaseAddr = l_sys->getAttr<TARGETING::ATTR_MIRROR_BASE_ADDRESS>(); // For single-node systems, the non-master processors can be // in a different logical (powerbus) node. // Need to migrate task to master. task_affinity_pin(); task_affinity_migrate_to_master(); uint64_t this_node = INTR::PIR_t(task_getcpuid()).nodeId; task_affinity_unpin(); l_mirrorBaseAddr += (this_node * hrmor_base)/2; } // Verify there is memory at the mirrored location bool mirroredMemExists = false; TARGETING::TargetHandleList l_procList; getAllChips(l_procList, TYPE_PROC); for (TargetHandleList::const_iterator proc = l_procList.begin(); proc != l_procList.end() && !mirroredMemExists; ++proc) { uint64_t mirrorBase[4]; uint64_t mirrorSize[4]; bool rc = (*proc)-> tryGetAttr<TARGETING::ATTR_PROC_MIRROR_BASES>(mirrorBase); if(false == rc) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Failed to get ATTR_PROC_MIRROR_BASES"); assert(0); } rc = (*proc)-> tryGetAttr<TARGETING::ATTR_PROC_MIRROR_SIZES>(mirrorSize); if(false == rc) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Failed to get ATTR_PROC_MIRROR_SIZES"); assert(0); } for(uint64_t i = 0; i < 4 && !mirroredMemExists; ++i) { if(mirrorSize[i] != 0 && l_mirrorBaseAddr >= mirrorBase[i] && l_mirrorBaseAddr < (mirrorBase[i] + mirrorSize[i])) { mirroredMemExists = true; } } } if (mirroredMemExists) { // ATTR_PAYLOAD_BASE is in MB payloadBase += l_mirrorBaseAddr/MEGABYTE; } else { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK "Request to load payload into mirrored memory," " but no memory exists at address 0x%016lx", l_mirrorBaseAddr); /*@ * @errortype ERRL_SEV_CRITICAL_SYS_TERM * @moduleid fapi::MOD_EXIT_CACHE_CONTAINED, * @reasoncode fapi::RC_NO_MIRRORED_MEMORY, * @userdata1 Mirrored Memory Address * @userdata2 0 * * @devdesc Request given to load payload into mirrored * memory, but no mirrored memory exists at * that location. */ l_errl = new ERRORLOG::ErrlEntry ( ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM, fapi::MOD_EXIT_CACHE_CONTAINED, fapi::RC_NO_MIRRORED_MEMORY, l_mirrorBaseAddr, 0, true); // callout firmware } } // If we're not mirrored, payloadBase is the lowest mem_base. // Note that if we are mirrored, finding the correct mirror // base yields the proper payloadBase. This should also work // for sapphire as a single (working) node will return 0 for // bottom_mem_addr. else { payloadBase += get_bottom_mem_addr()/MEGABYTE; } } if(!l_errl) { if(!l_mpipl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Payload base address is 0x%016lx", payloadBase * MEGABYTE); l_sys->setAttr<ATTR_PAYLOAD_BASE>(payloadBase); } //@TODO RTC:133831 call the HWP with each fapi::Target //FAPI_INVOKE_HWP( l_errl, // proc_exit_cache_contained // ); if ( l_errl ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call_proc_exit_cache_contained, " "errorlog PLID=0x%x", l_errl->plid() ); } // no errors so extend VMM. else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : call_proc_exit_cache_contained" ); // @TODO RTC:134082 remove below block #if 1 // Add P9 - Fake trigger for memory expansion TARGETING::Target* l_masterProc = NULL; TARGETING::targetService() .masterProcChipTargetHandle( l_masterProc ); uint64_t l_top_addr = get_top_mem_addr(); uint64_t l_bottom_addr = get_bottom_mem_addr(); uint64_t l_mem_size = l_top_addr - l_bottom_addr; // aggregate scom data to write uint64_t l_data[] = {l_bottom_addr, // Memory Base Address l_mem_size, // Memory Size in bytes 1}; // Memory Valid uint64_t l_addr = 0x05000000; size_t scom_size = sizeof(uint64_t); for(uint8_t i = 0; i < sizeof(l_data) / sizeof(uint64_t); i++) { l_errl = deviceWrite( l_masterProc, &(l_data[i]), scom_size, DEVICE_SCOM_ADDRESS(l_addr+i) ); if( l_errl ) { break; } } if ( l_errl ) { // Create IStep error log and cross reference to error that // occurred l_stepError.addErrorDetails( l_errl ); // Commit Error errlCommit( l_errl, HWPF_COMP_ID ); } printk("Fake Memory now set up.\n"); // exit cache contained mode l_errl = deviceWrite( l_masterProc, &(l_data[2]), scom_size, DEVICE_SCOM_ADDRESS(l_addr+3) ); if ( l_errl ) { // Create IStep error log and cross reference to error that // occurred l_stepError.addErrorDetails( l_errl ); // Commit Error errlCommit( l_errl, HWPF_COMP_ID ); } printk("Cache contained mode has been exited.\n"); // End of Add P9 - Fake trigger for memory expansion #endif // @TODO RTC:134082 remove above block // Call the function to extend VMM to 32MEG int rc = mm_extend(); if (rc!=0) { /*@ * @errortype * @moduleid fapi::MOD_EXIT_CACHE_CONTAINED * @reasoncode fapi::RC_MM_EXTEND_FAILED * @userdata1 rc from mm_extend * @userdata2 <UNUSED> * * @devdesc Failure extending memory to 32MEG after * exiting cache contained mode. */ l_errl = new ERRORLOG::ErrlEntry (ERRORLOG::ERRL_SEV_UNRECOVERABLE, fapi::MOD_EXIT_CACHE_CONTAINED, fapi::RC_MM_EXTEND_FAILED, rc, 0); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call_proc_exit_cache_contained" " - extendVMM, rc=0x%x", rc ); } else { // trace out the extend VMM was successful TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : call_proc_exit_cache_contained" " - extendVMM"); } } } if ( l_errl ) { // Create IStep error log and cross reference to error that occurred l_stepError.addErrorDetails( l_errl ); // Commit Error errlCommit( l_errl, HWPF_COMP_ID ); } TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_exit_cache_contained exit" ); // @@@@@ END CUSTOM BLOCK: @@@@@ // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } }; <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_MATH_RANDOM_HPP #define INCLUDE_AL_MATH_RANDOM_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The 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: 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 University of California 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. File description: Various flavors of pseudo-random number generators and distributions File author(s): Lance Putnam, 2006, putnam.lance@gmail.com */ #include <time.h> /* req'd for time() */ #include <cmath> #include "allocore/types/al_Conversion.hpp" /* req'd for int to float conversion */ #include "allocore/math/al_Constants.hpp" namespace al { /// Random number generation utilities namespace rnd{ class LinCon; class MulLinCon; class Tausworthe; template<class RNG> class Random; /// Get a random seed in interval [0, 4294967296) inline static uint32_t seed(){ static uint32_t val = time(NULL); return val = val*1664525UL + 1013904223UL; } /// Random distribution generator template <class RNG=al::rnd::Tausworthe> class Random{ public: /// Default constructor uses a randomly generated seed Random(){} /// @param[in] seed Initial seed value Random(uint32_t seed): mRNG(seed){} /// Set seed Random& seed(uint32_t v){ mRNG.seed(v); return *this; } /// Returns uniform random in [0, 1) float uniform(){ return al::uintToUnit<float>(mRNG()); } /// Returns uniform random in [0, hi) template <class T> T uniform(const T& hi){ return hi*uniform(); } /// Returns uniform random in [lo, hi) template <class T> T uniform(const T& hi, const T& lo){ return T((hi-lo)*uniform()) + lo; } /// Returns uniform random in [-1, 1) float uniformS(){ return al::uintToUnitS<float>(mRNG()); } /// Returns uniform random in [-lim, lim) template <class T> T uniformS(const T& lim){ return lim*uniformS(); } /// Returns point within a unit ball /// To get a random point on a sphere, simply normalize the result. /// \tparam N dimensions of ball /// @param[in] point an array of size N template <int N, class T> void ball(T * point); /// Returns random Gaussian float gaussian(){ float r; gaussian(r,r); return r; } /// Returns two random Gaussians template <class T> void gaussian(T& y1, T& y2); /// Returns true with a probability of p. bool prob(float p=0.5f){ return uniform() < p; } /// Randomly shuffles elements in array. template <class T> void shuffle(T * arr, uint32_t len); protected: RNG mRNG; }; /// Linear congruential uniform pseudo-random number generator. /// This generator is very fast requiring only a single integer multiply and add /// per iteration. However, the least significant bits of the numbers are less /// random; the most extreme case being the LSB which at best flips between /// 0 and 1. This generator also exhibits poor dimensional distribution, /// therefore it is best to have a different generator for each dimension, /// rather than sharing one. class LinCon { public: /// Default constructor uses a randomly generated seed LinCon(){ seed(al::rnd::seed()); type(0); } /// @param[in] seed Initial seed value LinCon(uint32_t seed) : mVal(seed) { type(0); } /// Generate next uniform random integer in [0, 2^32) uint32_t operator()(){ return mVal = mVal*mMul + mAdd; } /// Set seed void seed(uint32_t v){ mVal=v; } /// Change the type of equation used. /// 0 - Knuth, Numerical Recipes in C\n /// 1 - BCPL void type(int v){ switch(v){ default: case 0: mMul = 1664525; mAdd = 1013904223; break; case 1: mMul = 2147001325; mAdd = 715136305; break; } } private: uint32_t mVal; uint32_t mMul, mAdd; }; /// Multiplicative linear congruential uniform pseudo-random number generator. /// This generator is faster than LinCon requiring only a single integer /// multiply per iteration. However, the downside is that it produces lower /// quality (less "random") results than LinCon. Because of this, it is really /// not appropriate for simulations, but due to its speed it is very useful for /// synthesizing noise for audio and graphics. class MulLinCon{ public: /// Default constructor uses a randomly generated seed MulLinCon(){ seed(al::rnd::seed()); type(0); } /// @param[in] seed Initial seed value MulLinCon(uint32_t seed) : mVal(seed) { type(0); } /// Generate next uniform random integer in [0, 2^32) uint32_t operator()(){ return mVal *= mMul; } /// Set seed void seed(uint32_t v){ mVal=v; } /// Change the type of equation used. /// 0 - Marsaglia, Super-Duper\n /// void type(int v){ switch(v){ default: case 0: mMul = 69069; break; } } private: uint32_t mVal; uint32_t mMul; }; /// Combined Tausworthe uniform pseudo-random number generator. /// This generator produces highly random numbers, but is more expensive than /// than a linear congruential RNG. /// It is based on the paper /// P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe Generators", /// Mathematics of Computation, 65, 213 (1996), 203--213. /// http://www.iro.umontreal.ca/~lecuyer/papers.html class Tausworthe{ public: /// Default constructor uses a randomly generated seed Tausworthe(); /// @param[in] seed Initial seed value Tausworthe(uint32_t seed); /// Generate next uniform random integer in [0, 2^32) uint32_t operator()(); /// Set seed void seed(uint32_t v); /// Set seed void seed(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4); private: uint32_t s1, s2, s3, s4; void iterate(); }; /// Get global random number generator inline Random<>& global(){ static Random<> r; return r; } /// Returns point within a unit ball /// To get a random point on a sphere, simply normalize the result. /// \tparam N dimensions of ball /// @param[in] point an array of size N template <int N, class T> inline void ball(T * point){ global().ball<N>(point); } /// Returns random Gaussian inline float gaussian(){ return global().gaussian(); } /// Returns true with probability p inline bool prob(float p=0.5){ return global().prob(p); } /// Returns uniform random in [0, 1) inline float uniform(){ return global().uniform(); } /// Returns uniform random in [0, hi) template <class T> inline T uniform(const T& hi){ return global().uniform(hi); } /// Returns uniform random in [lo, hi) template <class T> inline T uniform(const T& hi, const T& lo){ return global().uniform(hi,lo); } /// Returns signed uniform random in (-1, 1) inline float uniformS(){ return global().uniformS(); } /// Returns signed uniform random in (-lim, lim) template <class T> inline T uniformS(const T& lim){ return global().uniformS(lim); } // Implementation_______________________________________________________________ inline Tausworthe::Tausworthe(){ seed(al::rnd::seed()); } inline Tausworthe::Tausworthe(uint32_t sd){ seed(sd); } inline uint32_t Tausworthe::operator()(){ iterate(); return s1 ^ s2 ^ s3 ^ s4; } inline void Tausworthe::seed(uint32_t v){ al::rnd::LinCon g(v); g(); seed(g(), g(), g(), g()); } inline void Tausworthe::seed(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4){ //printf("%u %u %u %u\n", v1, v2, v3, v4); v1 & 0xffffffe ? s1 = v1 : s1 = ~v1; v2 & 0xffffff8 ? s2 = v2 : s2 = ~v2; v3 & 0xffffff0 ? s3 = v3 : s3 = ~v3; v4 & 0xfffff80 ? s4 = v4 : s4 = ~v4; } inline void Tausworthe::iterate(){ s1 = ((s1 & 0xfffffffe) << 18) ^ (((s1 << 6) ^ s1) >> 13); s2 = ((s2 & 0xfffffff8) << 2) ^ (((s2 << 2) ^ s2) >> 27); s3 = ((s3 & 0xfffffff0) << 7) ^ (((s3 << 13) ^ s3) >> 21); s4 = ((s4 & 0xffffff80) << 13) ^ (((s4 << 3) ^ s4) >> 12); } template <class RNG> template <int N, class T> void Random<RNG>::ball(T * point){ T w; do{ w = T(0); for(int i=0; i<N; ++i){ float v = uniformS(); point[i] = v; w += v*v; } } while(w >= T(1)); // if on or outside unit ball, try again } // Box-Muller transform // Box, G. and Muller, M. A note on the generation of normal deviates. // Ann. Math. Slat. 28, (1958). // // http://en.wikipedia.org/wiki/Box–Muller_transform template <class RNG> template <class T> void Random<RNG>::gaussian(T& y1, T& y2){ float x1, x2, w; // Search for point within unit circle using sample-reject. // This will pass with probability π/4 = ~0.785. do{ x1 = uniformS(); x2 = uniformS(); w = x1 * x1 + x2 * x2; } while(w >= 1.f); // perform inverse Gaussian function mapping w = std::sqrt((-2.f * std::log(w)) / w); y1 = T(x1 * w); y2 = T(x2 * w); } // Fisher-Yates shuffle template <class RNG> template <class T> void Random<RNG>::shuffle(T * arr, uint32_t len){ for(uint32_t i=len-1; i>0; --i){ uint32_t j = uniform(i+1); T t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } } // al::rnd:: } // al:: #endif <commit_msg>rename gaussian to normal; more conventional and easier to type<commit_after>#ifndef INCLUDE_AL_MATH_RANDOM_HPP #define INCLUDE_AL_MATH_RANDOM_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The 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: 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 University of California 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. File description: Various flavors of pseudo-random number generators and distributions File author(s): Lance Putnam, 2006, putnam.lance@gmail.com */ #include <time.h> /* req'd for time() */ #include <cmath> #include "allocore/types/al_Conversion.hpp" /* req'd for int to float conversion */ #include "allocore/math/al_Constants.hpp" namespace al { /// Random number generation utilities namespace rnd{ class LinCon; class MulLinCon; class Tausworthe; template<class RNG> class Random; /// Get a random seed in interval [0, 4294967296) inline static uint32_t seed(){ static uint32_t val = time(NULL); return val = val*1664525UL + 1013904223UL; } /// Random distribution generator template <class RNG=al::rnd::Tausworthe> class Random{ public: /// Default constructor uses a randomly generated seed Random(){} /// @param[in] seed Initial seed value Random(uint32_t seed): mRNG(seed){} /// Set seed Random& seed(uint32_t v){ mRNG.seed(v); return *this; } /// Returns uniform random in [0, 1) float uniform(){ return al::uintToUnit<float>(mRNG()); } /// Returns uniform random in [0, hi) template <class T> T uniform(const T& hi){ return hi*uniform(); } /// Returns uniform random in [lo, hi) template <class T> T uniform(const T& hi, const T& lo){ return T((hi-lo)*uniform()) + lo; } /// Returns uniform random in [-1, 1) float uniformS(){ return al::uintToUnitS<float>(mRNG()); } /// Returns uniform random in [-lim, lim) template <class T> T uniformS(const T& lim){ return lim*uniformS(); } /// Returns point within a unit ball /// To get a random point on a sphere, simply normalize the result. /// \tparam N dimensions of ball /// @param[in] point an array of size N template <int N, class T> void ball(T * point); /// Returns standard normal variate float normal(){ float r; normal(r,r); return r; } /// Returns two standard normal variates (for the price of one) template <class T> void normal(T& y1, T& y2); /// Returns true with a probability of p bool prob(float p=0.5f){ return uniform() < p; } /// Randomly shuffles elements in array template <class T> void shuffle(T * arr, uint32_t len); // DEPRECATED: float gaussian(){ return normal(); } template <class T> void gaussian(T& y1, T& y2){ normal(y1,y2); } protected: RNG mRNG; }; /// Linear congruential uniform pseudo-random number generator. /// This generator is very fast requiring only a single integer multiply and add /// per iteration. However, the least significant bits of the numbers are less /// random; the most extreme case being the LSB which at best flips between /// 0 and 1. This generator also exhibits poor dimensional distribution, /// therefore it is best to have a different generator for each dimension, /// rather than sharing one. class LinCon { public: /// Default constructor uses a randomly generated seed LinCon(){ seed(al::rnd::seed()); type(0); } /// @param[in] seed Initial seed value LinCon(uint32_t seed) : mVal(seed) { type(0); } /// Generate next uniform random integer in [0, 2^32) uint32_t operator()(){ return mVal = mVal*mMul + mAdd; } /// Set seed void seed(uint32_t v){ mVal=v; } /// Change the type of equation used. /// 0 - Knuth, Numerical Recipes in C\n /// 1 - BCPL void type(int v){ switch(v){ default: case 0: mMul = 1664525; mAdd = 1013904223; break; case 1: mMul = 2147001325; mAdd = 715136305; break; } } private: uint32_t mVal; uint32_t mMul, mAdd; }; /// Multiplicative linear congruential uniform pseudo-random number generator. /// This generator is faster than LinCon requiring only a single integer /// multiply per iteration. However, the downside is that it produces lower /// quality (less "random") results than LinCon. Because of this, it is really /// not appropriate for simulations, but due to its speed it is very useful for /// synthesizing noise for audio and graphics. class MulLinCon{ public: /// Default constructor uses a randomly generated seed MulLinCon(){ seed(al::rnd::seed()); type(0); } /// @param[in] seed Initial seed value MulLinCon(uint32_t seed) : mVal(seed) { type(0); } /// Generate next uniform random integer in [0, 2^32) uint32_t operator()(){ return mVal *= mMul; } /// Set seed void seed(uint32_t v){ mVal=v; } /// Change the type of equation used. /// 0 - Marsaglia, Super-Duper\n /// void type(int v){ switch(v){ default: case 0: mMul = 69069; break; } } private: uint32_t mVal; uint32_t mMul; }; /// Combined Tausworthe uniform pseudo-random number generator. /// This generator produces highly random numbers, but is more expensive than /// than a linear congruential RNG. /// It is based on the paper /// P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe Generators", /// Mathematics of Computation, 65, 213 (1996), 203--213. /// http://www.iro.umontreal.ca/~lecuyer/papers.html class Tausworthe{ public: /// Default constructor uses a randomly generated seed Tausworthe(); /// @param[in] seed Initial seed value Tausworthe(uint32_t seed); /// Generate next uniform random integer in [0, 2^32) uint32_t operator()(); /// Set seed void seed(uint32_t v); /// Set seed void seed(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4); private: uint32_t s1, s2, s3, s4; void iterate(); }; /// Get global random number generator inline Random<>& global(){ static Random<> r; return r; } /// Returns point within a unit ball /// To get a random point on a sphere, simply normalize the result. /// \tparam N dimensions of ball /// @param[in] point an array of size N template <int N, class T> inline void ball(T * point){ global().ball<N>(point); } /// Returns standard normal variate inline float normal(){ return global().normal(); } inline float gaussian(){ return normal(); } /// Returns true with probability p inline bool prob(float p=0.5){ return global().prob(p); } /// Returns uniform random in [0, 1) inline float uniform(){ return global().uniform(); } /// Returns uniform random in [0, hi) template <class T> inline T uniform(const T& hi){ return global().uniform(hi); } /// Returns uniform random in [lo, hi) template <class T> inline T uniform(const T& hi, const T& lo){ return global().uniform(hi,lo); } /// Returns signed uniform random in (-1, 1) inline float uniformS(){ return global().uniformS(); } /// Returns signed uniform random in (-lim, lim) template <class T> inline T uniformS(const T& lim){ return global().uniformS(lim); } // Implementation_______________________________________________________________ inline Tausworthe::Tausworthe(){ seed(al::rnd::seed()); } inline Tausworthe::Tausworthe(uint32_t sd){ seed(sd); } inline uint32_t Tausworthe::operator()(){ iterate(); return s1 ^ s2 ^ s3 ^ s4; } inline void Tausworthe::seed(uint32_t v){ al::rnd::LinCon g(v); g(); seed(g(), g(), g(), g()); } inline void Tausworthe::seed(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t v4){ //printf("%u %u %u %u\n", v1, v2, v3, v4); v1 & 0xffffffe ? s1 = v1 : s1 = ~v1; v2 & 0xffffff8 ? s2 = v2 : s2 = ~v2; v3 & 0xffffff0 ? s3 = v3 : s3 = ~v3; v4 & 0xfffff80 ? s4 = v4 : s4 = ~v4; } inline void Tausworthe::iterate(){ s1 = ((s1 & 0xfffffffe) << 18) ^ (((s1 << 6) ^ s1) >> 13); s2 = ((s2 & 0xfffffff8) << 2) ^ (((s2 << 2) ^ s2) >> 27); s3 = ((s3 & 0xfffffff0) << 7) ^ (((s3 << 13) ^ s3) >> 21); s4 = ((s4 & 0xffffff80) << 13) ^ (((s4 << 3) ^ s4) >> 12); } template <class RNG> template <int N, class T> void Random<RNG>::ball(T * point){ T w; do{ w = T(0); for(int i=0; i<N; ++i){ float v = uniformS(); point[i] = v; w += v*v; } } while(w >= T(1)); // if on or outside unit ball, try again } // Box-Muller transform // Box, G. and Muller, M. A note on the generation of normal deviates. // Ann. Math. Slat. 28, (1958). // // http://en.wikipedia.org/wiki/Box–Muller_transform template <class RNG> template <class T> void Random<RNG>::normal(T& y1, T& y2){ float x1, x2, w; // Search for point within unit circle using sample-reject. // This will pass with probability π/4 = ~0.785. do{ x1 = uniformS(); x2 = uniformS(); w = x1 * x1 + x2 * x2; } while(w >= 1.f); // perform inverse Gaussian function mapping w = std::sqrt((-2.f * std::log(w)) / w); y1 = T(x1 * w); y2 = T(x2 * w); } // Fisher-Yates shuffle template <class RNG> template <class T> void Random<RNG>::shuffle(T * arr, uint32_t len){ for(uint32_t i=len-1; i>0; --i){ uint32_t j = uniform(i+1); T t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } } // al::rnd:: } // al:: #endif <|endoftext|>
<commit_before>#include "OpenCV.h" #include "Matrix.h" #include <nan.h> void OpenCV::Init(Local<Object> target) { Nan::HandleScope scope; // Version string. char out [21]; int n = sprintf(out, "%i.%i", CV_MAJOR_VERSION, CV_MINOR_VERSION); target->Set(Nan::New<String>("version").ToLocalChecked(), Nan::New<String>(out, n).ToLocalChecked()); Nan::SetMethod(target, "readImage", ReadImage); Nan::SetMethod(target, "readImageAsync", ReadImageAsync); Nan::SetMethod(target, "readImageMulti", ReadImageMulti); } // worker which decodes an image from data. class AsyncImDecodeWorker: public Nan::AsyncWorker { public: AsyncImDecodeWorker(Nan::Callback *callback, uint8_t *buf, unsigned len, int flags = -1): Nan::AsyncWorker(callback), buf(buf), len(len), flags(flags){ } ~AsyncImDecodeWorker() { } void Execute() { // Local<Object> img_to_return = // Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); // img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf); outputmat = cv::imdecode(*mbuf, flags); } void HandleOKCallback() { Nan::HandleScope scope; Local<Object> im_to_return= Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_to_return); img->mat = outputmat; Local<Value> argv[] = { Nan::Null(), im_to_return }; Nan::TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } private: uint8_t *buf; unsigned len; int flags; cv::Mat outputmat; //Matrix *img; }; // worker which reads an image from a file. class AsyncImReadWorker: public Nan::AsyncWorker { public: AsyncImReadWorker(Nan::Callback *callback, std::string filename, int flags = CV_LOAD_IMAGE_UNCHANGED): Nan::AsyncWorker(callback), filename(filename), flags(flags) { } ~AsyncImReadWorker() { } void Execute() { outputmat = cv::imread(filename, CV_LOAD_IMAGE_UNCHANGED); } void HandleOKCallback() { Nan::HandleScope scope; Local<Object> im_to_return= Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_to_return); img->mat = outputmat; Local<Value> argv[] = { Nan::Null(), im_to_return }; Nan::TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } private: std::string filename; int flags; cv::Mat outputmat; }; NAN_METHOD(OpenCV::ReadImageAsync) { Nan::EscapableHandleScope scope; Local<Value> argv[2]; argv[0] = Nan::Null(); argv[1] = Nan::Null(); int callback_arg = -1; int numargs = info.Length(); Local<Function> cb; // deal with situation where we have int, int, cb if (info[numargs-1]->IsFunction()){ callback_arg = numargs-1; cb = Local<Function>::Cast(info[callback_arg]); } try { if (info[0]->IsNumber() && info[1]->IsNumber()) { ////////////////////////////// // create image from a filename // always do sync as this take no time? int width, height; int type = CV_64FC1; // if we have a type arg if ((numargs > 2) && info[2]->IsNumber()){ type = info[2]->Uint32Value(); } width = info[0]->Uint32Value(); height = info[1]->Uint32Value(); Local<Object> img_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); img->mat = *(new cv::Mat(width, height, type)); if (callback_arg < 0){ info.GetReturnValue().Set(img_to_return); return; } else { argv[0] = Nan::Null(); argv[1] = img_to_return; cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); return; } // WILL have returned by here unless exception ////////////////////////////// } else if (info[0]->IsString()) { ////////////////////////////// // read image from a filename std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } if (callback_arg < 0){ Local<Object> img_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); img->mat = cv::imread(filename, flags); info.GetReturnValue().Set(img_to_return); return; } else { Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker(new AsyncImReadWorker(callback, filename, flags)); return; } // WILL have returned by here unless exception ////////////////////////////// } else if (Buffer::HasInstance(info[0])) { ////////////////////////////// // read image from a buffer // if sync int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } if (callback_arg < 0){ Local<Object> img_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject()); unsigned len = Buffer::Length(info[0]->ToObject()); cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf); img->mat = cv::imdecode(*mbuf, flags); info.GetReturnValue().Set(img_to_return); return; } else { // async uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject()); unsigned len = Buffer::Length(info[0]->ToObject()); Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker(new AsyncImDecodeWorker(callback, buf, len, flags)); return; } // WILL have returned by here unless exception ////////////////////////////// } } catch (cv::Exception& e) { argv[0] = Nan::Error(e.what()); argv[1] = Nan::Null(); } Nan::TryCatch try_catch; // if we got a callback if (callback_arg >= 0){ // if using callback cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); } else { // can only get here by exception info.GetReturnValue().Set(Nan::New<Boolean>(false)); } if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } NAN_METHOD(OpenCV::ReadImage) { Nan::EscapableHandleScope scope; Local<Value> argv[2]; argv[0] = Nan::Null(); Local<Object> im_h = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_h); argv[1] = im_h; int callback_arg = -1; int numargs = info.Length(); int success = 1; Local<Function> cb; // deal with situation where we have int, int, cb if (info[numargs-1]->IsFunction()){ callback_arg = numargs-1; cb = Local<Function>::Cast(info[callback_arg]); } try { cv::Mat mat; if (info[0]->IsNumber() && info[1]->IsNumber()) { int width, height; int type = CV_64FC1; // if we have a type arg if ((numargs > 2) && info[2]->IsNumber()){ type = info[2]->Uint32Value(); } width = info[0]->Uint32Value(); height = info[1]->Uint32Value(); mat = *(new cv::Mat(width, height, type)); } else if (info[0]->IsString()) { std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } mat = cv::imread(filename, flags); } else if (Buffer::HasInstance(info[0])) { uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject()); unsigned len = Buffer::Length(info[0]->ToObject()); int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf); mat = cv::imdecode(*mbuf, flags); if (mat.empty()) { success = 0; argv[0] = Nan::Error("Error loading file"); } } img->mat = mat; } catch (cv::Exception& e) { argv[0] = Nan::Error(e.what()); argv[1] = Nan::Null(); success = 0; } Nan::TryCatch try_catch; // if we got a callback if (callback_arg >= 0){ // if using callback cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); } else { // if to return the mat if (success) info.GetReturnValue().Set(im_h); else info.GetReturnValue().Set(Nan::New<Boolean>(false)); } if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } #if CV_MAJOR_VERSION >= 3 NAN_METHOD(OpenCV::ReadImageMulti) { Nan::EscapableHandleScope scope; REQ_FUN_ARG(1, cb); Local<Value> argv[2]; argv[0] = Nan::Null(); std::vector<cv::Mat> mats; try { if (info[0]->IsString()) { std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); cv::imreadmulti(filename, mats); if (mats.empty()) { argv[0] = Nan::Error("Error loading file"); } } } catch (cv::Exception& e) { argv[0] = Nan::Error(e.what()); argv[1] = Nan::Null(); } Local <Array> output = Nan::New<Array>(mats.size()); argv[1] = output; for (std::vector<cv::Mat>::size_type i = 0; i < mats.size(); i ++) { Local<Object> im_h = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_h); img->mat = mats[i]; output->Set(i, im_h); } Nan::TryCatch try_catch; cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } #else NAN_METHOD(OpenCV::ReadImageMulti) { info.GetReturnValue().Set(Nan::New<Boolean>(false)); return; } #endif <commit_msg>opencv:readimage Async - change newed mat to local class to try to prevent mem leak; also try-catch to signal failure through callback<commit_after>#include "OpenCV.h" #include "Matrix.h" #include <nan.h> void OpenCV::Init(Local<Object> target) { Nan::HandleScope scope; // Version string. char out [21]; int n = sprintf(out, "%i.%i", CV_MAJOR_VERSION, CV_MINOR_VERSION); target->Set(Nan::New<String>("version").ToLocalChecked(), Nan::New<String>(out, n).ToLocalChecked()); Nan::SetMethod(target, "readImage", ReadImage); Nan::SetMethod(target, "readImageAsync", ReadImageAsync); Nan::SetMethod(target, "readImageMulti", ReadImageMulti); } // worker which decodes an image from data. class AsyncImDecodeWorker: public Nan::AsyncWorker { public: AsyncImDecodeWorker(Nan::Callback *callback, uint8_t *buf, unsigned len, int flags = -1): Nan::AsyncWorker(callback), buf(buf), len(len), flags(flags), success(0){ } ~AsyncImDecodeWorker() { } void Execute() { try{ // don't new; just have a local class which will be removed. cv::Mat mbuf(len, 1, CV_64FC1, buf); outputmat = cv::imdecode(mbuf, flags); success = 1; } catch(...){ success = 0; } } void HandleOKCallback() { if (success){ Nan::HandleScope scope; try{ Local<Object> im_to_return= Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_to_return); img->mat = outputmat; Local<Value> argv[] = { Nan::Null(), im_to_return }; Nan::TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } catch (...){ } } // fall through here is !success or failed trying to callback. Local<Value> argv[] = { Nan::New("C++ exception executing imdecode").ToLocalChecked(), // err Nan::Null() }; Nan::TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } private: uint8_t *buf; unsigned len; int flags; cv::Mat outputmat; int success; //Matrix *img; }; // worker which reads an image from a file. class AsyncImReadWorker: public Nan::AsyncWorker { public: AsyncImReadWorker(Nan::Callback *callback, std::string filename, int flags = CV_LOAD_IMAGE_UNCHANGED): Nan::AsyncWorker(callback), filename(filename), flags(flags) { } ~AsyncImReadWorker() { } void Execute() { outputmat = cv::imread(filename, CV_LOAD_IMAGE_UNCHANGED); } void HandleOKCallback() { Nan::HandleScope scope; Local<Object> im_to_return= Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_to_return); img->mat = outputmat; Local<Value> argv[] = { Nan::Null(), im_to_return }; Nan::TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } private: std::string filename; int flags; cv::Mat outputmat; }; NAN_METHOD(OpenCV::ReadImageAsync) { Nan::EscapableHandleScope scope; Local<Value> argv[2]; argv[0] = Nan::Null(); argv[1] = Nan::Null(); int callback_arg = -1; int numargs = info.Length(); Local<Function> cb; // deal with situation where we have int, int, cb if (info[numargs-1]->IsFunction()){ callback_arg = numargs-1; cb = Local<Function>::Cast(info[callback_arg]); } try { if (info[0]->IsNumber() && info[1]->IsNumber()) { ////////////////////////////// // create image from a filename // always do sync as this take no time? int width, height; int type = CV_64FC1; // if we have a type arg if ((numargs > 2) && info[2]->IsNumber()){ type = info[2]->Uint32Value(); } width = info[0]->Uint32Value(); height = info[1]->Uint32Value(); Local<Object> img_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); img->mat = *(new cv::Mat(width, height, type)); if (callback_arg < 0){ info.GetReturnValue().Set(img_to_return); return; } else { argv[0] = Nan::Null(); argv[1] = img_to_return; cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); return; } // WILL have returned by here unless exception ////////////////////////////// } else if (info[0]->IsString()) { ////////////////////////////// // read image from a filename std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } if (callback_arg < 0){ Local<Object> img_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); img->mat = cv::imread(filename, flags); info.GetReturnValue().Set(img_to_return); return; } else { Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker(new AsyncImReadWorker(callback, filename, flags)); return; } // WILL have returned by here unless exception ////////////////////////////// } else if (Buffer::HasInstance(info[0])) { ////////////////////////////// // read image from a buffer // if sync int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } if (callback_arg < 0){ Local<Object> img_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(img_to_return); uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject()); unsigned len = Buffer::Length(info[0]->ToObject()); cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf); img->mat = cv::imdecode(*mbuf, flags); info.GetReturnValue().Set(img_to_return); return; } else { // async uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject()); unsigned len = Buffer::Length(info[0]->ToObject()); Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker(new AsyncImDecodeWorker(callback, buf, len, flags)); return; } // WILL have returned by here unless exception ////////////////////////////// } } catch (cv::Exception& e) { argv[0] = Nan::Error(e.what()); argv[1] = Nan::Null(); } Nan::TryCatch try_catch; // if we got a callback if (callback_arg >= 0){ // if using callback cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); } else { // can only get here by exception info.GetReturnValue().Set(Nan::New<Boolean>(false)); } if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } NAN_METHOD(OpenCV::ReadImage) { Nan::EscapableHandleScope scope; Local<Value> argv[2]; argv[0] = Nan::Null(); Local<Object> im_h = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_h); argv[1] = im_h; int callback_arg = -1; int numargs = info.Length(); int success = 1; Local<Function> cb; // deal with situation where we have int, int, cb if (info[numargs-1]->IsFunction()){ callback_arg = numargs-1; cb = Local<Function>::Cast(info[callback_arg]); } try { cv::Mat mat; if (info[0]->IsNumber() && info[1]->IsNumber()) { int width, height; int type = CV_64FC1; // if we have a type arg if ((numargs > 2) && info[2]->IsNumber()){ type = info[2]->Uint32Value(); } width = info[0]->Uint32Value(); height = info[1]->Uint32Value(); mat = *(new cv::Mat(width, height, type)); } else if (info[0]->IsString()) { std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } mat = cv::imread(filename, flags); } else if (Buffer::HasInstance(info[0])) { uint8_t *buf = (uint8_t *) Buffer::Data(info[0]->ToObject()); unsigned len = Buffer::Length(info[0]->ToObject()); int flags = CV_LOAD_IMAGE_UNCHANGED; if (numargs > 1){ if (info[1]->IsNumber()){ flags = info[1]->Uint32Value(); } } cv::Mat *mbuf = new cv::Mat(len, 1, CV_64FC1, buf); mat = cv::imdecode(*mbuf, flags); if (mat.empty()) { success = 0; argv[0] = Nan::Error("Error loading file"); } } img->mat = mat; } catch (cv::Exception& e) { argv[0] = Nan::Error(e.what()); argv[1] = Nan::Null(); success = 0; } Nan::TryCatch try_catch; // if we got a callback if (callback_arg >= 0){ // if using callback cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); } else { // if to return the mat if (success) info.GetReturnValue().Set(im_h); else info.GetReturnValue().Set(Nan::New<Boolean>(false)); } if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } #if CV_MAJOR_VERSION >= 3 NAN_METHOD(OpenCV::ReadImageMulti) { Nan::EscapableHandleScope scope; REQ_FUN_ARG(1, cb); Local<Value> argv[2]; argv[0] = Nan::Null(); std::vector<cv::Mat> mats; try { if (info[0]->IsString()) { std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); cv::imreadmulti(filename, mats); if (mats.empty()) { argv[0] = Nan::Error("Error loading file"); } } } catch (cv::Exception& e) { argv[0] = Nan::Error(e.what()); argv[1] = Nan::Null(); } Local <Array> output = Nan::New<Array>(mats.size()); argv[1] = output; for (std::vector<cv::Mat>::size_type i = 0; i < mats.size(); i ++) { Local<Object> im_h = Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked(); Matrix *img = Nan::ObjectWrap::Unwrap<Matrix>(im_h); img->mat = mats[i]; output->Set(i, im_h); } Nan::TryCatch try_catch; cb->Call(Nan::GetCurrentContext()->Global(), 2, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } return; } #else NAN_METHOD(OpenCV::ReadImageMulti) { info.GetReturnValue().Set(Nan::New<Boolean>(false)); return; } #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <vector> #include "Options.h" #include "capture.h" #include "xalt_config.h" #include "base64.h" double convert_double(const char* name, const char* s) { char *p; double v; v = strtod(s, &p); if (p == s || *p) { fprintf(stderr,"For option: \"%s\", unable to parse: \"%s\"\n", name, s); exit(1); } return v; } long convert_long(const char* name, const char* s) { char *p; long v; v = strtol(s, &p, 10); if (p == s || *p) { fprintf(stderr,"For option: \"%s\", unable to parse: \"%s\"\n", name, s); exit(1); } return v; } Options::Options(int argc, char** argv) : m_start(0.0), m_end(0.0), m_ntasks(1L), m_ngpus(0L), m_interfaceV(0L), m_ppid(0L), m_syshost("unknown"), m_uuid("unknown"), m_exec("unknown"), m_userCmdLine("[]"), m_exec_type("unknown"), m_confFn("xalt_db.conf") { int c; while(1) { int option_index = 0; static struct option long_options[] = { {"interfaceV", required_argument, NULL, 'V'}, {"start", required_argument, NULL, 's'}, {"end", required_argument, NULL, 'e'}, {"syshost", required_argument, NULL, 'h'}, {"exec", required_argument, NULL, 'x'}, {"ntasks", required_argument, NULL, 'n'}, {"ngpus", required_argument, NULL, 'g'}, {"uuid", required_argument, NULL, 'u'}, {"confFn", required_argument, NULL, 'c'}, {"ppid", required_argument, NULL, 'p'}, {"path", required_argument, NULL, 'P'}, {"prob", required_argument, NULL, 'b'}, {"ld_libpath", required_argument, NULL, 'L'}, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "c:s:e:h:x:n:g:u:p:P:L:", long_options, &option_index); if (c == -1) break; switch(c) { case 'V': if (optarg) m_interfaceV = (pid_t) convert_long("ppid", optarg); break; case 'p': if (optarg) m_ppid = (pid_t) convert_long("ppid", optarg); break; case 'b': if (optarg) m_probability = convert_double("prob", optarg); break; case 's': if (optarg) m_start = convert_double("start", optarg); break; case 'e': if (optarg) m_end = convert_double("end", optarg); break; case 'c': if (optarg) m_confFn = optarg; break; case 'h': if (optarg) m_syshost = optarg; break; case 'x': if (optarg) m_exec = optarg; break; case 'n': if (optarg) m_ntasks = convert_long("ntasks", optarg); break; case 'g': if (optarg) m_ngpus = convert_long("ngpus", optarg); break; case 'u': if (optarg) m_uuid = optarg; break; case 'P': if (optarg) m_path = optarg; break; case 'L': if (optarg) m_ldLibPath = optarg; break; case '?': printf("Huh?\n"); break; default: printf("?? getopt returned character code 0%o ??\n", c); } } if (optind + 1 == argc && argv[optind][0] == '[') m_userCmdLine = argv[optind]; else if (optind < argc) { if (m_interfaceV < 4) { m_userCmdLine = "["; for (int i = optind; i < argc; ++i) { m_userCmdLine += "\""; m_userCmdLine += argv[i]; m_userCmdLine += "\","; } if (m_userCmdLine.back() == ',') m_userCmdLine.replace(m_userCmdLine.size()-1,1,"]"); } else { int jLen; int len = strlen(argv[optind]); m_userCmdLine = reinterpret_cast<char*>(base64_decode(argv[optind], len, &jLen)); } } if (m_exec != "unknown") { std::vector<std::string> result; std::string cmd; cmd = PATH_TO_PRGM_FILE " " + m_exec; capture(cmd, result); if (result[0].find("script") != std::string::npos || result[0].find("text") != std::string::npos) m_exec_type = "script"; else m_exec_type = "binary"; } } <commit_msg>Free the generated c string from base64_decode()<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <vector> #include "Options.h" #include "capture.h" #include "xalt_config.h" #include "base64.h" double convert_double(const char* name, const char* s) { char *p; double v; v = strtod(s, &p); if (p == s || *p) { fprintf(stderr,"For option: \"%s\", unable to parse: \"%s\"\n", name, s); exit(1); } return v; } long convert_long(const char* name, const char* s) { char *p; long v; v = strtol(s, &p, 10); if (p == s || *p) { fprintf(stderr,"For option: \"%s\", unable to parse: \"%s\"\n", name, s); exit(1); } return v; } Options::Options(int argc, char** argv) : m_start(0.0), m_end(0.0), m_ntasks(1L), m_ngpus(0L), m_interfaceV(0L), m_ppid(0L), m_syshost("unknown"), m_uuid("unknown"), m_exec("unknown"), m_userCmdLine("[]"), m_exec_type("unknown"), m_confFn("xalt_db.conf") { int c; while(1) { int option_index = 0; static struct option long_options[] = { {"interfaceV", required_argument, NULL, 'V'}, {"start", required_argument, NULL, 's'}, {"end", required_argument, NULL, 'e'}, {"syshost", required_argument, NULL, 'h'}, {"exec", required_argument, NULL, 'x'}, {"ntasks", required_argument, NULL, 'n'}, {"ngpus", required_argument, NULL, 'g'}, {"uuid", required_argument, NULL, 'u'}, {"confFn", required_argument, NULL, 'c'}, {"ppid", required_argument, NULL, 'p'}, {"path", required_argument, NULL, 'P'}, {"prob", required_argument, NULL, 'b'}, {"ld_libpath", required_argument, NULL, 'L'}, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "c:s:e:h:x:n:g:u:p:P:L:", long_options, &option_index); if (c == -1) break; switch(c) { case 'V': if (optarg) m_interfaceV = (pid_t) convert_long("ppid", optarg); break; case 'p': if (optarg) m_ppid = (pid_t) convert_long("ppid", optarg); break; case 'b': if (optarg) m_probability = convert_double("prob", optarg); break; case 's': if (optarg) m_start = convert_double("start", optarg); break; case 'e': if (optarg) m_end = convert_double("end", optarg); break; case 'c': if (optarg) m_confFn = optarg; break; case 'h': if (optarg) m_syshost = optarg; break; case 'x': if (optarg) m_exec = optarg; break; case 'n': if (optarg) m_ntasks = convert_long("ntasks", optarg); break; case 'g': if (optarg) m_ngpus = convert_long("ngpus", optarg); break; case 'u': if (optarg) m_uuid = optarg; break; case 'P': if (optarg) m_path = optarg; break; case 'L': if (optarg) m_ldLibPath = optarg; break; case '?': printf("Huh?\n"); break; default: printf("?? getopt returned character code 0%o ??\n", c); } } if (optind + 1 == argc && argv[optind][0] == '[') m_userCmdLine = argv[optind]; else if (optind < argc) { if (m_interfaceV < 4) { m_userCmdLine = "["; for (int i = optind; i < argc; ++i) { m_userCmdLine += "\""; m_userCmdLine += argv[i]; m_userCmdLine += "\","; } if (m_userCmdLine.back() == ',') m_userCmdLine.replace(m_userCmdLine.size()-1,1,"]"); } else { int jLen; char* decoded = reinterpret_cast<char*>(base64_decode(argv[optind], strlen(argv[optind]), &jLen)); m_userCmdLine = decoded; free(decoded); } } if (m_exec != "unknown") { std::vector<std::string> result; std::string cmd; cmd = PATH_TO_PRGM_FILE " " + m_exec; capture(cmd, result); if (result[0].find("script") != std::string::npos || result[0].find("text") != std::string::npos) m_exec_type = "script"; else m_exec_type = "binary"; } } <|endoftext|>
<commit_before>/* * qmidi (QMidi.cpp) * Part of QMidi (http://github.com/waddlesplash/qtmidi). * * Copyright (c) 2012 WaddleSplash * * 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 "QMidi.h" #if defined(Q_OS_WIN) # include <windows.h> // MmSystem needs DWORD, etc. # include <mmsystem.h> // For MIDI In/Out on Win HMIDIOUT midiOutPtr; #elif defined(Q_OS_LINUX) # include <alsa/asoundlib.h> # include <alsa/seq.h> # include <alsa/seq_midi_event.h> # include <QStringList> snd_seq_t *midiOutPtr; #elif defined(Q_OS_HAIKU) # include <MidiConsumer.h> # include <MidiProducer.h> # include <MidiRoster.h> BMidiConsumer* midiOutConsumer; BMidiLocalProducer* midiOutLocProd; #endif // TODO: error reporting QString QMidi::myOutDeviceId; QMap<QString,QString> QMidi::outDeviceNames() { QMap<QString,QString> ret; #if defined(Q_OS_WIN) int numDevs = midiOutGetNumDevs(); if(numDevs == 0) { return ret; } for(int i = 0;i<numDevs;i++) { MIDIOUTCAPS* devCaps = new MIDIOUTCAPS; midiOutGetDevCaps(i,devCaps,sizeof(*devCaps)); ret.insert(QString::number(i),QString::fromWCharArray(devCaps->szPname)); delete devCaps; } #elif defined(Q_OS_LINUX) snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; int client; int err; snd_seq_t *handle; err = snd_seq_open(&handle, "hw", SND_SEQ_OPEN_DUPLEX, 0); if(err < 0) { /* Could not open sequencer!! use snd_strerror(errno) to get error. */ return ret; } snd_seq_client_info_alloca(&cinfo); snd_seq_client_info_set_client(cinfo, -1); while(snd_seq_query_next_client(handle, cinfo) >= 0) { client = snd_seq_client_info_get_client(cinfo); snd_seq_port_info_alloca(&pinfo); snd_seq_port_info_set_client(pinfo, client); snd_seq_port_info_set_port(pinfo, -1); while(snd_seq_query_next_port(handle, pinfo) >= 0) { int cap = (SND_SEQ_PORT_CAP_SUBS_WRITE|SND_SEQ_PORT_CAP_WRITE); if((snd_seq_port_info_get_capability(pinfo) & cap) == cap) { QString port = QString::number(snd_seq_port_info_get_client(pinfo)); port += ":" + QString::number(snd_seq_port_info_get_port(pinfo)); QString name = snd_seq_client_info_get_name(cinfo); ret.insert(port,name); } } } #elif defined(Q_OS_HAIKU) bool OK = true; int32 id = 0; while(OK) { BMidiConsumer* c = BMidiRoster::NextConsumer(&id); if(c != NULL) { ret.insert(QString::number(id),QString::fromUtf8(c->Name())); c->Release(); } else { OK = false; } } #endif return ret; } bool QMidi::initMidiOut(QString outDeviceId) { #if defined(Q_OS_WIN) midiOutOpen(&midiOutPtr,outDeviceId.toInt(),0,0,CALLBACK_NULL); #elif defined(Q_OS_LINUX) int err = snd_seq_open(&midiOutPtr, "default", SND_SEQ_OPEN_OUTPUT, 0); if(err < 0) { return false; } snd_seq_set_client_name(midiOutPtr, "QtMidi"); snd_seq_create_simple_port(midiOutPtr, "Output Port", SND_SEQ_PORT_CAP_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC); QStringList l = outDeviceId.split(":"); int client = l.at(0).toInt(); int port = l.at(1).toInt(); snd_seq_connect_to(midiOutPtr, 0, client, port); #elif defined(Q_OS_HAIKU) midiOutConsumer = BMidiRoster::FindConsumer(outDeviceId.toInt()); if(midiOutConsumer == NULL) { return false; } midiOutLocProd = new BMidiLocalProducer("QtMidi"); if(!midiOutLocProd->IsValid()) { midiOutLocProd->Release(); return false; } // some error ?? midiOutLocProd->Register(); if(midiOutLocProd->Connect(midiOutConsumer) != B_OK) { return false; } #endif myOutDeviceId = outDeviceId; return true; } void QMidi::closeMidiOut() { #if defined(Q_OS_WIN) midiOutClose(midiOutPtr); #elif defined(Q_OS_LINUX) QStringList l = myOutDeviceId.split(":"); int client = l.at(0).toInt(); int port = l.at(1).toInt(); snd_seq_disconnect_from(midiOutPtr, 0, client,port); #elif defined(Q_OS_HAIKU) midiOutLocProd->Disconnect(midiOutConsumer); midiOutConsumer->Release(); midiOutLocProd->Unregister(); midiOutLocProd->Release(); #endif } void QMidi::outSendMsg(qint32 msg) { #if defined(Q_OS_WIN) midiOutShortMsg(midiOutPtr,(DWORD)msg); #elif defined(Q_OS_LINUX) snd_seq_event_t ev; snd_midi_event_t* mev; snd_seq_ev_clear(&ev); snd_seq_ev_set_source(&ev, 0); snd_seq_ev_set_subs(&ev); snd_seq_ev_set_direct(&ev); snd_midi_event_new(sizeof(msg), &mev); snd_midi_event_resize_buffer(mev, sizeof(msg)); snd_midi_event_encode(mev,(unsigned char*)&msg, sizeof(msg), &ev); snd_seq_event_output(midiOutPtr, &ev); snd_seq_drain_output(midiOutPtr); #elif defined(Q_OS_HAIKU) midiOutLocProd->SprayData((void*)&msg,sizeof(msg),true); #endif } void QMidi::outSetInstr(int voice, int instr) { qint32 msg = 0x0000C0 + voice; msg |= instr<<8; outSendMsg(msg); } void QMidi::outNoteOn(int note, int voice, int velocity) { qint32 msg = 0x90 + voice; msg |= note<<8; msg |= velocity<<16; outSendMsg(msg); } void QMidi::outNoteOff(int note, int voice) { qint32 msg = 0x80 + voice; msg |= note<<8; outSendMsg(msg); } void QMidi::outPitchWheel(int voice, int value) { qint32 msg = 0xE0 + voice; msg |= (value & 0x7F)<<8; // fine adjustment msg |= (value / 128)<<16; // coarse adjustment outSendMsg(msg); } void QMidi::outControlChange(int voice, int number, int value) { qint32 msg = 0xB0 + voice; msg |= (number)<<8; msg |= (value)<<16; outSendMsg(msg); } void QMidi::outStopAll() { for(int i = 0;i<16;i++) { outStopAll(i); } } void QMidi::outStopAll(int voice) { outSendMsg((0xB0 | voice) | (0x7B<<8)); } <commit_msg>Make some fixes to output.<commit_after>/* * qmidi (QMidi.cpp) * Part of QMidi (http://github.com/waddlesplash/qtmidi). * * Copyright (c) 2012 WaddleSplash * * 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 "QMidi.h" #if defined(Q_OS_WIN) # include <windows.h> // MmSystem needs DWORD, etc. # include <mmsystem.h> // For MIDI In/Out on Win HMIDIOUT midiOutPtr; #elif defined(Q_OS_LINUX) # include <alsa/asoundlib.h> # include <alsa/seq.h> # include <alsa/seq_midi_event.h> # include <QStringList> snd_seq_t *midiOutPtr; #elif defined(Q_OS_HAIKU) # include <MidiConsumer.h> # include <MidiProducer.h> # include <MidiRoster.h> BMidiConsumer* midiOutConsumer; BMidiLocalProducer* midiOutLocProd; #endif // TODO: error reporting QString QMidi::myOutDeviceId; QMap<QString,QString> QMidi::outDeviceNames() { QMap<QString,QString> ret; #if defined(Q_OS_WIN) int numDevs = midiOutGetNumDevs(); if(numDevs == 0) { return ret; } for(int i = 0;i<numDevs;i++) { MIDIOUTCAPS* devCaps = new MIDIOUTCAPS; midiOutGetDevCaps(i,devCaps,sizeof(*devCaps)); ret.insert(QString::number(i),QString::fromWCharArray(devCaps->szPname)); delete devCaps; } #elif defined(Q_OS_LINUX) snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; int client; int err; snd_seq_t *handle; err = snd_seq_open(&handle, "hw", SND_SEQ_OPEN_DUPLEX, 0); if(err < 0) { /* Could not open sequencer!! use snd_strerror(errno) to get error. */ return ret; } snd_seq_client_info_alloca(&cinfo); snd_seq_client_info_set_client(cinfo, -1); while(snd_seq_query_next_client(handle, cinfo) >= 0) { client = snd_seq_client_info_get_client(cinfo); snd_seq_port_info_alloca(&pinfo); snd_seq_port_info_set_client(pinfo, client); snd_seq_port_info_set_port(pinfo, -1); while(snd_seq_query_next_port(handle, pinfo) >= 0) { int cap = (SND_SEQ_PORT_CAP_SUBS_WRITE|SND_SEQ_PORT_CAP_WRITE); if((snd_seq_port_info_get_capability(pinfo) & cap) == cap) { QString port = QString::number(snd_seq_port_info_get_client(pinfo)); port += ":" + QString::number(snd_seq_port_info_get_port(pinfo)); QString name = snd_seq_client_info_get_name(cinfo); ret.insert(port,name); } } } #elif defined(Q_OS_HAIKU) bool OK = true; int32 id = 0; while(OK) { BMidiConsumer* c = BMidiRoster::NextConsumer(&id); if(c != NULL) { ret.insert(QString::number(id),QString::fromUtf8(c->Name())); c->Release(); } else { OK = false; } } #endif return ret; } bool QMidi::initMidiOut(QString outDeviceId) { #if defined(Q_OS_WIN) midiOutOpen(&midiOutPtr,outDeviceId.toInt(),0,0,CALLBACK_NULL); #elif defined(Q_OS_LINUX) int err = snd_seq_open(&midiOutPtr, "default", SND_SEQ_OPEN_OUTPUT, 0); if(err < 0) { return false; } snd_seq_set_client_name(midiOutPtr, "QtMidi"); snd_seq_create_simple_port(midiOutPtr, "Output Port", SND_SEQ_PORT_CAP_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC); QStringList l = outDeviceId.split(":"); int client = l.at(0).toInt(); int port = l.at(1).toInt(); snd_seq_connect_to(midiOutPtr, 0, client, port); #elif defined(Q_OS_HAIKU) midiOutConsumer = BMidiRoster::FindConsumer(outDeviceId.toInt()); if(midiOutConsumer == NULL) { return false; } midiOutLocProd = new BMidiLocalProducer("QtMidi"); if(!midiOutLocProd->IsValid()) { midiOutLocProd->Release(); return false; } // some error ?? midiOutLocProd->Register(); if(midiOutLocProd->Connect(midiOutConsumer) != B_OK) { return false; } #endif myOutDeviceId = outDeviceId; return true; } void QMidi::closeMidiOut() { #if defined(Q_OS_WIN) midiOutClose(midiOutPtr); #elif defined(Q_OS_LINUX) QStringList l = myOutDeviceId.split(":"); int client = l.at(0).toInt(); int port = l.at(1).toInt(); snd_seq_disconnect_from(midiOutPtr, 0, client,port); #elif defined(Q_OS_HAIKU) midiOutLocProd->Disconnect(midiOutConsumer); midiOutConsumer->Release(); midiOutLocProd->Unregister(); midiOutLocProd->Release(); #endif } void QMidi::outSendMsg(qint32 msg) { #if !defined(Q_OS_WIN) char buf[3]; buf[0] = msg & 0xFF; buf[1] = (msg >> 8) & 0xFF; buf[2] = (msg >> 16) & 0xFF; #endif #if defined(Q_OS_WIN) midiOutShortMsg(midiOutPtr,(DWORD)msg); #elif defined(Q_OS_LINUX) snd_seq_event_t ev; snd_midi_event_t* mev; snd_seq_ev_clear(&ev); snd_seq_ev_set_source(&ev, 0); snd_seq_ev_set_subs(&ev); snd_seq_ev_set_direct(&ev); snd_midi_event_new(3, &mev); snd_midi_event_resize_buffer(mev, 3); snd_midi_event_encode(mev,(unsigned char*)&buf, 3, &ev); snd_seq_event_output(midiOutPtr, &ev); snd_seq_drain_output(midiOutPtr); #elif defined(Q_OS_HAIKU) midiOutLocProd->SprayData((void*)&buf,3,true); #endif } void QMidi::outSetInstr(int voice, int instr) { qint32 msg = 0x0000C0 + voice; msg |= instr<<8; outSendMsg(msg); } void QMidi::outNoteOn(int note, int voice, int velocity) { qint32 msg = 0x90 + voice; msg |= note<<8; msg |= velocity<<16; outSendMsg(msg); } void QMidi::outNoteOff(int note, int voice) { qint32 msg = 0x80 + voice; msg |= note<<8; outSendMsg(msg); } void QMidi::outPitchWheel(int voice, int value) { qint32 msg = 0xE0 + voice; msg |= (value & 0x7F)<<8; // fine adjustment msg |= (value / 128)<<16; // coarse adjustment outSendMsg(msg); } void QMidi::outControlChange(int voice, int number, int value) { qint32 msg = 0xB0 + voice; msg |= (number)<<8; msg |= (value)<<16; outSendMsg(msg); } void QMidi::outStopAll() { for(int i = 0;i<16;i++) { outStopAll(i); } } void QMidi::outStopAll(int voice) { outSendMsg((0xB0 | voice) | (0x7B<<8)); } <|endoftext|>
<commit_before>#include <string> #include "PCLink.hpp" PCLink::PCLink(void) : usbLink(64, 64, RJ_VENDOR_ID, RJ_PRODUCT_ID, RJ_RELEASE) {} PCLink::PCLink(uint16_t vendorID = RJ_VENDOR_ID, uint16_t productID = RJ_PRODUCT_ID, uint16_t release = RJ_RELEASE) : usbLink(64, 64, vendorID, productID, release) { pc = NULL; } PCLink::~PCLink(void) { // delete usbLink; } void PCLink::setSerialDebugging(Serial *pc) { this->pc = pc; } void PCLink::setLed(DigitalOut *led) { this->led = led; } void PCLink::read(void) { if (usbLink.readNB(&in)) { *led = !(*led); switch (in.data[0]) { case HID_FWD_GLOB_PKT: //set pkt data break; case HID_FWD_GLOB_TX: //tx pkt data break; case HID_FWD_BOT_TUNE_PKT: //set tune data break; case HID_FWD_BOT_TUNE_TX: //tx tune data break; case HID_FWD_ } if (pc != NULL) { // std::string tmp(reinterpret_cast<const char *>(in.data)); // tmp = tmp.append("\r\n"); // pc->printf("%s", tmp.c_str()); pc->printf("%d\r\n", in.data[0]); } } } void PCLink::reply(void) { usbLink.sendNB(&out); }<commit_msg>cleaned up PCLink.cpp<commit_after>#include <string> #include "PCLink.hpp" PCLink::PCLink(void) : usbLink(64, 64, RJ_VENDOR_ID, RJ_PRODUCT_ID, RJ_RELEASE) {} PCLink::PCLink(uint16_t vendorID = RJ_VENDOR_ID, uint16_t productID = RJ_PRODUCT_ID, uint16_t release = RJ_RELEASE) : usbLink(64, 64, vendorID, productID, release) { pc = NULL; } PCLink::~PCLink(void) { // delete usbLink; } void PCLink::setSerialDebugging(Serial *pc) { this->pc = pc; } void PCLink::setLed(DigitalOut *led) { this->led = led; } void PCLink::read(void) { if (usbLink.readNB(&in)) { *led = !(*led); if (pc != NULL) { pc->printf("%d\r\n", in.data[0]); } } } void PCLink::reply(void) { usbLink.sendNB(&out); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> using namespace std; void separatearg(vector<char* > &flags, vector<char* > &dirfiles, int argc, char** argv); void printarg(vector<char* > flags, vector<char* > dirfiles); //FOR error checking int checkflags(vector<char* > flags); int flagset(char flag); void opendirfile(char* dirfile, int flags); int main(int argc, char** argv) { if(argc<=1) { //if true, then no flags passed in cout << "No flags" << endl; //TEMPORARY //RUN ls on . directory char currentdir[] = "."; opendirfile(currentdir, 0); } else { vector<char* > flagsvec; vector<char* > dirfiles; separatearg(flagsvec, dirfiles, argc, argv); //printarg(flags,dirfiles); if(dirfiles.empty()) { //THEN check flags -> run ls on . directory int flags = checkflags(flagsvec); char currentdir[] = "."; opendirfile(currentdir, flags); } else { //THEN check flags -> run ls on files stated int flags = checkflags(flagsvec); for(unsigned int i=0; i<dirfiles.size(); ++i) { opendirfile(dirfiles[i], flags); } } } return 0; } void separatearg(vector<char* > &flags, vector<char* > &dirfiles, int argc, char** argv) { for(int i=1; i<argc; ++i) { cout << "The arguement is " << argv[i] << endl; if(argv[i][0]=='-') { flags.push_back(argv[i]); } else { dirfiles.push_back(argv[i]); } } } void printarg(vector<char* > flags, vector<char* > dirfiles) { cout << "flags: "; for(unsigned int i=0; i<flags.size(); ++i) { cout << flags[i] << " "; } cout << endl; cout << "dirfiles: "; for(unsigned int i=0; i<dirfiles.size(); ++i) { cout << dirfiles[i] << " "; } cout << endl; } int checkflags(vector<char* > flags) { int out = 0; if(flags.empty()) { return out; } else{ for(unsigned int i=0; i<flags.size(); ++i) { for(unsigned int j=1; flags[i][j]!=0; ++j) { out = out | flagset(flags[i][j]); } } } cout << "flags: " << out << endl; return out; } int flagset(char flag) { int out = 0; if(flag=='a') { out = out | 01; } else if(flag=='l') { out = out | 02; } else if(flag=='R') { out = out | 04; } else { cout << "Invalid option -- '" << flag << "'" << endl; } return out; } void opendirfile(char* dirfile, int flags) { } <commit_msg>can now use ls by itself, with other files and with -a<commit_after>#include <iostream> #include <vector> #include <dirent.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <iomanip> #include <algorithm> #include <string> #include <cctype> using namespace std; void separatearg(vector<char* > &flags, vector<char* > &dirfiles, int argc, char** argv); void printarg(vector<char* > flags, vector<char* > dirfiles); //FOR error checking int checkflags(vector<char* > flags); int flagset(char flag); void opendirfile(char* dirfile, int flags); int main(int argc, char** argv) { if(argc<=1) { //if true, then no flags passed in cout << "No flags" << endl; //TEMPORARY //RUN ls on . directory char currentdir[] = "."; opendirfile(currentdir, 0); } else { vector<char* > flagsvec; vector<char* > dirfiles; separatearg(flagsvec, dirfiles, argc, argv); //printarg(flags,dirfiles); if(dirfiles.empty()) { //THEN check flags -> run ls on . directory int flags = checkflags(flagsvec); char currentdir[] = "."; opendirfile(currentdir, flags); } else { //THEN check flags -> run ls on files stated int flags = checkflags(flagsvec); for(unsigned int i=0; i<dirfiles.size(); ++i) { opendirfile(dirfiles[i], flags); } } } return 0; } void separatearg(vector<char* > &flags, vector<char* > &dirfiles, int argc, char** argv) { for(int i=1; i<argc; ++i) { cout << "The arguement is " << argv[i] << endl; if(argv[i][0]=='-') { flags.push_back(argv[i]); } else { dirfiles.push_back(argv[i]); } } } void printarg(vector<char* > flags, vector<char* > dirfiles) { cout << "flags: "; for(unsigned int i=0; i<flags.size(); ++i) { cout << flags[i] << " "; } cout << endl; cout << "dirfiles: "; for(unsigned int i=0; i<dirfiles.size(); ++i) { cout << dirfiles[i] << " "; } cout << endl; } int checkflags(vector<char* > flags) { int out = 0; if(flags.empty()) { return out; } else{ for(unsigned int i=0; i<flags.size(); ++i) { for(unsigned int j=1; flags[i][j]!=0; ++j) { out = out | flagset(flags[i][j]); } } } cout << "flags: " << out << endl; return out; } int flagset(char flag) { int out = 0; if(flag=='a') { out = out | 01; } else if(flag=='l') { out = out | 02; } else if(flag=='R') { out = out | 04; } else { cout << "Invalid option -- '" << flag << "'" << endl; } return out; } //bool cstrcomp(const char* a, const char* b) { // char const** char_a = a; // char const** char_b = b; //return ((strcmp(a, b)<0) ? false : true); //} bool stringcomp(string a, string b) { for(unsigned int i=0; i<a.size() && i<b.size(); ++i) { if(tolower(b[i]) < tolower(a[i])) { return false; } else if(tolower(a[i]) < tolower(b[i])) { return true; } } if(b.size() < a.size()) { return false; } else { return true; } } void opendirfile(char* dirfile, int flags) { DIR* dirp; if(NULL == (dirp = opendir(dirfile))) { perror("Error with opendir(). "); exit(1); } struct dirent *filespecs; vector<string> list; unsigned char maxlen = 0; errno = 0; while(NULL != (filespecs = readdir(dirp))) { if((filespecs->d_name[0]!='.') || (flags & 01)) { //checks flag a list.push_back(filespecs->d_name); if(maxlen < strlen(filespecs->d_name)) { maxlen = strlen(filespecs->d_name); } } } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } maxlen += 3; sort(list.begin(), list.end(), stringcomp); unsigned int linewidth = 0; cout << left; if(flags & 02) { //checks -l flag //OUTPUT WITH -l STYLE } else { for(unsigned int i=0; i<list.size(); ++i) { linewidth += maxlen; if(linewidth > 80) { cout << "\n"; linewidth = 0; } cout << setw(maxlen) << list[i]; } cout << endl; } if(flags & 04) { //checks -R flag //DO -R THINGS for(unsigned int i=0; i<list.size(); ++i) { if(list[i]!="." && list[i]!="..") { if(S_ISDIR) { opendir(list[i]); } } } if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } } <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <pwd.h> #include <grp.h> #include <errno.h> #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <cstring> #define FLAG_a 1 #define FLAG_R 2 #define FLAG_l 4 #define PERMISSION(x, y) \ if (sb.st_mode & x) \ {cout << y;} \ else {cout << '-';} #define PER(x) PERMISSION(S_IR##x, 'r') PERMISSION(S_IW##x, 'w') \ PERMISSION(S_IX##x, 'x') #define ALL_PER() PER(USR) PER(GRP) PER(OTH) using namespace std; //for directories, it is ordered by alphabet and //by path, not foldername bool ledir(char* left, char* right) { //FIXME return true; } bool lefile(char* left, char* right) { //FIXME return true; } void merge(vector<char*>& vec, int mid) { vector<char*> temp(vec.size()); int i = 0; unsigned j = mid; unsigned index = 0; while(i < mid && j < vec.size()) { if (strcmp(vec.at(i), vec.at(j)) <= 0) { temp.at(index) = vec.at(i); ++i; } else { temp.at(index) = vec.at(j); ++j; } ++index; } while(i < mid) { temp.at(index) = vec.at(i); ++i; ++index; } while(j < vec.size()) { temp.at(index) = vec.at(j); ++j; ++index; } vec = temp; return; } void merge_sort(vector<char*>& vec, int begin, int end) { if (begin == end) { return; } int mid = (begin + end)/2; merge_sort(vec, begin, mid); merge_sort(vec, mid + 1, end); merge(vec, mid + 1); } int setFlag(int argc, char* argv[], vector<char*>& d, vector<char*>& f, int& a) { int flag = 0; struct stat sb; char* temp; for (int i = 1; i < argc; ++i) { if (argv[i][0] != '-') { int err = stat(argv[i], &sb); if (err == -1) { cerr << "ls: cannot access " << argv[i] << ": No such file or directory" << endl; } else { temp = new char[strlen(argv[i]) + 1]; strcpy(temp, argv[i]); if (S_ISDIR(sb.st_mode)) { d.push_back(temp); } else { f.push_back(temp); } } continue; } for (int j = 1; argv[i][j]; ++j) { if (argv[i][j] == 'R') { flag = flag | FLAG_R; } else if (argv[i][j] == 'l') { flag = flag | FLAG_l; } else if (argv[i][j] == 'a') { flag = flag | FLAG_a; } else { cerr << "ls: invalid option -- '" << argv[i][j] << "'" << endl; exit(1); } } a++; } return flag; } void outnorm(const vector<char*>& files, const char* dir, const int& flags) { if (flags & FLAG_R) { if (dir[strlen(dir) - 1] == '/') { for (unsigned i = 0; i < strlen(dir) - 1; ++i) { cout << dir[i]; } } else { cout << dir; } cout << ":" << endl << endl; } for (unsigned i = 0; i < files.size() ; ++i) { cout << files.at(i) << endl; } //int columns; return; } void outLong(const vector<char*>& files, const char* dir, const int& flags, const int& total) { struct stat sb; char* path; cout << "total " << total/2 << endl; //i have no idea why this is twice //the value ls gives for(unsigned i = 0; i < files.size(); ++i) { path = new char[strlen(files.at(i)) + strlen(dir) + 2]; strcpy(path, dir); if (dir[strlen(dir) - 1] != '/') { char temp[] = "/"; strcat(path, temp); } strcat(path, files.at(i)); int err = lstat(path, &sb); if (err != 0) { perror("stat"); exit(1); } if (S_ISLNK(sb.st_mode)) { cout << 'l'; } else if (S_ISDIR(sb.st_mode)) { cout << 'd'; } else { cout << '-'; } ALL_PER() cout << ' '; cout << sb.st_nlink << ' '; struct passwd *pw = getpwuid(sb.st_uid); if (pw == NULL) { perror("getpwuid"); exit(1); } cout << pw->pw_name; cout << '\t'; struct group *gr = getgrgid(sb.st_gid); if (gr == NULL) { perror("getgrgid"); exit(1); } cout << gr->gr_name; cout << '\t'; cout << sb.st_size; cout << '\t'; struct tm* ptm = gmtime( &sb.st_mtime); string tim = asctime(ptm); cout << tim.substr(4, 12) << ' '; cout << files.at(i); cout << endl; delete [] path; } return; } void ls(int flags, vector<char*>& dir) { for(unsigned i = 0; i < dir.size(); ++i) { vector<char*> dir_r; vector<char*> s; int total_block = 0; struct stat sb; DIR *dirp = opendir(dir.at(i)); if (dirp == 0) { perror("opendir"); exit(1); } dirent *direntp; while((direntp = readdir(dirp))) { char* f = direntp->d_name; char* file; char* directory; if (!(flags & FLAG_a) && *f == '.') { continue; } if (flags & FLAG_R && strncmp(f, "..", 3) == 0) { continue; } file = new char[strlen(f) + 1]; strcpy(file, f); directory = new char[strlen(file) + strlen(dir.at(i)) + 2]; strcpy(directory, dir.at(i)); strcat(directory, "/"); strcat(directory, file); if (lstat(directory, &sb) != 0) { perror("lstat"); exit(1); } total_block += sb.st_blocks; if (flags & FLAG_R && S_ISDIR(sb.st_mode)) { dir_r.push_back(directory); } else { delete [] directory; } //cout << "FIle: " << file << endl; s.push_back(file); } if (errno != 0) { perror("readdir"); exit(1); } if (closedir(dirp) != 0) { perror("closedir"); exit(1); } //cout << "===================================" << endl; //for (int j = s.size() - 1; j >= 0; --j) // { // cout << s.at(j) << endl; // } cout << "===================================" << endl; //merge_sort(s, 0, s.size()); //merge_sort(dir_r, 0, dir_r.size()); /*cout << "==========================" << endl; for (int j = s.size() - 1; j >= 0; --j) { cout << s.at(j) << endl; }*/ if (flags & FLAG_l) { outLong(s, dir.at(i), flags, total_block); } else { outnorm(s, dir.at(i), flags); } for (unsigned i = 0; i < s.size(); ++i) { if (s.at(i) != 0) { delete [] s.at(i); } } if (flags & FLAG_R && dir_r.size() != 0) { ls(flags, dir_r); } /*for (unsigned i = 0; i < dir_r.size(); ++i) { cout << dir_r.at(i) << endl; if (dir_r.at(i) != 0) { delete [] dir_r.at(i); } }*/ } for (unsigned i = 0; i < dir.size(); ++i) { if (dir.at(i) != 0) { delete [] dir.at(i); } } } int main(int argc, char* argv[]) { int a = 0; vector<char*> dirs; vector<char*> files; int flags = setFlag(argc, argv, dirs, files, a); if (dirs.size() == 0 && files.size() == 0 && argc - a == 1) { char* d = new char[2]; strcpy(d, "."); dirs.push_back(d); } ls(flags, dirs); return 0; } <commit_msg>testing<commit_after>#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <pwd.h> #include <grp.h> #include <errno.h> #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <cstring> #define FLAG_a 1 #define FLAG_R 2 #define FLAG_l 4 #define PERMISSION(x, y) \ if (sb.st_mode & x) \ {cout << y;} \ else {cout << '-';} #define PER(x) PERMISSION(S_IR##x, 'r') PERMISSION(S_IW##x, 'w') \ PERMISSION(S_IX##x, 'x') #define ALL_PER() PER(USR) PER(GRP) PER(OTH) using namespace std; //for directories, it is ordered by alphabet and //by path, not foldername bool ledir(char* left, char* right) { //FIXME return true; } bool lefile(char* left, char* right) { //FIXME return true; } void merge(vector<char*>& vec, int mid) { vector<char*> temp(vec.size()); int i = 0; unsigned j = mid; unsigned index = 0; while(i < mid && j < vec.size()) { if (strcmp(vec.at(i), vec.at(j)) <= 0) { temp.at(index) = vec.at(i); ++i; } else { temp.at(index) = vec.at(j); ++j; } ++index; } while(i < mid) { temp.at(index) = vec.at(i); ++i; ++index; } while(j < vec.size()) { temp.at(index) = vec.at(j); ++j; ++index; } vec = temp; return; } void merge_sort(vector<char*>& vec, int begin, int end) { if (begin == end) { return; } int mid = (begin + end)/2; merge_sort(vec, begin, mid); merge_sort(vec, mid + 1, end); merge(vec, mid + 1); } int setFlag(int argc, char* argv[], vector<char*>& d, vector<char*>& f, int& a) { int flag = 0; struct stat sb; char* temp; for (int i = 1; i < argc; ++i) { if (argv[i][0] != '-') { int err = stat(argv[i], &sb); if (err == -1) { cerr << "ls: cannot access " << argv[i] << ": No such file or directory" << endl; } else { temp = new char[strlen(argv[i]) + 1]; strcpy(temp, argv[i]); if (S_ISDIR(sb.st_mode)) { d.push_back(temp); } else { f.push_back(temp); } } continue; } for (int j = 1; argv[i][j]; ++j) { if (argv[i][j] == 'R') { flag = flag | FLAG_R; } else if (argv[i][j] == 'l') { flag = flag | FLAG_l; } else if (argv[i][j] == 'a') { flag = flag | FLAG_a; } else { cerr << "ls: invalid option -- '" << argv[i][j] << "'" << endl; exit(1); } } a++; } return flag; } void outnorm(const vector<char*>& files, const char* dir, const int& flags) { if (flags & FLAG_R) { if (dir[strlen(dir) - 1] == '/') { for (unsigned i = 0; i < strlen(dir) - 1; ++i) { cout << dir[i]; } } else { cout << dir; } cout << ":" << endl << endl; } for (unsigned i = 0; i < files.size() ; ++i) { cout << files.at(i) << endl; } //int columns; return; } void outLong(const vector<char*>& files, const char* dir, const int& flags, const int& total) { struct stat sb; char* path; cout << "total " << total/2 << endl; //i have no idea why this is twice //the value ls gives for(unsigned i = 0; i < files.size(); ++i) { path = new char[strlen(files.at(i)) + strlen(dir) + 2]; strcpy(path, dir); if (dir[strlen(dir) - 1] != '/') { char temp[] = "/"; strcat(path, temp); } strcat(path, files.at(i)); int err = lstat(path, &sb); if (err != 0) { perror("stat"); exit(1); } if (S_ISLNK(sb.st_mode)) { cout << 'l'; } else if (S_ISDIR(sb.st_mode)) { cout << 'd'; } else { cout << '-'; } ALL_PER() cout << ' '; cout << sb.st_nlink << ' '; struct passwd *pw = getpwuid(sb.st_uid); if (pw == NULL) { perror("getpwuid"); exit(1); } cout << pw->pw_name; cout << '\t'; struct group *gr = getgrgid(sb.st_gid); if (gr == NULL) { perror("getgrgid"); exit(1); } cout << gr->gr_name; cout << '\t'; cout << sb.st_size; cout << '\t'; struct tm* ptm = gmtime( &sb.st_mtime); string tim = asctime(ptm); cout << tim.substr(4, 12) << ' '; cout << files.at(i); cout << endl; delete [] path; } return; } void ls(int flags, vector<char*>& dir) { for(unsigned i = 0; i < dir.size(); ++i) { vector<char*> dir_r; vector<char*> s; int total_block = 0; struct stat sb; DIR *dirp = opendir(dir.at(i)); if (dirp == 0) { perror("opendir"); exit(1); } dirent *direntp; while((direntp = readdir(dirp))) { char* f = direntp->d_name; char* file; char* directory; if (!(flags & FLAG_a) && *f == '.') { continue; } if (flags & FLAG_R && strncmp(f, "..", 3) == 0) { continue; } file = new char[strlen(f) + 1]; strcpy(file, f); directory = new char[strlen(file) + strlen(dir.at(i)) + 2]; strcpy(directory, dir.at(i)); strcat(directory, "/"); strcat(directory, file); if (lstat(directory, &sb) != 0) { perror("lstat"); exit(1); } total_block += sb.st_blocks; if (flags & FLAG_R && S_ISDIR(sb.st_mode)) { dir_r.push_back(directory); } else { delete [] directory; } //cout << "FIle: " << file << endl; s.push_back(file); } if (errno != 0) { perror("readdir"); exit(1); } if (closedir(dirp) != 0) { perror("closedir"); exit(1); } //cout << "===================================" << endl; //for (int j = s.size() - 1; j >= 0; --j) // { // cout << s.at(j) << endl; // } cout << "===================================" << endl; //merge_sort(s, 0, s.size()); //merge_sort(dir_r, 0, dir_r.size()); /*cout << "==========================" << endl; for (int j = s.size() - 1; j >= 0; --j) { cout << s.at(j) << endl; }*/ if (flags & FLAG_l) { outLong(s, dir.at(i), flags, total_block); } else { outnorm(s, dir.at(i), flags); } for (unsigned i = 0; i < s.size(); ++i) { if (s.at(i) != 0) { delete [] s.at(i); } } if (flags & FLAG_R && dir_r.size() != 0) { ls(flags, dir_r); } /*for (unsigned i = 0; i < dir_r.size(); ++i) { cout << dir_r.at(i) << endl; if (dir_r.at(i) != 0) { delete [] dir_r.at(i); } }*/ } for (unsigned i = 0; i < dir.size(); ++i) { if (dir.at(i) != 0) { delete [] dir.at(i); } } } int main(int argc, char* argv[]) { int a = 0; //initialize counter for number of flags vector<char*> dirs; vector<char*> files; int flags = setFlag(argc, argv, dirs, files, a); if (dirs.size() == 0 && files.size() == 0 && argc - a == 1) { char* d = new char[2]; strcpy(d, "."); dirs.push_back(d); } ls(flags, dirs); return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <cstdlib> #include <ctime> #include <cstring> #include <stdio.h> #include <iomanip> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <sys/stat.h> #include <iostream> #include "alphanum.hpp" #define IMPROPER_FLAGS 1 #define FAILURE_EXIT 2 #define LINE_SIZE 80 using namespace std; /* GLOBAL OPTIONS */ bool show_hidden = false; // -a bool long_listing_format = false; // -l bool recursive = false; // -R // a vector of files, in sorted order vector<string> sorted_files; // a vector of files, in sorted order, with long_listing data vector<string> sorted_files_long; class Result { public: string type; string permissions; int links; string owner; string group_owner; int bytes_size; string time_last_mod; string filename; //constructors Result () {}; //methods void print_basic () { //print basic ls cout << filename << " "; } void print_basic_hidden () { ; } void print_long_format () { //print -l ls cout << type << permissions << " " << links << " " << owner << " " << group_owner << " " << bytes_size << " " << time_last_mod << " " << filename << endl; } }; // a vector of Results; data from stat vector<Result> results; bool result_sort (Result i, Result j) { return (i.filename < j.filename); } //isHidden: a helper function to std::remove_if to determine // if a file in the vector is a hidden file bool isHidden (Result s) { return (s.filename.at(0) == '.'); } //set_flags: sets the various global options according to // the flags passed in by the user. Returns the // index of the first non-option argument. void set_flags (int, char**); //get_files: populates sorted_files with the files, in order, // ready for printing, that readdir returns. void get_files (int, char**, int); //sort_files: sorts the files in sorted_files, readying them // for printing void sort_files (); //usage_error: attempts to print a helpful error message to the user // should they try something illegal void usage_error (int); //display: prints the selected version of ls to the console. // Takes the index of the first non-option argument; // assumes that options have been moved to the front. void display (int, char**, int); //determine_index: finds the index of the first non-option argument int determine_index (int, char**); int main (int argc, char** argv) { set_flags (argc, argv); //flags will be moved to beginning of argv // if recursive, dup (?) // maybe use ftw (file tree walk) int idx = determine_index (argc, argv); //index of first non-opt. char. get_files (argc, argv, idx); sort_files (); display (argc, argv, idx); return 0; } void set_flags (int argc, char** argv) { //opterr = 0; //write our own warnings while (1) { int c = getopt (argc, argv, "alR"); //magic! if (c == -1) break; switch (c) { case 'a': show_hidden = true; break; case 'l': long_listing_format = true; break; case 'R': recursive = true; break; default: usage_error (IMPROPER_FLAGS); } } } void usage_error (int err) { switch (err) { case IMPROPER_FLAGS: cerr << "Please enter valid flags." << endl; break; default: cerr << "An unknown error occurred. Sorry!" << endl; } exit (-1); //mirror ls behavior: if any flags fail, do not print } void display (int argc, char** argv, int idx) { if (!long_listing_format && !recursive) // -a, default { for (unsigned i = 0; i < results.size(); ++i) { results[i].print_basic (); } cout << endl; } else if (long_listing_format && !recursive) // -l, -al { for (unsigned i = 0; i < results.size(); ++i) { results[i].print_long_format (); } } else if (!long_listing_format && recursive) // -R, -aR { cout << "R, aR" << endl; } else if (long_listing_format && recursive) // -lR, -alR { cout << "lR, alR" << endl; } else { cout << "An error has occured! Flags were not caught." << endl; } } void get_files (int argc, char** argv, int idx) { bool first_iteration = true; while (idx <= argc) { const char *dirname; if (idx == argc && first_iteration) { dirname = "."; } else if (idx == argc && !first_iteration) { break; } else { dirname = argv[idx]; first_iteration = false; } DIR *dirp = opendir (dirname); if (!dirp) { perror("opendir"); exit(-1); } dirent *direntp; while ((direntp = readdir (dirp))) { if (direntp == NULL) { perror("readdir"); exit(-1); } string file_name_s (direntp->d_name); string file_name (direntp->d_name); // pass a modified path to stat file_name_s = dirname; //argv[idx]; file_name_s += "/"; file_name_s += direntp->d_name; Result temp; struct stat sb; int err = stat((file_name_s).c_str(), &sb); if (err == -1) { perror("stat"); exit(-1); } if (!show_hidden && file_name.at(0) == '.') continue; //populate the temp object, then push it to the vector if (S_ISREG (sb.st_mode)) { temp.type = "-"; } else if (S_ISDIR (sb.st_mode)) { temp.type = "d"; } else if (S_ISCHR (sb.st_mode)) { temp.type = "c"; } else if (S_ISBLK (sb.st_mode)) { temp.type = "b"; } else if (S_ISFIFO (sb.st_mode)) { temp.type = "p"; } else if (S_ISLNK (sb.st_mode)) { temp.type = "l"; } else if (S_ISSOCK (sb.st_mode)) { temp.type = "s"; } else { temp.type = "-"; } string permissions = ""; if (sb.st_mode & S_IRUSR) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWUSR) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXUSR) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IRGRP) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWGRP) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXGRP) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IROTH) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWOTH) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXOTH) { permissions += "x"; } else { permissions += "-"; } temp.permissions = permissions; temp.links = sb.st_nlink; struct passwd *pb = getpwuid (sb.st_uid); if (pb == NULL) { perror("getpwuid"); exit(-1); } temp.owner = pb->pw_name; struct group *gb = getgrgid (sb.st_gid); if (gb == NULL) { perror("getgrgid"); exit(-1); } temp.group_owner = gb->gr_name; temp.bytes_size = sb.st_size; time_t rawtime = sb.st_mtime; struct tm *timeinfo; timeinfo = localtime (&rawtime); char *t = asctime (timeinfo); t [strlen(t) - 1] = 0; temp.time_last_mod = t; temp.filename = file_name; results.push_back (temp); } if ((closedir (dirp)) == -1) { perror("closedir"); exit(-1); } ++idx; } } void sort_files () { //TODO: think about implementing a natural sorting algorithm // to match the behavior of the original ls. // ASCIIbetical sort sucks... sort (sorted_files.begin(), sorted_files.end()); sort (results.begin(), results.end(), result_sort); } void print_basic () { string printed = ""; for (unsigned i = 0; i < sorted_files.size(); ++i) { printed += (sorted_files[i] + " "); if (printed.length() >= LINE_SIZE) { cout << endl; printed = ""; printed += (sorted_files[i] + " "); } cout << sorted_files[i] << " "; } cout << endl; } int determine_index (int argc, char** argv) { int idx = 1; //start at one for argv[0] offset for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') ++idx; } return idx; } <commit_msg>updated directory logic in prep for -R impl., spent 2 hours on ++j...<commit_after>#include <algorithm> #include <cstdlib> #include <ctime> #include <cstring> #include <stdio.h> #include <iomanip> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <sys/stat.h> #include <iostream> #include "alphanum.hpp" #define IMPROPER_FLAGS 1 #define FAILURE_EXIT 2 #define LINE_SIZE 80 using namespace std; /* GLOBAL OPTIONS */ bool show_hidden = false; // -a bool long_listing_format = false; // -l bool recursive = false; // -R class Result { public: string type; string permissions; int links; string owner; string group_owner; int bytes_size; string time_last_mod; string filename; //constructors Result () {}; //cppcheck warning with --enable=warning //destructor ~Result () {}; //methods void print_basic () { //print basic ls cout << filename << " "; } void get_recursive () { ; } void print_recursive () { ; } void print_long_format () { //print -l ls cout << type << permissions << " " << links << " " << owner << " " << group_owner << " " << bytes_size << " " << time_last_mod << " " << filename << endl; } }; class Directory { public: vector<Result> files; string dir_name; //constructore Directory () {}; Directory (string dir_name) : dir_name(dir_name) { } }; // a vector of directories; data from stat vector<Directory> dirs; vector<Result> results; bool result_sort (Result i, Result j) { return (i.filename < j.filename); } //isHidden: a helper function to std::remove_if to determine // if a file in the vector is a hidden file bool isHidden (Result s) { return (s.filename.at(0) == '.'); } //set_flags: sets the various global options according to // the flags passed in by the user. Returns the // index of the first non-option argument. void set_flags (int, char**); //get_files: populates sorted_files with the files, in order, // ready for printing, that readdir returns. void get_files (int, char**, int); //sort_files: sorts the files in sorted_files, readying them // for printing void sort_files (); //usage_error: attempts to print a helpful error message to the user // should they try something illegal void usage_error (int); //display: prints the selected version of ls to the console. // Takes the index of the first non-option argument; // assumes that options have been moved to the front. void display (int, char**, int); //determine_index: finds the index of the first non-option argument int determine_index (int, char**); int main (int argc, char** argv) { set_flags (argc, argv); //flags will be moved to beginning of argv // if recursive, dup (?) // maybe use ftw (file tree walk) int idx = determine_index (argc, argv); //index of first non-opt. char. get_files (argc, argv, idx); sort_files (); display (argc, argv, idx); return 0; } void set_flags (int argc, char** argv) { //opterr = 0; //write our own warnings while (1) { int c = getopt (argc, argv, "alR"); //magic! if (c == -1) break; switch (c) { case 'a': show_hidden = true; break; case 'l': long_listing_format = true; break; case 'R': recursive = true; break; default: usage_error (IMPROPER_FLAGS); } } } void usage_error (int err) { switch (err) { case IMPROPER_FLAGS: cerr << "Please enter valid flags." << endl; break; default: cerr << "An unknown error occurred. Sorry!" << endl; } exit (-1); //mirror ls behavior: if any flags fail, do not print } void display (int argc, char** argv, int idx) { if (!long_listing_format && !recursive) // -a, default { for (unsigned i = 0; i < dirs.size(); ++i) { if (dirs.size() > 1) { cout << dirs[i].dir_name << ": " << endl; } for (unsigned j = 0; j < dirs[i].files.size(); ++j) { dirs[i].files[j].print_basic (); } cout << endl; if ( (i + 1) != dirs.size() ) cout << endl; } } else if (long_listing_format && !recursive) // -l, -al { for (unsigned i = 0; i < dirs.size(); ++i) { if (dirs.size() > 1) { cout << dirs[i].dir_name << ": " << endl; } for (unsigned j = 0; j < dirs[i].files.size(); ++j) { dirs[i].files[j].print_long_format (); } if ( (i + 1) != dirs.size() ) cout << endl; } } else if (!long_listing_format && recursive) // -R, -aR { cout << "R, aR" << endl; } else if (long_listing_format && recursive) // -lR, -alR { cout << "lR, alR" << endl; } else { cout << "An error has occured! Flags were not caught." << endl; } } void get_files (int argc, char** argv, int idx) { bool first_iteration = true; while (idx <= argc) { const char *dirname; if (idx == argc && first_iteration) { dirname = "./"; // added a slash (MAY BREAK THINGS) } else if (idx == argc && !first_iteration) { break; } else { dirname = argv[idx]; first_iteration = false; } DIR *dirp = opendir (dirname); if (!dirp) { perror("opendir"); exit(-1); } dirent *direntp; //create a temp Directory object //Directory tempdir (dirname); //cout << "dirname: " << tempdir.dir_name << endl; //construct one file (result) while ((direntp = readdir (dirp))) { if (direntp == NULL) { perror("readdir"); exit(-1); } string file_name_s (direntp->d_name); string file_name (direntp->d_name); // pass a modified path to stat file_name_s = dirname; //argv[idx]; file_name_s += "/"; file_name_s += direntp->d_name; Result temp; struct stat sb; int err = stat((file_name_s).c_str(), &sb); if (err == -1) { perror("stat"); exit(-1); } if (!show_hidden && file_name.at(0) == '.') continue; //populate the temp object, then push it to the vector if (S_ISREG (sb.st_mode)) { temp.type = "-"; } else if (S_ISDIR (sb.st_mode)) { temp.type = "d"; } else if (S_ISCHR (sb.st_mode)) { temp.type = "c"; } else if (S_ISBLK (sb.st_mode)) { temp.type = "b"; } else if (S_ISFIFO (sb.st_mode)) { temp.type = "p"; } else if (S_ISLNK (sb.st_mode)) { temp.type = "l"; } else if (S_ISSOCK (sb.st_mode)) { temp.type = "s"; } else { temp.type = "-"; } string permissions = ""; if (sb.st_mode & S_IRUSR) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWUSR) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXUSR) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IRGRP) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWGRP) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXGRP) { permissions += "x"; } else { permissions += "-"; } if (sb.st_mode & S_IROTH) { permissions += "r"; } else { permissions += "-"; } if (sb.st_mode & S_IWOTH) { permissions += "w"; } else { permissions += "-"; } if (sb.st_mode & S_IXOTH) { permissions += "x"; } else { permissions += "-"; } temp.permissions = permissions; temp.links = sb.st_nlink; struct passwd *pb = getpwuid (sb.st_uid); if (pb == NULL) { perror("getpwuid"); exit(-1); } temp.owner = pb->pw_name; struct group *gb = getgrgid (sb.st_gid); if (gb == NULL) { perror("getgrgid"); exit(-1); } temp.group_owner = gb->gr_name; temp.bytes_size = sb.st_size; time_t rawtime = sb.st_mtime; struct tm *timeinfo; timeinfo = localtime (&rawtime); char *t = asctime (timeinfo); t [strlen(t) - 1] = 0; temp.time_last_mod = t; temp.filename = file_name; results.push_back (temp); //fill up results with all for this dir //tempdir.files.push_back (temp); //TESTING~ //temp.print_long_format(); } if ((closedir (dirp)) == -1) { perror("closedir"); exit(-1); } //now, we have a filled results array //we must 1) create a Directory with that array as files, and // 2) push that Directory back onto the dirs vector // 3) clear out the results vector Directory tempdir (dirname); tempdir.files = results; //alternately, to construct the array in each directory, try for loop (each result) dirs.push_back (tempdir); results.clear (); ++idx; } } void sort_files () { //TODO: think about implementing a natural sorting algorithm // to match the behavior of the original ls. // ASCIIbetical sort sucks... for (int i = 0; i < dirs.size (); ++i) { //sort each passed-in directory's files separately sort (dirs[i].files.begin(), dirs[i].files.end(), result_sort); } } int determine_index (int argc, char** argv) { int idx = 1; //start at one for argv[0] offset for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') ++idx; } return idx; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <stdio.h> #include <unistd.h> #include "errno.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <vector> #include <list> #include <iterator> #include <fcntl.h> #include <dirent.h> #include <sys/ioctl.h> #include <stdio.h> #include <unistd.h> #include <cmath> #include <string.h> #include <sys/stat.h> #include <grp.h> #include <pwd.h> #include <time.h> #include <locale.h> #include <langinfo.h> #include <algorithm> using namespace std; void list_output(vector<char*> &v) { struct passwd *pws; pws = getpwuid(geteuid()); struct group *grp; grp = getgrgid(getgid()); int width = 0; int total = 0; for(auto x : v) { int tempWidth = 0; struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); total += ceil(fileStat.st_blocks); for(; fileStat.st_size != 0; fileStat.st_size /= 10, tempWidth++); tempWidth > width ? width = tempWidth : width; } cout << "total " << total/2 << endl; for(auto x : v) { struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); bool directory = (S_ISDIR(fileStat.st_mode)); bool executable = (fileStat.st_mode > 0) && (S_IEXEC & fileStat.st_mode); bool hidden = (x[0] == '.'); printf( directory ? "d" : "-"); printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-"); printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-"); printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-"); printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-"); printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-"); printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-"); printf( (fileStat.st_mode & S_IROTH) ? "r" : "-"); printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-"); printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-"); printf(" "); cout << fileStat.st_nlink << " "; printf("%s ", pws->pw_name); printf("%s ", grp->gr_name); cout.width(width); cout << std::right << fileStat.st_size << " "; struct tm *tm; char datestring[256]; tm = localtime(&fileStat.st_mtime); strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm); printf("%s ", datestring); if(directory) { if(hidden) cout << "\x1b[34;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[34;40m" << x << "\x1b[0m" << endl; } else if(executable) { if(hidden) cout << "\x1b[1;32;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[1;32;40m" << x << "\x1b[0m" << endl; } else if(hidden) cout << "\x1b[30;47m" << x << "\x1b[0m" << endl; else cout << x << endl; } } void standard_output(vector<char*> &v, int length) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); int check_width = v.size()*length-1; int num_rows = ceil((double)check_width/(double)w.ws_col); for(int i = 0; i < num_rows; ++i) { for(unsigned a = i; a < v.size(); a += num_rows) { struct stat fileStat; bool directory = (S_ISDIR(fileStat.st_mode)); bool executable = (fileStat.st_mode > 0) && (S_IEXEC & fileStat.st_mode); bool hidden = ((v.at(a))[0] == '.'); if(directory) { if(hidden) cout << "\x1b[34;47m" << v.at(a) << "\x1b[0m"; else cout << "\x1b[34;40m" << v.at(a) << "\x1b[0m"; } else if(executable) { if(hidden) cout << "\x1b[1;32;47m" << v.at(a) << "\x1b[0m"; else cout << "\x1b[1;32;40m" << v.at(a) << "\x1b[0m"; } else if(hidden) cout << "\x1b[30;47m" << v.at(a) << "\x1b[0m"; else cout << v.at(a); for(int i = strlen(v.at(a)); i < length; ++i) cout << " "; } cout << endl; } } bool comparisonFunc(const char *c1, const char *c2) { return strcasecmp(c1, c2) < 0; } int main (int argc, char const *argv[]) { DIR *dirp; string direc = "./"; bool list = false; bool all = false; bool recursive = false; vector<char*> files; unsigned max_length = 9; if(argc == 2) { string first = argv[1]; if(first[0] == '-') { if(first.find('a') != string::npos) all = true; if(first.find('l') != string::npos) list = true; if(first.find('R') != string::npos) recursive = true; } else direc = argv[1]; } if(argc > 2) { direc = argv[2]; } if(NULL == (dirp = opendir(const_cast<char*>(direc.c_str())))) { perror("There was an error with opendir(). "); exit(1); } struct dirent *filespecs; errno = 0; while(NULL != (filespecs = readdir(dirp))) { if(filespecs->d_name[0] == '.' && !all) continue; files.push_back(filespecs->d_name); strlen(filespecs->d_name) > max_length ? max_length = strlen(filespecs->d_name) : max_length; } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } sort(files.begin(), files.end(), comparisonFunc); if(!list) standard_output(files, ++max_length); else list_output(files); if(recursive) cout << "rec" << endl; if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } return 0; }<commit_msg>Removing trailing space<commit_after>#include <iostream> #include <fstream> #include <stdio.h> #include <unistd.h> #include "errno.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <vector> #include <list> #include <iterator> #include <fcntl.h> #include <dirent.h> #include <sys/ioctl.h> #include <stdio.h> #include <unistd.h> #include <cmath> #include <string.h> #include <sys/stat.h> #include <grp.h> #include <pwd.h> #include <time.h> #include <locale.h> #include <langinfo.h> #include <algorithm> using namespace std; void list_output(vector<char*> &v) { struct passwd *pws; pws = getpwuid(geteuid()); struct group *grp; grp = getgrgid(getgid()); int width = 0; int total = 0; for(auto x : v) { int tempWidth = 0; struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); total += ceil(fileStat.st_blocks); for(; fileStat.st_size != 0; fileStat.st_size /= 10, tempWidth++); tempWidth > width ? width = tempWidth : width; } cout << "total " << total/2 << endl; for(auto x : v) { struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); bool directory = (S_ISDIR(fileStat.st_mode)); bool executable = (fileStat.st_mode > 0) && (S_IEXEC & fileStat.st_mode); bool hidden = (x[0] == '.'); printf( directory ? "d" : "-"); printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-"); printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-"); printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-"); printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-"); printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-"); printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-"); printf( (fileStat.st_mode & S_IROTH) ? "r" : "-"); printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-"); printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-"); printf(" "); cout << fileStat.st_nlink << " "; printf("%s ", pws->pw_name); printf("%s ", grp->gr_name); cout.width(width); cout << std::right << fileStat.st_size << " "; struct tm *tm; char datestring[256]; tm = localtime(&fileStat.st_mtime); strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm); printf("%s ", datestring); if(directory) { if(hidden) cout << "\x1b[34;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[34;40m" << x << "\x1b[0m" << endl; } else if(executable) { if(hidden) cout << "\x1b[1;32;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[1;32;40m" << x << "\x1b[0m" << endl; } else if(hidden) cout << "\x1b[30;47m" << x << "\x1b[0m" << endl; else cout << x << endl; } } void standard_output(vector<char*> &v, int length) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); int check_width = v.size()*length-1; int num_rows = ceil((double)check_width/(double)w.ws_col); for(int i = 0; i < num_rows; ++i) { for(unsigned a = i; a < v.size(); a += num_rows) { struct stat fileStat; bool directory = (S_ISDIR(fileStat.st_mode)); bool executable = (fileStat.st_mode > 0) && (S_IEXEC & fileStat.st_mode); bool hidden = ((v.at(a))[0] == '.'); if(directory) { if(hidden) cout << "\x1b[34;47m" << v.at(a) << "\x1b[0m"; else cout << "\x1b[34;40m" << v.at(a) << "\x1b[0m"; } else if(executable) { if(hidden) cout << "\x1b[1;32;47m" << v.at(a) << "\x1b[0m"; else cout << "\x1b[1;32;40m" << v.at(a) << "\x1b[0m"; } else if(hidden) cout << "\x1b[30;47m" << v.at(a) << "\x1b[0m"; else cout << v.at(a); for(int i = strlen(v.at(a)); i < length && a < (v.size() - num_rows); ++i) cout << " "; } cout << endl; } } bool comparisonFunc(const char *c1, const char *c2) { return strcasecmp(c1, c2) < 0; } int main (int argc, char const *argv[]) { DIR *dirp; string direc = "./"; bool list = false; bool all = false; bool recursive = false; vector<char*> files; unsigned max_length = 9; if(argc == 2) { string first = argv[1]; if(first[0] == '-') { if(first.find('a') != string::npos) all = true; if(first.find('l') != string::npos) list = true; if(first.find('R') != string::npos) recursive = true; } else direc = argv[1]; } if(argc > 2) { direc = argv[2]; } if(NULL == (dirp = opendir(const_cast<char*>(direc.c_str())))) { perror("There was an error with opendir(). "); exit(1); } struct dirent *filespecs; errno = 0; while(NULL != (filespecs = readdir(dirp))) { if(filespecs->d_name[0] == '.' && !all) continue; files.push_back(filespecs->d_name); strlen(filespecs->d_name) > max_length ? max_length = strlen(filespecs->d_name) : max_length; } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } sort(files.begin(), files.end(), comparisonFunc); if(!list) standard_output(files, ++max_length); else list_output(files); if(recursive) cout << "rec" << endl; if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <vector> #include <sstream> #include <dirent.h> #include <errno.h> #include <sys/types.h> using namespace std; bool isDirectory(char* directoryName) { struct stat directoryInCurrent; if (-1 == (stat(directoryName, &directoryInCurrent))) { perror("stat failed"); return false; } if (directoryInCurrent.st_mode & S_IFDIR) { return true; } else { return false; } } int ls(char* directoryName) { char const *dirName = "."; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } bool lsWithFlags(char* directoryName, vector<string> flags) { bool isA = false; bool isL = false; bool isR = false; for (unsigned i = 0; i < flags.size(); ++i) { if (flags.at(i) == "a") isA = true; else if (flags.at(i) == "l") isL = true; else if (flags.at(i) == "R") isR = true; } char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; return errno; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); } int main(int argc, char* argv[]) { if (argc == 1) { if (errno == ls(".")) { return errno; } } /*else { vector<string> directories; vector<string> flags; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { flags.push_back(argv[i]); } else { if (isDirectory( } } }*/ } <commit_msg>commented lswithflags function<commit_after>#include <iostream> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <vector> #include <sstream> #include <dirent.h> #include <errno.h> #include <sys/types.h> using namespace std; bool isDirectory(char* directoryName) { struct stat directoryInCurrent; if (-1 == (stat(directoryName, &directoryInCurrent))) { perror("stat failed"); return false; } if (directoryInCurrent.st_mode & S_IFDIR) { return true; } else { return false; } } int ls(char* directoryName) { char const *dirName = "."; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } /*bool lsWithFlags(char* directoryName, vector<string> flags) { bool isA = false; bool isL = false; bool isR = false; for (unsigned i = 0; i < flags.size(); ++i) { if (flags.at(i) == "a") isA = true; else if (flags.at(i) == "l") isL = true; else if (flags.at(i) == "R") isR = true; } char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; return errno; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); }*/ int main(int argc, char* argv[]) { if (argc == 1) { if (errno == ls(".")) { return errno; } } /*else { vector<string> directories; vector<string> flags; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { flags.push_back(argv[i]); } else { if (isDirectory( } } }*/ } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <stdio.h> #include <unistd.h> #include "errno.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <vector> #include <list> #include <iterator> #include <fcntl.h> #include <dirent.h> #include <sys/ioctl.h> #include <stdio.h> #include <unistd.h> #include <cmath> #include <string.h> #include <sys/stat.h> #include <grp.h> #include <pwd.h> #include <time.h> #include <locale.h> #include <langinfo.h> using namespace std; void list_output(vector<char*> &v) { struct passwd *pws; pws = getpwuid(geteuid()); struct group *grp; grp = getgrgid(getgid()); int width = 0; int total = 0; for(auto x : v) { int tempWidth = 0; struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); total += ceil(fileStat.st_blocks); for(; fileStat.st_size != 0; fileStat.st_size /= 10, tempWidth++); tempWidth > width ? width = tempWidth : width; } cout << "total " << total << endl; for(auto x : v) { struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); bool directory = (S_ISDIR(fileStat.st_mode)); bool executable = (fileStat.st_mode > 0) && (S_IEXEC & fileStat.st_mode); bool hidden = (x[0] == '.'); printf( directory ? "d" : "-"); printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-"); printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-"); printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-"); printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-"); printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-"); printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-"); printf( (fileStat.st_mode & S_IROTH) ? "r" : "-"); printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-"); printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-"); printf(" "); cout << fileStat.st_nlink << " "; printf("%s ", pws->pw_name); printf("%s ", grp->gr_name); cout.width(width); cout << std::right << fileStat.st_size << " "; struct tm *tm; char datestring[256]; tm = localtime(&fileStat.st_mtime); strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm); printf("%s ", datestring); if(directory) { if(hidden) cout << "\x1b[34;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[34;40m" << x << "\x1b[0m" << endl; } else if(executable) { if(hidden) cout << "\x1b[1;32;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[1;32;40m" << x << "\x1b[0m" << endl; } else if(hidden) cout << "\x1b[30;47m" << x << "\x1b[0m" << endl; else cout << x << endl; } } void standard_output(vector<char*> &v, int length) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); int check_width = v.size()*length; int num_rows = ceil((double)check_width/(double)w.ws_col); for(int i = 0; i < num_rows; ++i) { for(unsigned a = i; a < v.size(); a += num_rows) { cout << v.at(a); for(int i = strlen(v.at(a)); i < length; ++i) cout << " "; } cout << endl; } } int main (int argc, char const *argv[]) { DIR *dirp; string direc = "./"; bool list = false; bool all = false; bool recursive = false; vector<char*> files; unsigned max_length = 9; if(argc == 2) { string first = argv[1]; if(first[0] == '-') { if(first.find('a') != string::npos) all = true; if(first.find('l') != string::npos) list = true; if(first.find('R') != string::npos) recursive = true; } else direc = argv[1]; } if(argc > 2) { direc = argv[2]; } if(NULL == (dirp = opendir(const_cast<char*>(direc.c_str())))) { perror("There was an error with opendir(). "); exit(1); } struct dirent *filespecs; errno = 0; while(NULL != (filespecs = readdir(dirp))) { if(filespecs->d_name[0] == '.' && !all) continue; files.push_back(filespecs->d_name); strlen(filespecs->d_name) > max_length ? max_length = strlen(filespecs->d_name) : max_length; } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } if(!list) standard_output(files, ++max_length); else list_output(files); if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } return 0; }<commit_msg>Make apparently doesn't like one of my variables<commit_after>#include <iostream> #include <fstream> #include <stdio.h> #include <unistd.h> #include "errno.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <vector> #include <list> #include <iterator> #include <fcntl.h> #include <dirent.h> #include <sys/ioctl.h> #include <stdio.h> #include <unistd.h> #include <cmath> #include <string.h> #include <sys/stat.h> #include <grp.h> #include <pwd.h> #include <time.h> #include <locale.h> #include <langinfo.h> using namespace std; void list_output(vector<char*> &v) { struct passwd *pws; pws = getpwuid(geteuid()); struct group *grp; grp = getgrgid(getgid()); int width = 0; int total = 0; for(auto x : v) { int tempWidth = 0; struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); total += ceil(fileStat.st_blocks); for(; fileStat.st_size != 0; fileStat.st_size /= 10, tempWidth++); tempWidth > width ? width = tempWidth : width; } cout << "total " << total << endl; for(auto x : v) { struct stat fileStat; if(stat(x, &fileStat) < 0) perror("Failed"); bool directory = (S_ISDIR(fileStat.st_mode)); bool executable = (fileStat.st_mode > 0) && (S_IEXEC & fileStat.st_mode); bool hidden = (x[0] == '.'); printf( directory ? "d" : "-"); printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-"); printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-"); printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-"); printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-"); printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-"); printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-"); printf( (fileStat.st_mode & S_IROTH) ? "r" : "-"); printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-"); printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-"); printf(" "); cout << fileStat.st_nlink << " "; printf("%s ", pws->pw_name); printf("%s ", grp->gr_name); cout.width(width); cout << std::right << fileStat.st_size << " "; struct tm *tm; char datestring[256]; tm = localtime(&fileStat.st_mtime); strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm); printf("%s ", datestring); if(directory) { if(hidden) cout << "\x1b[34;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[34;40m" << x << "\x1b[0m" << endl; } else if(executable) { if(hidden) cout << "\x1b[1;32;47m" << x << "\x1b[0m" << endl; else cout << "\x1b[1;32;40m" << x << "\x1b[0m" << endl; } else if(hidden) cout << "\x1b[30;47m" << x << "\x1b[0m" << endl; else cout << x << endl; } } void standard_output(vector<char*> &v, int length) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); int check_width = v.size()*length; int num_rows = ceil((double)check_width/(double)w.ws_col); for(int i = 0; i < num_rows; ++i) { for(unsigned a = i; a < v.size(); a += num_rows) { cout << v.at(a); for(int i = strlen(v.at(a)); i < length; ++i) cout << " "; } cout << endl; } } int main (int argc, char const *argv[]) { DIR *dirp; string direc = "./"; bool list = false; bool all = false; bool recursive = false; vector<char*> files; unsigned max_length = 9; if(argc == 2) { string first = argv[1]; if(first[0] == '-') { if(first.find('a') != string::npos) all = true; if(first.find('l') != string::npos) list = true; if(first.find('R') != string::npos) recursive = true; } else direc = argv[1]; } if(argc > 2) { direc = argv[2]; } if(NULL == (dirp = opendir(const_cast<char*>(direc.c_str())))) { perror("There was an error with opendir(). "); exit(1); } struct dirent *filespecs; errno = 0; while(NULL != (filespecs = readdir(dirp))) { if(filespecs->d_name[0] == '.' && !all) continue; files.push_back(filespecs->d_name); strlen(filespecs->d_name) > max_length ? max_length = strlen(filespecs->d_name) : max_length; } if(errno != 0) { perror("There was an error with readdir(). "); exit(1); } if(!list) standard_output(files, ++max_length); else list_output(files); if(recursive) cout << "rec" << endl; if(-1 == closedir(dirp)) { perror("There was an error with closedir(). "); exit(1); } return 0; }<|endoftext|>
<commit_before>/** * Copyright 2012 FAU (Friedrich Alexander University of Erlangen-Nuremberg) * * 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 "i6engine/modules/gui/guiwidgets/GUIComboBox.h" #include "i6engine/utils/Exceptions.h" #include "i6engine/api/configs/GUIConfig.h" #include "CEGUI/CEGUI.h" namespace i6engine { namespace modules { GUIComboBox::GUIComboBox(const std::string & name, const std::string & style) : api::GUIWidget(name), _selectedCallback() { CEGUI::WindowManager & wmgr = CEGUI::WindowManager::getSingleton(); _window = wmgr.createWindow(style, name); _window->setProperty("RiseOnClickEnabled", "False"); dynamic_cast<CEGUI::Combobox *>(_window)->setReadOnly(true); _window->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&GUIComboBox::selectionChanged, this)); } void GUIComboBox::update(uint16_t type, api::gui::GUIUpdateMessageStruct * data) { if (type == api::gui::GuiAddText) { api::gui::GUI_Text * g = dynamic_cast<api::gui::GUI_Text *>(data); dynamic_cast<CEGUI::Combobox *>(_window)->addItem(new CEGUI::ListboxTextItem(g->text)); } else if (type == api::gui::GuiSetSelectedStringCallback) { api::gui::GUI_SetSelectedStringCallback * g = dynamic_cast<api::gui::GUI_SetSelectedStringCallback *>(data); _selectedCallback = g->callback; } else if (api::gui::GuiSetText) { std::string selection = dynamic_cast<api::gui::GUI_Text *>(data)->text; for (size_t i = 0; i < dynamic_cast<CEGUI::Combobox *>(_window)->getItemCount(); i++) { CEGUI::ListboxTextItem * lti = dynamic_cast<CEGUI::ListboxTextItem *>(dynamic_cast<CEGUI::Combobox *>(_window)->getListboxItemFromIndex(i)); if (lti->getText() == selection) { lti->setSelected(true); dynamic_cast<CEGUI::Combobox *>(_window)->setText(selection); break; } } } else { GUIWidget::update(type, data); } } bool GUIComboBox::selectionChanged(const CEGUI::EventArgs & evt) { if (_selectedCallback == nullptr) { return true; } _selectedCallback(dynamic_cast<CEGUI::ListboxTextItem *>(dynamic_cast<CEGUI::Combobox *>(_window)->getSelectedItem())->getText().c_str()); return true; } } /* namespace modules */ } /* namespace i6engine */ <commit_msg>ISIXE-1502 fixed bug<commit_after>/** * Copyright 2012 FAU (Friedrich Alexander University of Erlangen-Nuremberg) * * 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 "i6engine/modules/gui/guiwidgets/GUIComboBox.h" #include "i6engine/utils/Exceptions.h" #include "i6engine/api/configs/GUIConfig.h" #include "CEGUI/CEGUI.h" namespace i6engine { namespace modules { GUIComboBox::GUIComboBox(const std::string & name, const std::string & style) : api::GUIWidget(name), _selectedCallback() { CEGUI::WindowManager & wmgr = CEGUI::WindowManager::getSingleton(); _window = wmgr.createWindow(style, name); _window->setProperty("RiseOnClickEnabled", "False"); dynamic_cast<CEGUI::Combobox *>(_window)->setReadOnly(true); _window->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&GUIComboBox::selectionChanged, this)); } void GUIComboBox::update(uint16_t type, api::gui::GUIUpdateMessageStruct * data) { if (type == api::gui::GuiAddText) { api::gui::GUI_Text * g = dynamic_cast<api::gui::GUI_Text *>(data); dynamic_cast<CEGUI::Combobox *>(_window)->addItem(new CEGUI::ListboxTextItem(g->text)); } else if (type == api::gui::GuiSetSelectedStringCallback) { api::gui::GUI_SetSelectedStringCallback * g = dynamic_cast<api::gui::GUI_SetSelectedStringCallback *>(data); _selectedCallback = g->callback; } else if (type == api::gui::GuiSetText) { std::string selection = dynamic_cast<api::gui::GUI_Text *>(data)->text; for (size_t i = 0; i < dynamic_cast<CEGUI::Combobox *>(_window)->getItemCount(); i++) { CEGUI::ListboxTextItem * lti = dynamic_cast<CEGUI::ListboxTextItem *>(dynamic_cast<CEGUI::Combobox *>(_window)->getListboxItemFromIndex(i)); if (lti->getText() == selection) { lti->setSelected(true); dynamic_cast<CEGUI::Combobox *>(_window)->setText(selection); break; } } } else { GUIWidget::update(type, data); } } bool GUIComboBox::selectionChanged(const CEGUI::EventArgs & evt) { if (_selectedCallback == nullptr) { return true; } _selectedCallback(dynamic_cast<CEGUI::ListboxTextItem *>(dynamic_cast<CEGUI::Combobox *>(_window)->getSelectedItem())->getText().c_str()); return true; } } /* namespace modules */ } /* namespace i6engine */ <|endoftext|>
<commit_before>/* * Copyright 2000-2008, François Revol, <revol@free.fr>. All rights reserved. * Distributed under the terms of the MIT License. */ #include "Utils.h" #include <FindDirectory.h> #include <Path.h> #include <String.h> #include <BeBuild.h> #include <malloc.h> #include <stdio.h> // some private font information structs namespace BPrivate { typedef struct font_folder_info { //char name[256]; char *name; uint32 flags; } font_folder_info; typedef struct font_file_info { char *name; uint32 flags; font_family family; font_style style; uint32 dummy; } font_file_info; }; using namespace BPrivate; // this is PRIVATE to libbe and NOT in R5!!! extern long _count_font_folders_(void); extern long _count_font_files_(long); extern status_t _get_nth_font_file_(long, font_file_info **); extern status_t _get_nth_font_folder_(long, font_folder_info **); status_t find_font_file(entry_ref *to, font_family family, font_style style, float size) { #ifdef B_BEOS_VERSION_DANO status_t err = ENOENT; long i, fontcount, foldercount; font_file_info *ffi; font_folder_info *fdi; bool found = false; (void)size; fontcount = _count_font_files_(0); for (i = 0; i < fontcount; i++) { err = _get_nth_font_file_(i, &ffi); if (err) continue; if (strcmp(ffi->family, family) || strcmp(ffi->style, style)) continue; found = true; break; } if (!found) return ENOENT; foldercount = _count_font_folders_(); for (i = 0; i < fontcount; i++) { err = _get_nth_font_folder_(i, &fdi); if (err) continue; BPath ffile(fdi->name); ffile.Append(ffi->name); printf("find_font_file: looking for '%s' in '%s'\n", ffi->name, fdi->name); BEntry ent(ffile.Path()); if (ent.InitCheck()) continue; printf("find_font_file: found\n."); return ent.GetRef(to); } #endif return ENOENT; } #define _BORK(_t) \ err = find_directory(_t, &path); \ if (!err && (s = dir->FindFirst(path.Path())) >= 0) { \ printf("found %s\n", #_t); \ dir->Remove(s, strlen(path.Path()) - s); \ BString tok(#_t); \ tok.Prepend("${"); \ tok.Append("}"); \ dir->Insert(tok, s); \ return B_OK; \ } \ status_t escape_find_directory(BString *dir) { status_t err; BPath path; int32 s; /* This is just the entire directory_which from FindDirectory.h */ _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_BEOS_DATA_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // Out of order again. _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_DATA_DIRECTORY); _BORK(B_USER_CACHE_DIRECTORY); _BORK(B_USER_PACKAGES_DIRECTORY); _BORK(B_USER_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DIRECTORY); _BORK(B_USER_NONPACKAGED_ADDONS_DIRECTORY); _BORK(B_USER_NONPACKAGED_TRANSLATORS_DIRECTORY); _BORK(B_USER_NONPACKAGED_MEDIA_NODES_DIRECTORY); _BORK(B_USER_NONPACKAGED_BIN_DIRECTORY); _BORK(B_USER_NONPACKAGED_DATA_DIRECTORY); _BORK(B_USER_NONPACKAGED_FONTS_DIRECTORY); _BORK(B_USER_NONPACKAGED_SOUNDS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DOCUMENTATION_DIRECTORY); _BORK(B_USER_NONPACKAGED_LIB_DIRECTORY); _BORK(B_USER_NONPACKAGED_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DEVELOP_DIRECTORY); _BORK(B_USER_DEVELOP_DIRECTORY); _BORK(B_USER_DOCUMENTATION_DIRECTORY); _BORK(B_USER_SERVERS_DIRECTORY); _BORK(B_USER_APPS_DIRECTORY); _BORK(B_USER_BIN_DIRECTORY); _BORK(B_USER_PREFERENCES_DIRECTORY); _BORK(B_USER_ETC_DIRECTORY); _BORK(B_USER_LOG_DIRECTORY); _BORK(B_USER_SPOOL_DIRECTORY); _BORK(B_USER_VAR_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); _BORK(B_PACKAGE_LINKS_DIRECTORY); return B_OK; } #undef _BORK #define _BORK(_t) \ if (tok == #_t) { \ err = find_directory(_t, &path); \ if (err) return err; \ dir->Remove(s, e - s + 1); \ dir->Insert(path.Path(), s); \ return B_OK; \ } \ status_t unescape_find_directory(BString *dir) { status_t err = B_ERROR; int32 s, e; BString tok; BPath path; s = dir->FindFirst("${"); if (s < 0) return B_OK; e = dir->FindFirst("}", s); if (e < 0) return B_OK; dir->CopyInto(tok, s + 2, e - s - 2); //printf("tok '%s'\n", tok.String()); /* This is just the entire directory_which from FindDirectory.h */ _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_BEOS_DATA_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // Out of order again. _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_DATA_DIRECTORY); _BORK(B_USER_CACHE_DIRECTORY); _BORK(B_USER_PACKAGES_DIRECTORY); _BORK(B_USER_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DIRECTORY); _BORK(B_USER_NONPACKAGED_ADDONS_DIRECTORY); _BORK(B_USER_NONPACKAGED_TRANSLATORS_DIRECTORY); _BORK(B_USER_NONPACKAGED_MEDIA_NODES_DIRECTORY); _BORK(B_USER_NONPACKAGED_BIN_DIRECTORY); _BORK(B_USER_NONPACKAGED_DATA_DIRECTORY); _BORK(B_USER_NONPACKAGED_FONTS_DIRECTORY); _BORK(B_USER_NONPACKAGED_SOUNDS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DOCUMENTATION_DIRECTORY); _BORK(B_USER_NONPACKAGED_LIB_DIRECTORY); _BORK(B_USER_NONPACKAGED_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DEVELOP_DIRECTORY); _BORK(B_USER_DEVELOP_DIRECTORY); _BORK(B_USER_DOCUMENTATION_DIRECTORY); _BORK(B_USER_SERVERS_DIRECTORY); _BORK(B_USER_APPS_DIRECTORY); _BORK(B_USER_BIN_DIRECTORY); _BORK(B_USER_PREFERENCES_DIRECTORY); _BORK(B_USER_ETC_DIRECTORY); _BORK(B_USER_LOG_DIRECTORY); _BORK(B_USER_SPOOL_DIRECTORY); _BORK(B_USER_VAR_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); _BORK(B_PACKAGE_LINKS_DIRECTORY); return B_OK; } #undef _BORK // copy a file including its attributes #define BUFF_SZ 1024*1024 status_t copy_file(entry_ref *ref, const char *to) { char *buff; status_t err = B_OK; //off_t off; //size_t got; (void)ref; (void)to; buff = (char *)malloc(BUFF_SZ); // XXX: TODO free(buff); return err; } int testhook() { status_t err; BString str("/boot/home/config/fonts/ttfonts/toto.ttf"); err = escape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); err = unescape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); return 0; } status_t FindRGBColor(BMessage &message, const char *name, int32 index, rgb_color *c) { #ifdef B_BEOS_VERSION_DANO return message.FindRGBColor(name, index, c); #else const void *data; ssize_t len; status_t err; err = message.FindData(name, B_RGB_COLOR_TYPE, index, &data, &len); if (err < B_OK) return err; if (len > (ssize_t)sizeof(*c)) return E2BIG; // Hack memcpy((void *)c, data, len); return B_OK; #endif } status_t AddRGBColor(BMessage &message, const char *name, rgb_color a_color, type_code type) { #ifdef B_BEOS_VERSION_DANO return message.AddRGBColor(name, a_color, type); #else return message.AddData(name, type, &a_color, sizeof(a_color)); #endif } status_t FindFont(BMessage &message, const char *name, int32 index, BFont *f) { #ifdef B_BEOS_VERSION_DANO return message.FindFlat(name, index, f); #else const void *data; ssize_t len; status_t err = message.FindData(name, 'FONt', index, &data, &len); #define DERR(e) { PRINT(("%s: err: %s\n", __FUNCTION__, strerror(e))); } if (err < B_OK) return err; if (len > (ssize_t)sizeof(*f)) return E2BIG; // Hack: only Dano has BFont : public BFlattenable memcpy((void *)f, data, len); return B_OK; #endif } status_t AddFont(BMessage &message, const char *name, BFont *f, int32 count) { #ifdef B_BEOS_VERSION_DANO return message.AddFlat(name, f, count); #else return message.AddData(name, 'FONt', (void *)f, sizeof(*f), true, count); #endif } <commit_msg>B_BEOS_DATA_DIRECTORY -> B_SYSTEM_DATA_DIRECTORY (#2)<commit_after>/* * Copyright 2000-2008, François Revol, <revol@free.fr>. All rights reserved. * Distributed under the terms of the MIT License. */ #include "Utils.h" #include <FindDirectory.h> #include <Path.h> #include <String.h> #include <BeBuild.h> #include <malloc.h> #include <stdio.h> // some private font information structs namespace BPrivate { typedef struct font_folder_info { //char name[256]; char *name; uint32 flags; } font_folder_info; typedef struct font_file_info { char *name; uint32 flags; font_family family; font_style style; uint32 dummy; } font_file_info; }; using namespace BPrivate; // this is PRIVATE to libbe and NOT in R5!!! extern long _count_font_folders_(void); extern long _count_font_files_(long); extern status_t _get_nth_font_file_(long, font_file_info **); extern status_t _get_nth_font_folder_(long, font_folder_info **); status_t find_font_file(entry_ref *to, font_family family, font_style style, float size) { #ifdef B_BEOS_VERSION_DANO status_t err = ENOENT; long i, fontcount, foldercount; font_file_info *ffi; font_folder_info *fdi; bool found = false; (void)size; fontcount = _count_font_files_(0); for (i = 0; i < fontcount; i++) { err = _get_nth_font_file_(i, &ffi); if (err) continue; if (strcmp(ffi->family, family) || strcmp(ffi->style, style)) continue; found = true; break; } if (!found) return ENOENT; foldercount = _count_font_folders_(); for (i = 0; i < fontcount; i++) { err = _get_nth_font_folder_(i, &fdi); if (err) continue; BPath ffile(fdi->name); ffile.Append(ffi->name); printf("find_font_file: looking for '%s' in '%s'\n", ffi->name, fdi->name); BEntry ent(ffile.Path()); if (ent.InitCheck()) continue; printf("find_font_file: found\n."); return ent.GetRef(to); } #endif return ENOENT; } #define _BORK(_t) \ err = find_directory(_t, &path); \ if (!err && (s = dir->FindFirst(path.Path())) >= 0) { \ printf("found %s\n", #_t); \ dir->Remove(s, strlen(path.Path()) - s); \ BString tok(#_t); \ tok.Prepend("${"); \ tok.Append("}"); \ dir->Insert(tok, s); \ return B_OK; \ } \ status_t escape_find_directory(BString *dir) { status_t err; BPath path; int32 s; /* This is just the entire directory_which from FindDirectory.h */ _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_SYSTEM_DATA_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // Out of order again. _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_DATA_DIRECTORY); _BORK(B_USER_CACHE_DIRECTORY); _BORK(B_USER_PACKAGES_DIRECTORY); _BORK(B_USER_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DIRECTORY); _BORK(B_USER_NONPACKAGED_ADDONS_DIRECTORY); _BORK(B_USER_NONPACKAGED_TRANSLATORS_DIRECTORY); _BORK(B_USER_NONPACKAGED_MEDIA_NODES_DIRECTORY); _BORK(B_USER_NONPACKAGED_BIN_DIRECTORY); _BORK(B_USER_NONPACKAGED_DATA_DIRECTORY); _BORK(B_USER_NONPACKAGED_FONTS_DIRECTORY); _BORK(B_USER_NONPACKAGED_SOUNDS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DOCUMENTATION_DIRECTORY); _BORK(B_USER_NONPACKAGED_LIB_DIRECTORY); _BORK(B_USER_NONPACKAGED_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DEVELOP_DIRECTORY); _BORK(B_USER_DEVELOP_DIRECTORY); _BORK(B_USER_DOCUMENTATION_DIRECTORY); _BORK(B_USER_SERVERS_DIRECTORY); _BORK(B_USER_APPS_DIRECTORY); _BORK(B_USER_BIN_DIRECTORY); _BORK(B_USER_PREFERENCES_DIRECTORY); _BORK(B_USER_ETC_DIRECTORY); _BORK(B_USER_LOG_DIRECTORY); _BORK(B_USER_SPOOL_DIRECTORY); _BORK(B_USER_VAR_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); _BORK(B_PACKAGE_LINKS_DIRECTORY); return B_OK; } #undef _BORK #define _BORK(_t) \ if (tok == #_t) { \ err = find_directory(_t, &path); \ if (err) return err; \ dir->Remove(s, e - s + 1); \ dir->Insert(path.Path(), s); \ return B_OK; \ } \ status_t unescape_find_directory(BString *dir) { status_t err = B_ERROR; int32 s, e; BString tok; BPath path; s = dir->FindFirst("${"); if (s < 0) return B_OK; e = dir->FindFirst("}", s); if (e < 0) return B_OK; dir->CopyInto(tok, s + 2, e - s - 2); //printf("tok '%s'\n", tok.String()); /* This is just the entire directory_which from FindDirectory.h */ _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_SYSTEM_DATA_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // Out of order again. _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_DATA_DIRECTORY); _BORK(B_USER_CACHE_DIRECTORY); _BORK(B_USER_PACKAGES_DIRECTORY); _BORK(B_USER_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DIRECTORY); _BORK(B_USER_NONPACKAGED_ADDONS_DIRECTORY); _BORK(B_USER_NONPACKAGED_TRANSLATORS_DIRECTORY); _BORK(B_USER_NONPACKAGED_MEDIA_NODES_DIRECTORY); _BORK(B_USER_NONPACKAGED_BIN_DIRECTORY); _BORK(B_USER_NONPACKAGED_DATA_DIRECTORY); _BORK(B_USER_NONPACKAGED_FONTS_DIRECTORY); _BORK(B_USER_NONPACKAGED_SOUNDS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DOCUMENTATION_DIRECTORY); _BORK(B_USER_NONPACKAGED_LIB_DIRECTORY); _BORK(B_USER_NONPACKAGED_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DEVELOP_DIRECTORY); _BORK(B_USER_DEVELOP_DIRECTORY); _BORK(B_USER_DOCUMENTATION_DIRECTORY); _BORK(B_USER_SERVERS_DIRECTORY); _BORK(B_USER_APPS_DIRECTORY); _BORK(B_USER_BIN_DIRECTORY); _BORK(B_USER_PREFERENCES_DIRECTORY); _BORK(B_USER_ETC_DIRECTORY); _BORK(B_USER_LOG_DIRECTORY); _BORK(B_USER_SPOOL_DIRECTORY); _BORK(B_USER_VAR_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); _BORK(B_PACKAGE_LINKS_DIRECTORY); return B_OK; } #undef _BORK // copy a file including its attributes #define BUFF_SZ 1024*1024 status_t copy_file(entry_ref *ref, const char *to) { char *buff; status_t err = B_OK; //off_t off; //size_t got; (void)ref; (void)to; buff = (char *)malloc(BUFF_SZ); // XXX: TODO free(buff); return err; } int testhook() { status_t err; BString str("/boot/home/config/fonts/ttfonts/toto.ttf"); err = escape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); err = unescape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); return 0; } status_t FindRGBColor(BMessage &message, const char *name, int32 index, rgb_color *c) { #ifdef B_BEOS_VERSION_DANO return message.FindRGBColor(name, index, c); #else const void *data; ssize_t len; status_t err; err = message.FindData(name, B_RGB_COLOR_TYPE, index, &data, &len); if (err < B_OK) return err; if (len > (ssize_t)sizeof(*c)) return E2BIG; // Hack memcpy((void *)c, data, len); return B_OK; #endif } status_t AddRGBColor(BMessage &message, const char *name, rgb_color a_color, type_code type) { #ifdef B_BEOS_VERSION_DANO return message.AddRGBColor(name, a_color, type); #else return message.AddData(name, type, &a_color, sizeof(a_color)); #endif } status_t FindFont(BMessage &message, const char *name, int32 index, BFont *f) { #ifdef B_BEOS_VERSION_DANO return message.FindFlat(name, index, f); #else const void *data; ssize_t len; status_t err = message.FindData(name, 'FONt', index, &data, &len); #define DERR(e) { PRINT(("%s: err: %s\n", __FUNCTION__, strerror(e))); } if (err < B_OK) return err; if (len > (ssize_t)sizeof(*f)) return E2BIG; // Hack: only Dano has BFont : public BFlattenable memcpy((void *)f, data, len); return B_OK; #endif } status_t AddFont(BMessage &message, const char *name, BFont *f, int32 count) { #ifdef B_BEOS_VERSION_DANO return message.AddFlat(name, f, count); #else return message.AddData(name, 'FONt', (void *)f, sizeof(*f), true, count); #endif } <|endoftext|>
<commit_before>//=========================================== // PC-BSD source code // Copyright (c) 2016, PC-BSD Software/iXsystems // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "TrayUI.h" #ifdef __FreeBSD__ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #endif QHash<QString,sysadm_client*> CORES; // hostIP / core QHash<QString, HostMessage> MESSAGES; // "hostIP/message_type", Message Structure // === PUBLIC === sysadm_tray::sysadm_tray() : QSystemTrayIcon(){ CMAN = 0; SDLG = 0; showNotices = false; iconreset = true; cPriority = 0; iconTimer = new QTimer(this); iconTimer->setInterval(1500); //1.5 seconds connect(iconTimer, SIGNAL(timeout()), this, SLOT(UpdateIcon()) ); //Load any CORES updateCoreList(); //Setup the tray icon UpdateIcon(); connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayActivated()) ); //Setup the message menu msgMenu = new QMenu(); msgMenu->setIcon( QIcon(":/icons/black/inbox.svg") ); QAction *act = msgMenu->addAction(QIcon(":/icons/black/trash.svg"), tr("Hide all messages")); act->setWhatsThis("clearall"); QFont fnt = act->font(); fnt.setItalic(true); act->setFont(fnt); msgMenu->addSeparator(); connect(msgMenu, SIGNAL(triggered(QAction*)), this, SLOT(MessageTriggered(QAction*)) ); //Setup the menu menu = new MenuItem(0,"",msgMenu); this->setContextMenu(menu); connect(menu, SIGNAL(OpenConnectionManager()), this, SLOT(OpenConnectionManager()) ); connect(menu, SIGNAL(OpenSettings()), this, SLOT(OpenSettings()) ); connect(menu, SIGNAL(CloseApplication()),this, SLOT(CloseApplication()) ); connect(menu, SIGNAL(OpenCore(QString)), this, SLOT(OpenCore(QString)) ); connect(menu, SIGNAL(ShowMessage(HostMessage)), this, SLOT(ShowMessage(HostMessage)) ); connect(menu, SIGNAL(ClearMessage(QString, QString)), this, SLOT(ClearMessage(QString, QString)) ); connect(menu, SIGNAL(UnlockConnections()), this, SLOT(UnlockConnections()) ); connect(menu, SIGNAL(UpdateTrayIcon()), this, SLOT(UpdateIconPriority()) ); QTimer::singleShot(10, menu, SLOT(UpdateMenu()) ); QTimer::singleShot(0,this, SLOT(updateMessageMenu()) ); } sysadm_tray::~sysadm_tray(){ if(CMAN!=0){ delete CMAN; } if(SDLG!=0){ delete SDLG; } delete this->contextMenu(); //Note in docs that the tray does not take ownership of this menu } // === PRIVATE === sysadm_client* sysadm_tray::getCore(QString host){ //simplification to ensure that core always exists fot the given host if(!CORES.contains(host)){ CORES.insert(host, new sysadm_client()); CORES[host]->registerForEvents(sysadm_client::SYSSTATE); #ifdef __FreeBSD__ //Also load the currently-running user for this process and place that into the UI automatically //Note: This will only be valid on FreeBSD systems (since the server is only for FreeBSD) if(host==LOCALHOST){ CORES[host]->openConnection(getlogin(),"",LOCALHOST); } #endif } return CORES[host]; } // === PRIVATE SLOTS === void sysadm_tray::trayActivated(){ qDebug() << "tray activated"; if(this->contextMenu()!=0){ this->contextMenu()->popup( this->geometry().center()); } } // - Application-wide setting changed void sysadm_tray::UpdateWindows(){ //First check for any of the special windows (skip settings window) //if(CMAN!=0){ QTimer::singleShot(0, CMAN, SLOT(UpdateWindow()) ); } //Now do all the open client windows /*for(int i=0; i<CLIENTS.length(); i++){ QTimer::singleShot(0, CLIENTS[i], SLOT(UpdateUI()) ); }*/ } void sysadm_tray::updateCoreList(){ showNotices = false; //First add the localhost to the top of the list (if available) if(sysadm_client::localhostAvailable() ){ getCore(LOCALHOST); } //Now add any known hosts (including connection status) if(!SSL_cfg.isNull()){ QStringList known = settings->allKeys().filter("Hosts/").filter("/username"); //syntax: Hosts/<hostIP>/username = <username> known.sort(); //sort by name //Now add these hosts to the menu for(int i=0; i<known.length(); i++){ QString host = known[i].section("/",1,-1).section("/username",0,0); if(!CORES.contains(host)){ qDebug() << "Connect To Host:" << host; getCore(host); QString user = settings->value(known[i]).toString(); CORES[host]->openConnection(host); } } } QTimer::singleShot(1000, this, SLOT(allowPopups()) ); } void sysadm_tray::ClientClosed(MainUI* client){ qDebug() << "Client Closed"; int index = CLIENTS.indexOf(client); if(index >=0){ CLIENTS.takeAt(index)->deleteLater(); } } //Menu Actions void sysadm_tray::OpenConnectionManager(){ if(CMAN==0){ CMAN = new C_Manager(); connect(CMAN, SIGNAL(SettingsChanged()), menu, SLOT(UpdateMenu()) ); } CMAN->showNormal(); } void sysadm_tray::OpenSettings(){ if(SDLG==0){ SDLG = new SettingsDialog(); connect(SDLG, SIGNAL(updateWindows()), this, SLOT(UpdateWindows()) ); } SDLG->showNormal(); } void sysadm_tray::CloseApplication(){ //perform any cleanup // Disconnect any cores QStringList cores = CORES.keys(); for(int i=0; i<cores.length(); i++){ qDebug() << "Closing Connection:" << CORES[cores[i]]->currentHost(); CORES[ cores[i] ]->closeConnection(); } // Close any clients if(!CLIENTS.isEmpty()){ qDebug() << "Closing open client:" << CLIENTS.length();} for(int i=0; i<CLIENTS.length(); i++){ CLIENTS[i]->close(); } // Delete any cores (should be disconnected by now) for(int i=0; i<cores.length(); i++){ qDebug() << "Deleting Cores..."; delete CORES.take(cores[i]); } QCoreApplication::exit(0); } void sysadm_tray::OpenCore(QString host, QString page){ //See if a window for this host is already open and use that qDebug() << "Open Host Window:" << host; for(int i=0; i<CLIENTS.length(); i++){ if(CLIENTS[i]->currentHost()==host){ //if(CLIENTS[i]->currentCore()->isReady()){ CLIENTS[i]->showNormal(); //} return; } } //Split the host ID into host/bridge if necessary QString b_id = host.section("/",1,-1); if(!b_id.isEmpty()){ host = host.section("/",0,0); } if(getCore(host)->isConnecting()){ return; } //wait - still trying to connect else if(!getCore(host)->isReady()){ if(getCore(host)->needsBaseAuth()){ //Need to use username/password to re-connect QString user = settings->value("Hosts/"+host+"/username").toString(); //Have username already in settings QString pass = QInputDialog::getText(0, host + ": "+tr("Password Required"), QString(tr("Password for %1")).arg(user), QLineEdit::Password); if(!pass.isEmpty()){ getCore(host)->openConnection(user, pass, host); } }else{ getCore(host)->openConnection(); } return; } if(b_id.isEmpty() && getCore(host)->isBridge()){ return; } //Open a new window for this host sysadm_client *core = getCore(host); MainUI *tmp = new MainUI(core, page, b_id); if(core->isReady()){ tmp->showNormal(); } connect(tmp, SIGNAL(ClientClosed(MainUI*)), this, SLOT(ClientClosed(MainUI*)) ); CLIENTS << tmp; } void sysadm_tray::UnlockConnections(){ UpdateIcon(); //Open all the cores updateCoreList(); //Update the menu QTimer::singleShot(0, menu, SLOT(UpdateMenu()) ); QTimer::singleShot(50, this, SLOT(trayActivated()) ); } //Popup Notifications void sysadm_tray::ShowMessage(HostMessage msg){ //qDebug() << "Got Show Message"; bool refreshlist = true; //Update the internal database of messages if(MESSAGES.contains(msg.host_id+"/"+msg.message_id) ){ //see if this message is new or not HostMessage old = MESSAGES[msg.host_id+"/"+msg.message_id]; if(old.message==msg.message /*&& old.date_time > msg.date_time*/){ refreshlist=false; } //same hidden message - don't re-show it else{ MESSAGES.insert(msg.host_id+"/"+msg.message_id, msg); } }else{ MESSAGES.insert(msg.host_id+"/"+msg.message_id, msg); } //Now update the user-viewable menu's if(refreshlist){ QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); } } void sysadm_tray::ClearMessage(QString host, QString msg_id){ //qDebug() << "Clear Message:" << host << msg_id; if(MESSAGES.contains(host+"/"+msg_id)){ MESSAGES.remove(host+"/"+msg_id); QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); } } void sysadm_tray::MessageTriggered(QAction *act){ if(act->whatsThis()=="clearall"){ QStringList keys = MESSAGES.keys(); QDateTime cdt = QDateTime::currentDateTime(); QDateTime delay = cdt.addDays(1); //qDebug() << "Clear all messages:" << cdt << " -to-" << delay; for(int i=0; i<keys.length(); i++){ if(MESSAGES[keys[i]].date_time.secsTo(cdt)>1 ){ HostMessage msg = MESSAGES[keys[i]]; msg.date_time = delay; MESSAGES.insert(keys[i],msg); } } QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); }else if(MESSAGES.contains(act->whatsThis())){ //Open the designated host and hide this message HostMessage msg = MESSAGES[act->whatsThis()]; //Lower the priority down to stop the tray notifications if(msg.priority>2){ msg.priority=2; } //msg.date_time = QDateTime::currentDateTime().addDays(1); //hide for one day if unresolved in the meantime; MESSAGES.insert(act->whatsThis(),msg); QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); if(act->whatsThis().section("/",-1)=="updates"){ OpenCore(msg.host_id, "page_updates"); } else{ OpenCore(msg.host_id); } } } //Function to update the messageMenu void sysadm_tray::updateMessageMenu(){ //qDebug() << "Update Message Menu:"; QStringList keys = MESSAGES.keys(); QList<QAction*> acts = msgMenu->actions(); //First update the existing actions as needed int num = 0; //for the final tally of messages which are visible QDateTime cdt = QDateTime::currentDateTime(); //qDebug() << "Current DT/keys" << cdt << keys; uint cdt_t = cdt.toTime_t(); for(int i=0; i<acts.length(); i++){ //qDebug() << " - Check Act:" << acts[i]->whatsThis(); if(keys.contains(acts[i]->whatsThis()) && (MESSAGES[acts[i]->whatsThis()].date_time.toTime_t() < cdt_t) ){ //qDebug() << " - Update action" << MESSAGES[acts[i]->whatsThis()].date_time; acts[i]->setText( MESSAGES[acts[i]->whatsThis()].message ); acts[i]->setIcon( QIcon(MESSAGES[acts[i]->whatsThis()].iconfile) ); num++; keys.removeAll(acts[i]->whatsThis()); //already handled }else if( acts[i]->whatsThis()!="clearall" && !acts[i]->whatsThis().isEmpty() ) { //qDebug() << " - Remove Action"; msgMenu->removeAction(acts[i]); } } //Now add in any new messages for(int i=0; i<keys.length(); i++){ if(MESSAGES[keys[i]].date_time.secsTo(cdt)>-1){ //qDebug() << " Add new action:" << keys[i]; QAction *act = msgMenu->addAction( QIcon(MESSAGES[keys[i]].iconfile),MESSAGES[keys[i]].message ); act->setWhatsThis(keys[i]); num++; } } //Now update the main menu title to account for the new number of messages QString title = tr("Messages"); if(num>0){ title.prepend("("+QString::number(num)+") "); } msgMenu->setTitle(title); msgMenu->setEnabled(num>0); UpdateIconPriority(); } //Icon Updates void sysadm_tray::UpdateIconPriority(){ int pri = 0; QStringList keys = MESSAGES.keys(); QDateTime cdt = QDateTime::currentDateTime(); //qDebug() << "Update Priority:" << cdt; for(int i=0; i<keys.length(); i++){ //qDebug() << "Check Key:" << keys[i] << MESSAGES[keys[i]].priority << MESSAGES[keys[i]].date_time; if(MESSAGES[keys[i]].date_time.secsTo(cdt) <-1 ){ continue; } //hidden message - ignore it for priorities if(MESSAGES[keys[i]].priority > pri){ pri = MESSAGES[keys[i]].priority; } } cPriority = pri; //save for use //Update the icon right now if(iconTimer->isActive()){ iconTimer->stop(); } iconreset = false; UpdateIcon(); //Now setup the automatic flashing if(cPriority >2 && cPriority < 9){ iconTimer->start(); } } void sysadm_tray::UpdateIcon(){ //qDebug() << "Update Icon:" << cPriority << QDateTime::currentDateTime(); QString icon = ":/icons/custom/sysadm_circle.svg"; if(iconreset || cPriority <3){ if(SSL_cfg.isNull()){ icon = ":/icons/custom/sysadm_circle_grey.png"; } }else if(cPriority < 6){ icon = ":/icons/custom/sysadm_circle_yellow.png"; } else if(cPriority < 9){ icon = ":/icons/custom/sysadm_circle_orange.png"; } else if(cPriority==9){ icon = ":/icons/custom/sysadm_circle_red.png"; } this->setIcon( QIcon(icon) ); //Reset the icon flag as needed (for next run) iconreset = !iconreset; } <commit_msg>Streamline a bit of the closedown operations for sysadm client.<commit_after>//=========================================== // PC-BSD source code // Copyright (c) 2016, PC-BSD Software/iXsystems // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "TrayUI.h" #ifdef __FreeBSD__ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #endif QHash<QString,sysadm_client*> CORES; // hostIP / core QHash<QString, HostMessage> MESSAGES; // "hostIP/message_type", Message Structure // === PUBLIC === sysadm_tray::sysadm_tray() : QSystemTrayIcon(){ CMAN = 0; SDLG = 0; showNotices = false; iconreset = true; cPriority = 0; iconTimer = new QTimer(this); iconTimer->setInterval(1500); //1.5 seconds connect(iconTimer, SIGNAL(timeout()), this, SLOT(UpdateIcon()) ); //Load any CORES updateCoreList(); //Setup the tray icon UpdateIcon(); connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayActivated()) ); //Setup the message menu msgMenu = new QMenu(); msgMenu->setIcon( QIcon(":/icons/black/inbox.svg") ); QAction *act = msgMenu->addAction(QIcon(":/icons/black/trash.svg"), tr("Hide all messages")); act->setWhatsThis("clearall"); QFont fnt = act->font(); fnt.setItalic(true); act->setFont(fnt); msgMenu->addSeparator(); connect(msgMenu, SIGNAL(triggered(QAction*)), this, SLOT(MessageTriggered(QAction*)) ); //Setup the menu menu = new MenuItem(0,"",msgMenu); this->setContextMenu(menu); connect(menu, SIGNAL(OpenConnectionManager()), this, SLOT(OpenConnectionManager()) ); connect(menu, SIGNAL(OpenSettings()), this, SLOT(OpenSettings()) ); connect(menu, SIGNAL(CloseApplication()),this, SLOT(CloseApplication()) ); connect(menu, SIGNAL(OpenCore(QString)), this, SLOT(OpenCore(QString)) ); connect(menu, SIGNAL(ShowMessage(HostMessage)), this, SLOT(ShowMessage(HostMessage)) ); connect(menu, SIGNAL(ClearMessage(QString, QString)), this, SLOT(ClearMessage(QString, QString)) ); connect(menu, SIGNAL(UnlockConnections()), this, SLOT(UnlockConnections()) ); connect(menu, SIGNAL(UpdateTrayIcon()), this, SLOT(UpdateIconPriority()) ); QTimer::singleShot(10, menu, SLOT(UpdateMenu()) ); QTimer::singleShot(0,this, SLOT(updateMessageMenu()) ); } sysadm_tray::~sysadm_tray(){ if(CMAN!=0){ CMAN->deleteLater(); } if(SDLG!=0){ SDLG->deleteLater(); } delete this->contextMenu(); //Note in docs that the tray does not take ownership of this menu } // === PRIVATE === sysadm_client* sysadm_tray::getCore(QString host){ //simplification to ensure that core always exists fot the given host if(!CORES.contains(host)){ CORES.insert(host, new sysadm_client()); CORES[host]->registerForEvents(sysadm_client::SYSSTATE); #ifdef __FreeBSD__ //Also load the currently-running user for this process and place that into the UI automatically //Note: This will only be valid on FreeBSD systems (since the server is only for FreeBSD) if(host==LOCALHOST){ CORES[host]->openConnection(getlogin(),"",LOCALHOST); } #endif } return CORES[host]; } // === PRIVATE SLOTS === void sysadm_tray::trayActivated(){ qDebug() << "tray activated"; if(this->contextMenu()!=0){ this->contextMenu()->popup( this->geometry().center()); } } // - Application-wide setting changed void sysadm_tray::UpdateWindows(){ //First check for any of the special windows (skip settings window) //if(CMAN!=0){ QTimer::singleShot(0, CMAN, SLOT(UpdateWindow()) ); } //Now do all the open client windows /*for(int i=0; i<CLIENTS.length(); i++){ QTimer::singleShot(0, CLIENTS[i], SLOT(UpdateUI()) ); }*/ } void sysadm_tray::updateCoreList(){ showNotices = false; //First add the localhost to the top of the list (if available) if(sysadm_client::localhostAvailable() ){ getCore(LOCALHOST); } //Now add any known hosts (including connection status) if(!SSL_cfg.isNull()){ QStringList known = settings->allKeys().filter("Hosts/").filter("/username"); //syntax: Hosts/<hostIP>/username = <username> known.sort(); //sort by name //Now add these hosts to the menu for(int i=0; i<known.length(); i++){ QString host = known[i].section("/",1,-1).section("/username",0,0); if(!CORES.contains(host)){ qDebug() << "Connect To Host:" << host; getCore(host); QString user = settings->value(known[i]).toString(); CORES[host]->openConnection(host); } } } QTimer::singleShot(1000, this, SLOT(allowPopups()) ); } void sysadm_tray::ClientClosed(MainUI* client){ qDebug() << "Client Closed"; int index = CLIENTS.indexOf(client); if(index >=0){ CLIENTS.takeAt(index)->deleteLater(); } } //Menu Actions void sysadm_tray::OpenConnectionManager(){ if(CMAN==0){ CMAN = new C_Manager(); connect(CMAN, SIGNAL(SettingsChanged()), menu, SLOT(UpdateMenu()) ); } CMAN->showNormal(); } void sysadm_tray::OpenSettings(){ if(SDLG==0){ SDLG = new SettingsDialog(); connect(SDLG, SIGNAL(updateWindows()), this, SLOT(UpdateWindows()) ); } SDLG->showNormal(); } void sysadm_tray::CloseApplication(){ //perform any cleanup // Disconnect any cores QStringList cores = CORES.keys(); for(int i=0; i<cores.length(); i++){ qDebug() << "Closing Connection:" << CORES[cores[i]]->currentHost(); QTimer::singleShot(0, CORES[ cores[i] ], SLOT(closeConnection())); } // Close any clients if(!CLIENTS.isEmpty()){ qDebug() << "Closing open client:" << CLIENTS.length();} for(int i=0; i<CLIENTS.length(); i++){ CLIENTS[i]->deleteLater(); } QApplication::processEvents(); // Delete any cores (should be disconnected by now) for(int i=0; i<cores.length(); i++){ QApplication::processEvents(); qDebug() << "Deleting Cores..."; delete CORES.take(cores[i]); } QCoreApplication::exit(0); } void sysadm_tray::OpenCore(QString host, QString page){ //See if a window for this host is already open and use that qDebug() << "Open Host Window:" << host; for(int i=0; i<CLIENTS.length(); i++){ if(CLIENTS[i]->currentHost()==host){ //if(CLIENTS[i]->currentCore()->isReady()){ CLIENTS[i]->showNormal(); //} return; } } //Split the host ID into host/bridge if necessary QString b_id = host.section("/",1,-1); if(!b_id.isEmpty()){ host = host.section("/",0,0); } if(getCore(host)->isConnecting()){ return; } //wait - still trying to connect else if(!getCore(host)->isReady()){ if(getCore(host)->needsBaseAuth()){ //Need to use username/password to re-connect QString user = settings->value("Hosts/"+host+"/username").toString(); //Have username already in settings QString pass = QInputDialog::getText(0, host + ": "+tr("Password Required"), QString(tr("Password for %1")).arg(user), QLineEdit::Password); if(!pass.isEmpty()){ getCore(host)->openConnection(user, pass, host); } }else{ getCore(host)->openConnection(); } return; } if(b_id.isEmpty() && getCore(host)->isBridge()){ return; } //Open a new window for this host sysadm_client *core = getCore(host); MainUI *tmp = new MainUI(core, page, b_id); if(core->isReady()){ tmp->showNormal(); } connect(tmp, SIGNAL(ClientClosed(MainUI*)), this, SLOT(ClientClosed(MainUI*)) ); CLIENTS << tmp; } void sysadm_tray::UnlockConnections(){ UpdateIcon(); //Open all the cores updateCoreList(); //Update the menu QTimer::singleShot(0, menu, SLOT(UpdateMenu()) ); QTimer::singleShot(50, this, SLOT(trayActivated()) ); } //Popup Notifications void sysadm_tray::ShowMessage(HostMessage msg){ //qDebug() << "Got Show Message"; bool refreshlist = true; //Update the internal database of messages if(MESSAGES.contains(msg.host_id+"/"+msg.message_id) ){ //see if this message is new or not HostMessage old = MESSAGES[msg.host_id+"/"+msg.message_id]; if(old.message==msg.message /*&& old.date_time > msg.date_time*/){ refreshlist=false; } //same hidden message - don't re-show it else{ MESSAGES.insert(msg.host_id+"/"+msg.message_id, msg); } }else{ MESSAGES.insert(msg.host_id+"/"+msg.message_id, msg); } //Now update the user-viewable menu's if(refreshlist){ QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); } } void sysadm_tray::ClearMessage(QString host, QString msg_id){ //qDebug() << "Clear Message:" << host << msg_id; if(MESSAGES.contains(host+"/"+msg_id)){ MESSAGES.remove(host+"/"+msg_id); QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); } } void sysadm_tray::MessageTriggered(QAction *act){ if(act->whatsThis()=="clearall"){ QStringList keys = MESSAGES.keys(); QDateTime cdt = QDateTime::currentDateTime(); QDateTime delay = cdt.addDays(1); //qDebug() << "Clear all messages:" << cdt << " -to-" << delay; for(int i=0; i<keys.length(); i++){ if(MESSAGES[keys[i]].date_time.secsTo(cdt)>1 ){ HostMessage msg = MESSAGES[keys[i]]; msg.date_time = delay; MESSAGES.insert(keys[i],msg); } } QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); }else if(MESSAGES.contains(act->whatsThis())){ //Open the designated host and hide this message HostMessage msg = MESSAGES[act->whatsThis()]; //Lower the priority down to stop the tray notifications if(msg.priority>2){ msg.priority=2; } //msg.date_time = QDateTime::currentDateTime().addDays(1); //hide for one day if unresolved in the meantime; MESSAGES.insert(act->whatsThis(),msg); QTimer::singleShot(10,this, SLOT(updateMessageMenu()) ); if(act->whatsThis().section("/",-1)=="updates"){ OpenCore(msg.host_id, "page_updates"); } else{ OpenCore(msg.host_id); } } } //Function to update the messageMenu void sysadm_tray::updateMessageMenu(){ //qDebug() << "Update Message Menu:"; QStringList keys = MESSAGES.keys(); QList<QAction*> acts = msgMenu->actions(); //First update the existing actions as needed int num = 0; //for the final tally of messages which are visible QDateTime cdt = QDateTime::currentDateTime(); //qDebug() << "Current DT/keys" << cdt << keys; uint cdt_t = cdt.toTime_t(); for(int i=0; i<acts.length(); i++){ //qDebug() << " - Check Act:" << acts[i]->whatsThis(); if(keys.contains(acts[i]->whatsThis()) && (MESSAGES[acts[i]->whatsThis()].date_time.toTime_t() < cdt_t) ){ //qDebug() << " - Update action" << MESSAGES[acts[i]->whatsThis()].date_time; acts[i]->setText( MESSAGES[acts[i]->whatsThis()].message ); acts[i]->setIcon( QIcon(MESSAGES[acts[i]->whatsThis()].iconfile) ); num++; keys.removeAll(acts[i]->whatsThis()); //already handled }else if( acts[i]->whatsThis()!="clearall" && !acts[i]->whatsThis().isEmpty() ) { //qDebug() << " - Remove Action"; msgMenu->removeAction(acts[i]); } } //Now add in any new messages for(int i=0; i<keys.length(); i++){ if(MESSAGES[keys[i]].date_time.secsTo(cdt)>-1){ //qDebug() << " Add new action:" << keys[i]; QAction *act = msgMenu->addAction( QIcon(MESSAGES[keys[i]].iconfile),MESSAGES[keys[i]].message ); act->setWhatsThis(keys[i]); num++; } } //Now update the main menu title to account for the new number of messages QString title = tr("Messages"); if(num>0){ title.prepend("("+QString::number(num)+") "); } msgMenu->setTitle(title); msgMenu->setEnabled(num>0); UpdateIconPriority(); } //Icon Updates void sysadm_tray::UpdateIconPriority(){ int pri = 0; QStringList keys = MESSAGES.keys(); QDateTime cdt = QDateTime::currentDateTime(); //qDebug() << "Update Priority:" << cdt; for(int i=0; i<keys.length(); i++){ //qDebug() << "Check Key:" << keys[i] << MESSAGES[keys[i]].priority << MESSAGES[keys[i]].date_time; if(MESSAGES[keys[i]].date_time.secsTo(cdt) <-1 ){ continue; } //hidden message - ignore it for priorities if(MESSAGES[keys[i]].priority > pri){ pri = MESSAGES[keys[i]].priority; } } cPriority = pri; //save for use //Update the icon right now if(iconTimer->isActive()){ iconTimer->stop(); } iconreset = false; UpdateIcon(); //Now setup the automatic flashing if(cPriority >2 && cPriority < 9){ iconTimer->start(); } } void sysadm_tray::UpdateIcon(){ //qDebug() << "Update Icon:" << cPriority << QDateTime::currentDateTime(); QString icon = ":/icons/custom/sysadm_circle.svg"; if(iconreset || cPriority <3){ if(SSL_cfg.isNull()){ icon = ":/icons/custom/sysadm_circle_grey.png"; } }else if(cPriority < 6){ icon = ":/icons/custom/sysadm_circle_yellow.png"; } else if(cPriority < 9){ icon = ":/icons/custom/sysadm_circle_orange.png"; } else if(cPriority==9){ icon = ":/icons/custom/sysadm_circle_red.png"; } this->setIcon( QIcon(icon) ); //Reset the icon flag as needed (for next run) iconreset = !iconreset; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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 Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // C++ #include <iostream> // This class #include "grins/grins_enums.h" #include "grins/mesh_builder.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/string_to_enum.h" #include "libmesh/mesh_generation.h" #include "libmesh/mesh_modification.h" #include "libmesh/mesh_refinement.h" #include "libmesh/parallel_mesh.h" #include "libmesh/parsed_function.h" #include "libmesh/serial_mesh.h" namespace GRINS { MeshBuilder::MeshBuilder() { return; } MeshBuilder::~MeshBuilder() { return; } std::tr1::shared_ptr<libMesh::UnstructuredMesh> MeshBuilder::build (const GetPot& input, const libMesh::Parallel::Communicator &comm) { // First, read all needed variables std::string mesh_option = input("mesh-options/mesh_option", "NULL"); std::string mesh_filename = input("mesh-options/mesh_filename", "NULL"); libMesh::Real domain_x1_min = input("mesh-options/domain_x1_min", 0.0); libMesh::Real domain_x2_min = input("mesh-options/domain_x2_min", 0.0); libMesh::Real domain_x3_min = input("mesh-options/domain_x3_min", 0.0); libMesh::Real domain_x1_max = input("mesh-options/domain_x1_max", 1.0); libMesh::Real domain_x2_max = input("mesh-options/domain_x2_max", 1.0); libMesh::Real domain_x3_max = input("mesh-options/domain_x3_max", 1.0); int mesh_nx1 = input("mesh-options/mesh_nx1", -1); int mesh_nx2 = input("mesh-options/mesh_nx2", -1); int mesh_nx3 = input("mesh-options/mesh_nx3", -1); std::string element_type = input("mesh-options/element_type", "NULL"); // Make sure the user told us what to do if(mesh_option == "NULL") { std::cerr << " MeshBuilder::read_input_options :" << " mesh-options/mesh_option NOT specified " << std::endl; libmesh_error(); } // Create UnstructuredMesh object (defaults to dimension 1). libMesh::UnstructuredMesh* mesh; // Were we specifically asked to use a ParallelMesh or SerialMesh? std::string mesh_class = input("mesh-options/mesh_class", "default"); if (mesh_class == "parallel") mesh = new libMesh::ParallelMesh(comm); else if (mesh_class == "serial") mesh = new libMesh::SerialMesh(comm); else if (mesh_class == "default") mesh = new libMesh::Mesh(comm); else { std::cerr << " MeshBuilder::build:" << " mesh-options/mesh_class had invalid value " << mesh_class << std::endl; libmesh_error(); } if(mesh_option=="read_mesh_from_file") { // According to Roy Stogner, the only read format // that won't properly reset the dimension is gmsh. /*! \todo Need to a check a GMSH meshes */ mesh->read(mesh_filename); } else if(mesh_option=="create_1D_mesh") { if(element_type=="NULL") { element_type = "EDGE3"; } GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_line(*mesh, mesh_nx1, domain_x1_min, domain_x1_max, element_enum_type); } else if(mesh_option=="create_2D_mesh") { if(element_type=="NULL") { element_type = "TRI6"; } // Reset mesh dimension to 2. mesh->set_mesh_dimension(2); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_square(*mesh, mesh_nx1, mesh_nx2, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, element_enum_type); } else if(mesh_option=="create_3D_mesh") { if(element_type=="NULL") { element_type = "TET10"; } // Reset mesh dimension to 3. mesh->set_mesh_dimension(3); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_cube(*mesh, mesh_nx1, mesh_nx2, mesh_nx3, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, domain_x3_min, domain_x3_max, element_enum_type); } else { std::cerr << " MeshBuilder::build_mesh :" << " mesh-options/mesh_option [" << mesh_option << "] NOT supported " << std::endl; libmesh_error(); } std::string redistribution_function_string = input("mesh-options/redistribute", std::string("0")); if (redistribution_function_string != "0") { libMesh::ParsedFunction<libMesh::Real> redistribution_function(redistribution_function_string); libMesh::MeshTools::Modification::redistribute (*mesh, redistribution_function); // Redistribution can create distortions *within* second-order // elements, which can then be magnified by refinement. Let's // undistort everything by converting to first order and back // if necessary. // FIXME - this only works for meshes with uniform geometry // order equal to FIRST or (full-order) SECOND. const libMesh::Elem *elem = *mesh->elements_begin(); if (elem->default_order() != libMesh::FIRST) { mesh->all_first_order(); mesh->all_second_order(); } } int uniformly_refine = input("mesh-options/uniformly_refine", 0); if( uniformly_refine > 0 ) { libMesh::MeshRefinement(*mesh).uniformly_refine(uniformly_refine); } std::string h_refinement_function_string = input("mesh-options/locally_h_refine", std::string("0")); if (h_refinement_function_string != "0") { libMesh::ParsedFunction<libMesh::Real> h_refinement_function(h_refinement_function_string); libMesh::MeshRefinement mesh_refinement(*mesh); libMesh::dof_id_type found_refinements = 0; do { found_refinements = 0; libMesh::MeshBase::element_iterator elem_it = mesh->active_local_elements_begin(); libMesh::MeshBase::element_iterator elem_end = mesh->active_local_elements_end(); for (; elem_it != elem_end; ++elem_it) { libMesh::Elem *elem = *elem_it; const libMesh::Real refinement_val = h_refinement_function(elem->centroid()); const unsigned int n_refinements = refinement_val > 0 ? refinement_val : 0; if (elem->level() - uniformly_refine < n_refinements) { elem->set_refinement_flag(libMesh::Elem::REFINE); found_refinements++; } } if (found_refinements) { std::cout << "Found " << found_refinements << " elements to locally refine" << std::endl; mesh_refinement.refine_and_coarsen_elements(); } } while(found_refinements); } return std::tr1::shared_ptr<libMesh::UnstructuredMesh>(mesh); } } // namespace GRINS <commit_msg>Bugfix for locally_h_refine in parallel<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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 Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // C++ #include <iostream> // This class #include "grins/grins_enums.h" #include "grins/mesh_builder.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/string_to_enum.h" #include "libmesh/mesh_generation.h" #include "libmesh/mesh_modification.h" #include "libmesh/mesh_refinement.h" #include "libmesh/parallel_mesh.h" #include "libmesh/parsed_function.h" #include "libmesh/serial_mesh.h" namespace GRINS { MeshBuilder::MeshBuilder() { return; } MeshBuilder::~MeshBuilder() { return; } std::tr1::shared_ptr<libMesh::UnstructuredMesh> MeshBuilder::build (const GetPot& input, const libMesh::Parallel::Communicator &comm) { // First, read all needed variables std::string mesh_option = input("mesh-options/mesh_option", "NULL"); std::string mesh_filename = input("mesh-options/mesh_filename", "NULL"); libMesh::Real domain_x1_min = input("mesh-options/domain_x1_min", 0.0); libMesh::Real domain_x2_min = input("mesh-options/domain_x2_min", 0.0); libMesh::Real domain_x3_min = input("mesh-options/domain_x3_min", 0.0); libMesh::Real domain_x1_max = input("mesh-options/domain_x1_max", 1.0); libMesh::Real domain_x2_max = input("mesh-options/domain_x2_max", 1.0); libMesh::Real domain_x3_max = input("mesh-options/domain_x3_max", 1.0); int mesh_nx1 = input("mesh-options/mesh_nx1", -1); int mesh_nx2 = input("mesh-options/mesh_nx2", -1); int mesh_nx3 = input("mesh-options/mesh_nx3", -1); std::string element_type = input("mesh-options/element_type", "NULL"); // Make sure the user told us what to do if(mesh_option == "NULL") { std::cerr << " MeshBuilder::read_input_options :" << " mesh-options/mesh_option NOT specified " << std::endl; libmesh_error(); } // Create UnstructuredMesh object (defaults to dimension 1). libMesh::UnstructuredMesh* mesh; // Were we specifically asked to use a ParallelMesh or SerialMesh? std::string mesh_class = input("mesh-options/mesh_class", "default"); if (mesh_class == "parallel") mesh = new libMesh::ParallelMesh(comm); else if (mesh_class == "serial") mesh = new libMesh::SerialMesh(comm); else if (mesh_class == "default") mesh = new libMesh::Mesh(comm); else { std::cerr << " MeshBuilder::build:" << " mesh-options/mesh_class had invalid value " << mesh_class << std::endl; libmesh_error(); } if(mesh_option=="read_mesh_from_file") { // According to Roy Stogner, the only read format // that won't properly reset the dimension is gmsh. /*! \todo Need to a check a GMSH meshes */ mesh->read(mesh_filename); } else if(mesh_option=="create_1D_mesh") { if(element_type=="NULL") { element_type = "EDGE3"; } GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_line(*mesh, mesh_nx1, domain_x1_min, domain_x1_max, element_enum_type); } else if(mesh_option=="create_2D_mesh") { if(element_type=="NULL") { element_type = "TRI6"; } // Reset mesh dimension to 2. mesh->set_mesh_dimension(2); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_square(*mesh, mesh_nx1, mesh_nx2, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, element_enum_type); } else if(mesh_option=="create_3D_mesh") { if(element_type=="NULL") { element_type = "TET10"; } // Reset mesh dimension to 3. mesh->set_mesh_dimension(3); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_cube(*mesh, mesh_nx1, mesh_nx2, mesh_nx3, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, domain_x3_min, domain_x3_max, element_enum_type); } else { std::cerr << " MeshBuilder::build_mesh :" << " mesh-options/mesh_option [" << mesh_option << "] NOT supported " << std::endl; libmesh_error(); } std::string redistribution_function_string = input("mesh-options/redistribute", std::string("0")); if (redistribution_function_string != "0") { libMesh::ParsedFunction<libMesh::Real> redistribution_function(redistribution_function_string); libMesh::MeshTools::Modification::redistribute (*mesh, redistribution_function); // Redistribution can create distortions *within* second-order // elements, which can then be magnified by refinement. Let's // undistort everything by converting to first order and back // if necessary. // FIXME - this only works for meshes with uniform geometry // order equal to FIRST or (full-order) SECOND. const libMesh::Elem *elem = *mesh->elements_begin(); if (elem->default_order() != libMesh::FIRST) { mesh->all_first_order(); mesh->all_second_order(); } } int uniformly_refine = input("mesh-options/uniformly_refine", 0); if( uniformly_refine > 0 ) { libMesh::MeshRefinement(*mesh).uniformly_refine(uniformly_refine); } std::string h_refinement_function_string = input("mesh-options/locally_h_refine", std::string("0")); if (h_refinement_function_string != "0") { libMesh::ParsedFunction<libMesh::Real> h_refinement_function(h_refinement_function_string); libMesh::MeshRefinement mesh_refinement(*mesh); libMesh::dof_id_type found_refinements = 0; do { found_refinements = 0; libMesh::MeshBase::element_iterator elem_it = mesh->active_elements_begin(); libMesh::MeshBase::element_iterator elem_end = mesh->active_elements_end(); for (; elem_it != elem_end; ++elem_it) { libMesh::Elem *elem = *elem_it; const libMesh::Real refinement_val = h_refinement_function(elem->centroid()); const unsigned int n_refinements = refinement_val > 0 ? refinement_val : 0; if (elem->level() - uniformly_refine < n_refinements) { elem->set_refinement_flag(libMesh::Elem::REFINE); found_refinements++; } } comm.max(found_refinements); if (found_refinements) { std::cout << "Found up to " << found_refinements << " elements to refine on each processor" << std::endl; mesh_refinement.refine_and_coarsen_elements(); } } while(found_refinements); } return std::tr1::shared_ptr<libMesh::UnstructuredMesh>(mesh); } } // namespace GRINS <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Problem.h" #include "Factory.h" Problem::Problem(): _output_initial(false) { unsigned int n_threads = libMesh::n_threads(); _real_zero.resize(n_threads); _zero.resize(n_threads); _grad_zero.resize(n_threads); _second_zero.resize(n_threads); _functions.resize(n_threads); } Problem::~Problem() { unsigned int n_threads = libMesh::n_threads(); for (unsigned int i = 0; i < n_threads; i++) { _zero[i].release(); _grad_zero[i].release(); _second_zero[i].release(); } _real_zero.release(); _zero.release(); _grad_zero.release(); _second_zero.release(); for (unsigned int i = 0; i < n_threads; i++) for (std::map<std::string, Function *>::iterator it = _functions[i].begin(); it != _functions[i].end(); ++it) delete it->second; } void Problem::addFunction(std::string type, const std::string & name, InputParameters parameters) { parameters.set<Problem *>("_problem") = this; for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++) { parameters.set<THREAD_ID>("_tid") = tid; Function * func = static_cast<Function *>(Factory::instance()->create(type, name, parameters)); _functions[tid][name] = func; } } Function & Problem::getFunction(const std::string & name, THREAD_ID tid) { return *_functions[tid][name]; } <commit_msg>Problem::_real_zero was not properly initialized and caused some troubles in threaded runs<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Problem.h" #include "Factory.h" Problem::Problem(): _output_initial(false) { unsigned int n_threads = libMesh::n_threads(); _real_zero.resize(n_threads, 0.); _zero.resize(n_threads); _grad_zero.resize(n_threads); _second_zero.resize(n_threads); _functions.resize(n_threads); } Problem::~Problem() { unsigned int n_threads = libMesh::n_threads(); for (unsigned int i = 0; i < n_threads; i++) { _zero[i].release(); _grad_zero[i].release(); _second_zero[i].release(); } _real_zero.release(); _zero.release(); _grad_zero.release(); _second_zero.release(); for (unsigned int i = 0; i < n_threads; i++) for (std::map<std::string, Function *>::iterator it = _functions[i].begin(); it != _functions[i].end(); ++it) delete it->second; } void Problem::addFunction(std::string type, const std::string & name, InputParameters parameters) { parameters.set<Problem *>("_problem") = this; for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++) { parameters.set<THREAD_ID>("_tid") = tid; Function * func = static_cast<Function *>(Factory::instance()->create(type, name, parameters)); _functions[tid][name] = func; } } Function & Problem::getFunction(const std::string & name, THREAD_ID tid) { return *_functions[tid][name]; } <|endoftext|>
<commit_before>#ifndef DUNE_MULTISCALE_SRC_COMMON_HH #define DUNE_MULTISCALE_SRC_COMMON_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #undef ENABLE_MPI // polynomial order of discrete space #ifndef POLORDER #define POLORDER 1 #endif #ifndef USE_GRAPE #define USE_GRAPE HAVE_GRAPE #endif #define USE_TWISTFREE_MAPPER #define VERBOSE false #include <iostream> #include <sstream> #include <stdio.h> #include <stdlib.h> // ----------------------------- #include <dune/common/mpihelper.hh> // An initializer of MPI #include <dune/common/exceptions.hh> // We use exceptions #include <dune/common/unused.hh> #if HAVE_GRAPE #include <dune/grid/io/visual/grapedatadisplay.hh> #endif // to display data with ParaView: #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/fem/io/file/dataoutput.hh> #include <dune/fem/io/parameter.hh> #include <dune/fem/io/file/datawriter.hh> #include <dune/fem/gridpart/common/gridpart.hh> #include <dune/multiscale/grids/periodicgridpart/periodicgridpart.hh> #include <dune/fem/gridpart/adaptiveleafgridpart.hh> #include <dune/fem/space/lagrangespace.hh> #include <dune/fem/function/adaptivefunction.hh> #include <dune/fem/operator/matrix/spmatrix.hh> #include <dune/fem/space/common/adaptmanager.hh> #include <dune/fem/solver/inverseoperators.hh> #include <dune/fem/misc/mpimanager.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/debug.hh> #include <dune/stuff/common/misc.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/profiler.hh> void init(int argc, char** argv) { namespace DSC = Dune::Stuff::Common; Dune::MPIManager::initialize(argc, argv); DSC::Config().readCommandLine(argc, argv); // LOG_NONE = 1, LOG_ERROR = 2, LOG_INFO = 4,LOG_DEBUG = 8,LOG_CONSOLE = 16,LOG_FILE = 32 // --> LOG_ERROR | LOG_INFO | LOG_DEBUG | LOG_CONSOLE | LOG_FILE = 62 const bool useLogger = false; DSC::Logger().create(DSC_CONFIG_GETB("logging.level", 62, useLogger), DSC_CONFIG_GETB("logging.file", std::string(argv[0]) + ".log", useLogger), DSC_CONFIG_GETB("global.datadir", "data", useLogger), DSC_CONFIG_GETB("logging.dir", "log" /*path below datadir*/, useLogger) ); DSC_CONFIG.setRecordDefaults(true); DSC_PROFILER.setOutputdir(DSC_CONFIG_GET("global.datadir", "data")); } // init #endif // DUNE_MULTISCALE_SRC_COMMON_HH <commit_msg>Code runs on Mac again.<commit_after>#ifndef DUNE_MULTISCALE_SRC_COMMON_HH #define DUNE_MULTISCALE_SRC_COMMON_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG // polynomial order of discrete space #ifndef POLORDER #define POLORDER 1 #endif #ifndef USE_GRAPE #define USE_GRAPE HAVE_GRAPE #endif #define USE_TWISTFREE_MAPPER #define VERBOSE false #include <iostream> #include <sstream> #include <stdio.h> #include <stdlib.h> // ----------------------------- #include <dune/common/mpihelper.hh> // An initializer of MPI #include <dune/common/exceptions.hh> // We use exceptions #include <dune/common/unused.hh> #if HAVE_GRAPE #include <dune/grid/io/visual/grapedatadisplay.hh> #endif // to display data with ParaView: #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/fem/io/file/dataoutput.hh> #include <dune/fem/io/parameter.hh> #include <dune/fem/io/file/datawriter.hh> #include <dune/fem/gridpart/common/gridpart.hh> #include <dune/multiscale/grids/periodicgridpart/periodicgridpart.hh> #include <dune/fem/gridpart/adaptiveleafgridpart.hh> #include <dune/fem/space/lagrangespace.hh> #include <dune/fem/function/adaptivefunction.hh> #include <dune/fem/operator/matrix/spmatrix.hh> #include <dune/fem/space/common/adaptmanager.hh> #include <dune/fem/solver/inverseoperators.hh> #include <dune/fem/misc/mpimanager.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/debug.hh> #include <dune/stuff/common/misc.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/profiler.hh> void init(int argc, char** argv) { namespace DSC = Dune::Stuff::Common; Dune::MPIManager::initialize(argc, argv); DSC::Config().readCommandLine(argc, argv); // LOG_NONE = 1, LOG_ERROR = 2, LOG_INFO = 4,LOG_DEBUG = 8,LOG_CONSOLE = 16,LOG_FILE = 32 // --> LOG_ERROR | LOG_INFO | LOG_DEBUG | LOG_CONSOLE | LOG_FILE = 62 const bool useLogger = false; DSC::Logger().create(DSC_CONFIG_GETB("logging.level", 62, useLogger), DSC_CONFIG_GETB("logging.file", std::string(argv[0]) + ".log", useLogger), DSC_CONFIG_GETB("global.datadir", "data", useLogger), DSC_CONFIG_GETB("logging.dir", "log" /*path below datadir*/, useLogger) ); DSC_CONFIG.setRecordDefaults(true); DSC_PROFILER.setOutputdir(DSC_CONFIG_GET("global.datadir", "data")); } // init #endif // DUNE_MULTISCALE_SRC_COMMON_HH <|endoftext|>
<commit_before>// Time: O(n) // Space: O(h) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { ostringstream out; serializeHelper(root, out); return out.str(); } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { istringstream in(data); return deserializeHelper(in); } private: void serializeHelper(const TreeNode *root, ostringstream& out) { if (!root) { out << "# "; } else { out << root->val << " "; serializeHelper(root->left, out); serializeHelper(root->right, out); } } TreeNode *deserializeHelper(istringstream& in) { string val; in >> val; if (val == "#") { return nullptr; } else { TreeNode* root = new TreeNode(stoi(val)); root->left = deserializeHelper(in); root->right = deserializeHelper(in); return root; } } }; <commit_msg>Update binary-tree-serialization.cpp<commit_after>// Time: O(n) // Space: O(h) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { string output; serializeHelper(root, &output); return output; } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { TreeNode *root = nullptr; int start = 0; deserializeHelper(data, &start, &root); return root; } private: bool getNumber(const string &data, int *start, int *num) { int sign = 1; if (data[*start] == '#') { *start += 2; // Skip "# ". return false; } else if (data[*start] == '-') { sign = -1; ++(*start); } for (*num = 0; isdigit(data[*start]); ++(*start)) { *num = *num * 10 + data[*start] - '0'; } *num *= sign; ++(*start); // Skip " ". return true; } void serializeHelper(const TreeNode *root, string *prev) { if (!root) { prev->append("# "); } else { prev->append(to_string(root->val).append(" ")); serializeHelper(root->left, prev); serializeHelper(root->right, prev); } } void deserializeHelper(const string& data, int *start, TreeNode **root) { int num; if (!getNumber(data, start, &num)) { *root = nullptr; } else { *root = new TreeNode(num); deserializeHelper(data, start, &((*root)->left)); deserializeHelper(data, start, &((*root)->right)); } } }; // Time: O(n) // Space: O(n) class Solution2 { public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { ostringstream out; serializeHelper(root, out); return out.str(); } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { istringstream in(data); // Space: O(n) return deserializeHelper(in); } private: void serializeHelper(const TreeNode *root, ostringstream& out) { if (!root) { out << "# "; } else { out << root->val << " "; serializeHelper(root->left, out); serializeHelper(root->right, out); } } TreeNode *deserializeHelper(istringstream& in) { string val; in >> val; if (val == "#") { return nullptr; } else { TreeNode* root = new TreeNode(stoi(val)); root->left = deserializeHelper(in); root->right = deserializeHelper(in); return root; } } }; <|endoftext|>
<commit_before>//FRAGMENT(includes) #include <seqan/seeds.h> using namespace seqan; // FRAGMENT(writeSeed) template<typename TSeed, typename TSeq> void writeSeed(TSeed & seed, TSeq const & seq0, TSeq const & seq1) { std::cout << "Seed from position " << leftPosition(seed, 0); std::cout << " to " << rightPosition(seed, 0) << ": "; std::cout << infix(seq0, leftPosition(seed, 0), rightPosition(seed, 0)+1) << std::endl; std::cout << "Seed from position " << leftPosition(seed, 1); std::cout << " to " << rightPosition(seed, 1) << ": "; std::cout << infix(seq1, leftPosition(seed, 1), rightPosition(seed, 1)+1) << std::endl; } //FRAGMENT(main) int main() { typedef Seed<> TSeed; DnaString seq0 = "ATCATCAGTTATACTTTACCCAGGC"; DnaString seq1 = "ATTCAGCATACTTTCCATGAAGC"; TSeed seed(10, 7, 7); writeSeed(seed, seq0, seq1); // FRAGMENT(extension) typedef int TScore; Score<TScore, Simple> scoreMatrix(1, -1, -1); TScore scoreDropOff = 1; extendSeed(seed, scoreDropOff, scoreMatrix, seq0, seq1, 2, GappedXDrop()); std::cout << std::endl << "After extension:" << std::endl; writeSeed(seed, seq0, seq1); // FRAGMENT(banded-alignment) Align<DnaString> align; resize(rows(alignment), 2); assignSource(row(align, 0), seq0); assignSource(row(align, 1), seq1); std::cout << std::endl << "Banded Alignment:" << std::endl; std::cout << "Score: " << bandedAlignment(align, seed, 2, scoreMatrix) << std::endl; std::cout << align; // FRAGMENT(global-alignment) Align<DnaString> globalAlign; resize(rows(globalAlign), 2); assignSource(row(globalAlign, 0), seq0); assignSource(row(globalAlign, 1), seq1); std::cout << std::endl << "Global Alignment:" << std::endl; std::cout << "Score: " << globalAlignment(globalAlign, scoreMatrix) << std::endl; std::cout << globalAlign; return 0; } <commit_msg>small mistake in seed extension example<commit_after>//FRAGMENT(includes) #include <seqan/seeds.h> using namespace seqan; // FRAGMENT(writeSeed) template<typename TSeed, typename TSeq> void writeSeed(TSeed & seed, TSeq const & seq0, TSeq const & seq1) { std::cout << "Seed from position " << leftPosition(seed, 0); std::cout << " to " << rightPosition(seed, 0) << ": "; std::cout << infix(seq0, leftPosition(seed, 0), rightPosition(seed, 0)+1) << std::endl; std::cout << "Seed from position " << leftPosition(seed, 1); std::cout << " to " << rightPosition(seed, 1) << ": "; std::cout << infix(seq1, leftPosition(seed, 1), rightPosition(seed, 1)+1) << std::endl; } //FRAGMENT(main) int main() { typedef Seed<> TSeed; DnaString seq0 = "ATCATCAGTTATACTTTACCCAGGC"; DnaString seq1 = "ATTCAGCATACTTTCCATGAAGC"; TSeed seed(10, 7, 7); writeSeed(seed, seq0, seq1); // FRAGMENT(extension) typedef int TScore; Score<TScore, Simple> scoreMatrix(1, -1, -1); TScore scoreDropOff = 1; extendSeed(seed, scoreDropOff, scoreMatrix, seq0, seq1, 2, GappedXDrop()); std::cout << std::endl << "After extension:" << std::endl; writeSeed(seed, seq0, seq1); // FRAGMENT(banded-alignment) Align<DnaString> align; resize(rows(align), 2); assignSource(row(align, 0), seq0); assignSource(row(align, 1), seq1); std::cout << std::endl << "Banded Alignment:" << std::endl; std::cout << "Score: " << bandedAlignment(align, seed, 2, scoreMatrix) << std::endl; std::cout << align; // FRAGMENT(global-alignment) Align<DnaString> globalAlign; resize(rows(globalAlign), 2); assignSource(row(globalAlign, 0), seq0); assignSource(row(globalAlign, 1), seq1); std::cout << std::endl << "Global Alignment:" << std::endl; std::cout << "Score: " << globalAlignment(globalAlign, scoreMatrix) << std::endl; std::cout << globalAlign; return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_COLWISE_REDUCTION_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_COLWISE_REDUCTION_HPP #ifdef STAN_OPENCL #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation_cl.hpp> #include <stan/math/opencl/kernel_generator/as_operation_cl.hpp> #include <stan/math/opencl/kernel_generator/rowwise_reduction.hpp> #include <stan/math/opencl/kernel_generator/calc_if.hpp> #include <map> #include <string> #include <type_traits> #include <utility> namespace stan { namespace math { /** \addtogroup opencl_kernel_generator * @{ */ namespace internal { class colwise_reduction_base {}; /** * Determine number of work groups in rows direction that will be run fro * colwise reduction of given size. * @param n_rows number of rows of expression to resuce * @param n_cols number of columns of expression to resuce * @return number of work groups in rows direction */ int colwise_reduction_wgs_rows(int n_rows, int n_cols) { int local = opencl_context.base_opts().at("LOCAL_SIZE_"); int preferred_work_groups = opencl_context.device()[0].getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() * 16; // round up n_rows/local/n_cols return (std::min(preferred_work_groups, (n_rows + local - 1) / local) + n_cols - 1) / n_cols; } } // namespace internal /** * Represents a column wise reduction in kernel generator expressions. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam Derived derived type * @tparam T type of first argument * @tparam operation type with member function generate that accepts two * variable names and returns OpenCL source code for reduction operation_cl * @tparam PassZero whether \c operation passes trough zeros */ template <typename Derived, typename T, typename Operation> class colwise_reduction : public internal::colwise_reduction_base, public operation_cl<Derived, typename std::remove_reference_t<T>::Scalar, T> { public: using Scalar = typename std::remove_reference_t<T>::Scalar; using base = operation_cl<Derived, Scalar, T>; using base::var_name_; static const bool require_specific_local_size = true; protected: std::string init_; using base::derived; public: using base::cols; /** * Constructor * @param a the expression to reduce * @param init OpenCL source code of initialization value for reduction */ explicit colwise_reduction(T&& a, const std::string& init) : base(std::forward<T>(a)), init_(init) {} /** * Generates kernel code for assigning this expression into result expression. * @param[in,out] generated map from (pointer to) already generated local * operations to variable names * @param[in,out] generated_all map from (pointer to) already generated all * operations to variable names * @param ng name generator for this kernel * @param row_index_name row index variable name * @param col_index_name column index variable name * @param result expression into which result is to be assigned * @return part of kernel with code for this and nested expressions */ template <typename T_result> kernel_parts get_whole_kernel_parts( std::map<const void*, const char*>& generated, std::map<const void*, const char*>& generated_all, name_generator& ng, const std::string& row_index_name, const std::string& col_index_name, const T_result& result) const { kernel_parts parts = derived().get_kernel_parts( generated, generated_all, ng, row_index_name, col_index_name, false); kernel_parts out_parts = result.get_kernel_parts_lhs( generated, generated_all, ng, row_index_name, col_index_name); parts.args += out_parts.args; parts.reduction += "if (lid_i == 0) {\n" + result.var_name_ + "_global[j * n_groups_i + wg_id_i] = " + derived().var_name_ + "_local[0];\n" "}\n"; return parts; } /** * Generates kernel code for this and nested expressions. * @param row_index_name row index variable name * @param col_index_name column index variable name * @param view_handled whether whether caller already handled matrix view * @param var_name_arg name of the variable in kernel that holds argument to * this expression * @return part of kernel with code for this and nested expressions */ inline kernel_parts generate(const std::string& row_index_name, const std::string& col_index_name, const bool view_handled, const std::string& var_name_arg) const { kernel_parts res; res.declarations = "__local " + type_str<Scalar>() + " " + var_name_ + "_local[LOCAL_SIZE_];\n" + type_str<Scalar>() + " " + var_name_ + ";\n"; res.initialization = var_name_ + " = " + init_ + ";\n"; res.body = var_name_ + " = " + Operation::generate(var_name_, var_name_arg) + ";\n"; res.reduction = var_name_ + "_local[lid_i] = " + var_name_ + ";\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "for (int step = lsize_i / REDUCTION_STEP_SIZE; " "step > 0; step /= REDUCTION_STEP_SIZE) {\n" " if (lid_i < step) {\n" " for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n" " " + var_name_ + "_local[lid_i] = " + Operation::generate(var_name_ + "_local[lid_i]", var_name_ + "_local[lid_i + step * i]") + ";\n" " }\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n"; return res; } /** * Number of rows of a matrix that would be the result of evaluating this * expression. * @return number of rows */ inline int rows() const { int arg_rows = this->template get_arg<0>().rows(); int arg_cols = this->template get_arg<0>().cols(); if (arg_cols == 0) { return 1; } if (arg_cols == -1) { return -1; } return internal::colwise_reduction_wgs_rows(arg_rows, arg_cols); } /** * Number of rows threads need to be launched for. * @return number of rows */ inline int thread_rows() const { return this->template get_arg<0>().rows(); } /** * Determine indices of extreme sub- and superdiagonals written. * @return pair of indices - bottom and top diagonal */ inline std::pair<int, int> extreme_diagonals() const { return {-rows() + 1, cols() - 1}; } }; // namespace math /** * Represents column wise sum - reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class colwise_sum_ : public colwise_reduction<colwise_sum_<T>, T, sum_op> { using base = colwise_reduction<colwise_sum_<T>, T, sum_op>; using base::arguments_; public: explicit colwise_sum_(T&& a) : colwise_reduction<colwise_sum_<T>, T, sum_op>(std::forward<T>(a), "0") { } /** * Creates a deep copy of this expression. * @return copy of \c *this */ inline auto deep_copy() const { auto&& arg_copy = this->template get_arg<0>().deep_copy(); return colwise_sum_<std::remove_reference_t<decltype(arg_copy)>>( std::move(arg_copy)); } }; /** * Column wise sum - reduction of a kernel generator expression. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam T type of input expression * @param a expression to reduce * @return sum */ template <typename T, require_all_kernel_expressions_t<T>* = nullptr> inline auto colwise_sum(T&& a) { auto&& arg_copy = as_operation_cl(std::forward<T>(a)).deep_copy(); return colwise_sum_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Represents column wise max - reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class colwise_max_ : public colwise_reduction< colwise_max_<T>, T, max_op<typename std::remove_reference_t<T>::Scalar>> { using base = colwise_reduction<colwise_max_<T>, T, max_op<typename std::remove_reference_t<T>::Scalar>>; using base::arguments_; public: using op = max_op<typename std::remove_reference_t<T>::Scalar>; explicit colwise_max_(T&& a) : colwise_reduction<colwise_max_<T>, T, op>(std::forward<T>(a), op::init()) {} /** * Creates a deep copy of this expression. * @return copy of \c *this */ inline auto deep_copy() const { auto&& arg_copy = this->template get_arg<0>().deep_copy(); return colwise_max_<std::remove_reference_t<decltype(arg_copy)>>( std::move(arg_copy)); } }; /** * Column wise max - reduction of a kernel generator expression. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam T type of input expression * @param a expression to reduce * @return max */ template <typename T, require_all_kernel_expressions_t<T>* = nullptr> inline auto colwise_max(T&& a) { auto&& arg_copy = as_operation_cl(std::forward<T>(a)).deep_copy(); return colwise_max_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Represents column wise min - reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class colwise_min_ : public colwise_reduction< colwise_min_<T>, T, min_op<typename std::remove_reference_t<T>::Scalar>> { using base = colwise_reduction<colwise_min_<T>, T, min_op<typename std::remove_reference_t<T>::Scalar>>; using base::arguments_; public: using op = min_op<typename std::remove_reference_t<T>::Scalar>; explicit colwise_min_(T&& a) : colwise_reduction<colwise_min_<T>, T, op>(std::forward<T>(a), op::init()) {} /** * Creates a deep copy of this expression. * @return copy of \c *this */ inline auto deep_copy() const { auto&& arg_copy = this->template get_arg<0>().deep_copy(); return colwise_min_<std::remove_reference_t<decltype(arg_copy)>>( std::move(arg_copy)); } }; /** * Column wise min - reduction of a kernel generator expression. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam T type of input expression * @param a expression to reduce * @return min */ template <typename T, require_all_kernel_expressions_t<T>* = nullptr> inline auto colwise_min(T&& a) { return colwise_min_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } namespace internal { template <typename T> struct is_colwise_reduction_impl : public std::is_base_of<internal::colwise_reduction_base, std::decay_t<T>> {}; template <typename T> struct is_colwise_reduction_impl<calc_if_<true, T>> : public std::is_base_of<internal::colwise_reduction_base, std::decay_t<T>> {}; } // namespace internal /** * Check whether a kernel generator expression is a colwise reduction. */ template <typename T> using is_colwise_reduction = internal::is_colwise_reduction_impl<std::decay_t<T>>; /** @}*/ } // namespace math } // namespace stan #endif #endif <commit_msg>fixed multiple translation units<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_COLWISE_REDUCTION_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_COLWISE_REDUCTION_HPP #ifdef STAN_OPENCL #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation_cl.hpp> #include <stan/math/opencl/kernel_generator/as_operation_cl.hpp> #include <stan/math/opencl/kernel_generator/rowwise_reduction.hpp> #include <stan/math/opencl/kernel_generator/calc_if.hpp> #include <map> #include <string> #include <type_traits> #include <utility> namespace stan { namespace math { /** \addtogroup opencl_kernel_generator * @{ */ namespace internal { class colwise_reduction_base {}; /** * Determine number of work groups in rows direction that will be run fro * colwise reduction of given size. * @param n_rows number of rows of expression to resuce * @param n_cols number of columns of expression to resuce * @return number of work groups in rows direction */ inline int colwise_reduction_wgs_rows(int n_rows, int n_cols) { int local = opencl_context.base_opts().at("LOCAL_SIZE_"); int preferred_work_groups = opencl_context.device()[0].getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() * 16; // round up n_rows/local/n_cols return (std::min(preferred_work_groups, (n_rows + local - 1) / local) + n_cols - 1) / n_cols; } } // namespace internal /** * Represents a column wise reduction in kernel generator expressions. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam Derived derived type * @tparam T type of first argument * @tparam operation type with member function generate that accepts two * variable names and returns OpenCL source code for reduction operation_cl * @tparam PassZero whether \c operation passes trough zeros */ template <typename Derived, typename T, typename Operation> class colwise_reduction : public internal::colwise_reduction_base, public operation_cl<Derived, typename std::remove_reference_t<T>::Scalar, T> { public: using Scalar = typename std::remove_reference_t<T>::Scalar; using base = operation_cl<Derived, Scalar, T>; using base::var_name_; static const bool require_specific_local_size = true; protected: std::string init_; using base::derived; public: using base::cols; /** * Constructor * @param a the expression to reduce * @param init OpenCL source code of initialization value for reduction */ explicit colwise_reduction(T&& a, const std::string& init) : base(std::forward<T>(a)), init_(init) {} /** * Generates kernel code for assigning this expression into result expression. * @param[in,out] generated map from (pointer to) already generated local * operations to variable names * @param[in,out] generated_all map from (pointer to) already generated all * operations to variable names * @param ng name generator for this kernel * @param row_index_name row index variable name * @param col_index_name column index variable name * @param result expression into which result is to be assigned * @return part of kernel with code for this and nested expressions */ template <typename T_result> kernel_parts get_whole_kernel_parts( std::map<const void*, const char*>& generated, std::map<const void*, const char*>& generated_all, name_generator& ng, const std::string& row_index_name, const std::string& col_index_name, const T_result& result) const { kernel_parts parts = derived().get_kernel_parts( generated, generated_all, ng, row_index_name, col_index_name, false); kernel_parts out_parts = result.get_kernel_parts_lhs( generated, generated_all, ng, row_index_name, col_index_name); parts.args += out_parts.args; parts.reduction += "if (lid_i == 0) {\n" + result.var_name_ + "_global[j * n_groups_i + wg_id_i] = " + derived().var_name_ + "_local[0];\n" "}\n"; return parts; } /** * Generates kernel code for this and nested expressions. * @param row_index_name row index variable name * @param col_index_name column index variable name * @param view_handled whether whether caller already handled matrix view * @param var_name_arg name of the variable in kernel that holds argument to * this expression * @return part of kernel with code for this and nested expressions */ inline kernel_parts generate(const std::string& row_index_name, const std::string& col_index_name, const bool view_handled, const std::string& var_name_arg) const { kernel_parts res; res.declarations = "__local " + type_str<Scalar>() + " " + var_name_ + "_local[LOCAL_SIZE_];\n" + type_str<Scalar>() + " " + var_name_ + ";\n"; res.initialization = var_name_ + " = " + init_ + ";\n"; res.body = var_name_ + " = " + Operation::generate(var_name_, var_name_arg) + ";\n"; res.reduction = var_name_ + "_local[lid_i] = " + var_name_ + ";\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "for (int step = lsize_i / REDUCTION_STEP_SIZE; " "step > 0; step /= REDUCTION_STEP_SIZE) {\n" " if (lid_i < step) {\n" " for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n" " " + var_name_ + "_local[lid_i] = " + Operation::generate(var_name_ + "_local[lid_i]", var_name_ + "_local[lid_i + step * i]") + ";\n" " }\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "}\n"; return res; } /** * Number of rows of a matrix that would be the result of evaluating this * expression. * @return number of rows */ inline int rows() const { int arg_rows = this->template get_arg<0>().rows(); int arg_cols = this->template get_arg<0>().cols(); if (arg_cols == 0) { return 1; } if (arg_cols == -1) { return -1; } return internal::colwise_reduction_wgs_rows(arg_rows, arg_cols); } /** * Number of rows threads need to be launched for. * @return number of rows */ inline int thread_rows() const { return this->template get_arg<0>().rows(); } /** * Determine indices of extreme sub- and superdiagonals written. * @return pair of indices - bottom and top diagonal */ inline std::pair<int, int> extreme_diagonals() const { return {-rows() + 1, cols() - 1}; } }; // namespace math /** * Represents column wise sum - reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class colwise_sum_ : public colwise_reduction<colwise_sum_<T>, T, sum_op> { using base = colwise_reduction<colwise_sum_<T>, T, sum_op>; using base::arguments_; public: explicit colwise_sum_(T&& a) : colwise_reduction<colwise_sum_<T>, T, sum_op>(std::forward<T>(a), "0") { } /** * Creates a deep copy of this expression. * @return copy of \c *this */ inline auto deep_copy() const { auto&& arg_copy = this->template get_arg<0>().deep_copy(); return colwise_sum_<std::remove_reference_t<decltype(arg_copy)>>( std::move(arg_copy)); } }; /** * Column wise sum - reduction of a kernel generator expression. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam T type of input expression * @param a expression to reduce * @return sum */ template <typename T, require_all_kernel_expressions_t<T>* = nullptr> inline auto colwise_sum(T&& a) { auto&& arg_copy = as_operation_cl(std::forward<T>(a)).deep_copy(); return colwise_sum_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Represents column wise max - reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class colwise_max_ : public colwise_reduction< colwise_max_<T>, T, max_op<typename std::remove_reference_t<T>::Scalar>> { using base = colwise_reduction<colwise_max_<T>, T, max_op<typename std::remove_reference_t<T>::Scalar>>; using base::arguments_; public: using op = max_op<typename std::remove_reference_t<T>::Scalar>; explicit colwise_max_(T&& a) : colwise_reduction<colwise_max_<T>, T, op>(std::forward<T>(a), op::init()) {} /** * Creates a deep copy of this expression. * @return copy of \c *this */ inline auto deep_copy() const { auto&& arg_copy = this->template get_arg<0>().deep_copy(); return colwise_max_<std::remove_reference_t<decltype(arg_copy)>>( std::move(arg_copy)); } }; /** * Column wise max - reduction of a kernel generator expression. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam T type of input expression * @param a expression to reduce * @return max */ template <typename T, require_all_kernel_expressions_t<T>* = nullptr> inline auto colwise_max(T&& a) { auto&& arg_copy = as_operation_cl(std::forward<T>(a)).deep_copy(); return colwise_max_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } /** * Represents column wise min - reduction in kernel generator expressions. * @tparam T type of expression */ template <typename T> class colwise_min_ : public colwise_reduction< colwise_min_<T>, T, min_op<typename std::remove_reference_t<T>::Scalar>> { using base = colwise_reduction<colwise_min_<T>, T, min_op<typename std::remove_reference_t<T>::Scalar>>; using base::arguments_; public: using op = min_op<typename std::remove_reference_t<T>::Scalar>; explicit colwise_min_(T&& a) : colwise_reduction<colwise_min_<T>, T, op>(std::forward<T>(a), op::init()) {} /** * Creates a deep copy of this expression. * @return copy of \c *this */ inline auto deep_copy() const { auto&& arg_copy = this->template get_arg<0>().deep_copy(); return colwise_min_<std::remove_reference_t<decltype(arg_copy)>>( std::move(arg_copy)); } }; /** * Column wise min - reduction of a kernel generator expression. So as to * be efficient column wise reductions are only done partially. That means * instead of 1 row kernel output will have a few rows that need to be reduced * to obtain final result. This can be done in a separate kernel or after * copying to CPU. Also column wise reductions can not be used as arguments to * other operations - they can only be evaluated. * @tparam T type of input expression * @param a expression to reduce * @return min */ template <typename T, require_all_kernel_expressions_t<T>* = nullptr> inline auto colwise_min(T&& a) { return colwise_min_<as_operation_cl_t<T>>( as_operation_cl(std::forward<T>(a))); } namespace internal { template <typename T> struct is_colwise_reduction_impl : public std::is_base_of<internal::colwise_reduction_base, std::decay_t<T>> {}; template <typename T> struct is_colwise_reduction_impl<calc_if_<true, T>> : public std::is_base_of<internal::colwise_reduction_base, std::decay_t<T>> {}; } // namespace internal /** * Check whether a kernel generator expression is a colwise reduction. */ template <typename T> using is_colwise_reduction = internal::is_colwise_reduction_impl<std::decay_t<T>>; /** @}*/ } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#include "system/payload_system.hpp" #include "util/time.hpp" #include "ch.hpp" #include "chprintf.h" PayloadSystem::PayloadSystem( Accelerometer& accel, optional<Accelerometer *> accelH, optional<Barometer *> bar, optional<GPS *> gps, Gyroscope& gyr, optional<Magnetometer *> mag, WorldEstimator& estimator, InputSource& inputSource, MotorMapper& motorMapper, Communicator& communicator, Platform& platform) : VehicleSystem(communicator), MessageListener(communicator), accel(accel), accelH(accelH), bar(bar), gps(gps), gyr(gyr), mag(mag), estimator(estimator), inputSource(inputSource), motorMapper(motorMapper), platform(platform), imuStream(communicator, 100), systemStream(communicator, 5), state(PayloadState::DISARMED), motorDC(0.0) { // Disarm by default. A set_arm_state_message_t message is required to enable // the control pipeline. setArmed(false); } void PayloadSystem::update() { //static int time = 0; //if (time % 1000 == 0) { // chprintf((BaseSequentialStream*)&SD4, "%d\r\n", RTT2MS(chibios_rt::System::getTime())); //} //time = (time+1) % 1000; // Poll the gyroscope and accelerometer AccelerometerReading accelReading = accel.readAccel(); GyroscopeReading gyrReading = gyr.readGyro(); optional<AccelerometerReading> accelHReading; optional<BarometerReading> barReading; optional<GPSReading> gpsReading; optional<MagnetometerReading> magReading; if (accelH) accelHReading = (*accelH)->readAccel(); if (bar) barReading = (*bar)->readBar(); if (gps) gpsReading = (*gps)->readGPS(); //if (mag) magReading = (*mag)->readMag(); SensorMeasurements meas { .accel = std::experimental::make_optional(accelReading), .accelH = accelHReading, .bar = barReading, .gps = gpsReading, .gyro = std::experimental::make_optional(gyrReading), .mag = magReading }; // Update the world estimate WorldEstimate estimate = estimator.update(meas); // Poll for controller input ControllerInput input = inputSource.read(); // Keep moving average of acceleration static float accel = -1.0f; accel = 0.5*accel + 0.5*accelReading.axes[0]; // Run the controllers //ActuatorSetpoint actuatorSp; // Run state machine switch (state) { case PayloadState::DISARMED: state = DisarmedState(meas, estimate); break; case PayloadState::PRE_ARM: state = PreArmState(meas, estimate); break; case PayloadState::ARMED: state = ArmedState(meas, estimate); break; case PayloadState::FLIGHT: state = FlightState(meas, estimate); break; case PayloadState::APOGEE: state = ApogeeState(meas, estimate); break; case PayloadState::ZERO_G: state = ZeroGState(meas, estimate); break; case PayloadState::DESCENT: state = DescentState(meas, estimate); break; case PayloadState::RECOVERY: state = RecoveryState(meas, estimate); break; default: break; } // Update streams updateStreams(meas, estimate); // Update motor outputs //motorMapper.run(isArmed(), actuatorSp); } bool PayloadSystem::healthy() { bool healthy = accel.healthy() && gyr.healthy(); if(accelH) { healthy &= (*accelH)->healthy(); } if(bar) { healthy &= (*bar)->healthy(); } if(gps) { healthy &= (*gps)->healthy(); } if(mag) { healthy &= (*mag)->healthy(); } return healthy; } void PayloadSystem::on(const protocol::message::set_arm_state_message_t& m) { setArmed(m.armed); } void PayloadSystem::updateStreams(SensorMeasurements meas, WorldEstimate est) { if (imuStream.ready()) { protocol::message::imu_message_t m { .time = ST2MS(chibios_rt::System::getTime()), .gyro = { (*meas.gyro).axes[0], (*meas.gyro).axes[1], (*meas.gyro).axes[2] }, .accel = { (*meas.accel).axes[0], (*meas.accel).axes[1], (*meas.accel).axes[2] } }; imuStream.publish(m); } if (systemStream.ready()) { uint8_t stateNum = 0; switch (state) { case PayloadState::DISARMED: stateNum = 0; break; case PayloadState::PRE_ARM: stateNum = 1; break; case PayloadState::ARMED: stateNum = 2; break; case PayloadState::FLIGHT: stateNum = 3; break; case PayloadState::APOGEE: stateNum = 4; break; case PayloadState::ZERO_G: stateNum = 5; break; case PayloadState::DESCENT: stateNum = 6; break; case PayloadState::RECOVERY: stateNum = 7; break; default: break; } protocol::message::system_message_t m { .time = ST2MS(chibios_rt::System::getTime()), .state = stateNum, .motorDC = motorDC }; systemStream.publish(m); } } PayloadState PayloadSystem::DisarmedState(SensorMeasurements meas, WorldEstimate est) { PulseLED(1,0,0,1); // Red 1 Hz // Proceed directly to PRE_ARM for now. return PayloadState::PRE_ARM; } PayloadState PayloadSystem::PreArmState(SensorMeasurements meas, WorldEstimate est) { PulseLED(1,0,0,4); // Red 4 Hz // Calibrate groundAltitude = est.loc.alt; // TODO(yoos): run sensor calibration here // Proceed to ARMED if all sensors are healthy and GS arm signal received. if (healthy() && isArmed()) { return PayloadState::ARMED; } return PayloadState::PRE_ARM; } PayloadState PayloadSystem::ArmedState(SensorMeasurements meas, WorldEstimate est) { SetLED(1,0,0); // Red static int count = 10; count = ((*meas.accel).axes[0] > 1.1) ? (count-1) : 10; // Revert to PRE_ARM if any sensors are unhealthy or disarm signal received if (!(healthy() && isArmed())) { return PayloadState::PRE_ARM; } // Proceed to FLIGHT on 1.1g sense on X axis. if (count == 0) { return PayloadState::FLIGHT; } return PayloadState::ARMED; } PayloadState PayloadSystem::FlightState(SensorMeasurements meas, WorldEstimate est) { SetLED(0,0,1); // Blue static bool powered = true; // First time we enter, we are in powered flight. // Check for motor cutoff. We should see negative acceleration due to drag. static int count = 100; if (powered) { count = ((*meas.accel).axes[0] < 0.0) ? (count-1) : 100; powered = (count == 0) ? false : true; } // Apogee occurs after motor cutoff if (!powered) { // If falling faster than -40m/s, definitely deploy. if (est.loc.dAlt < -40.0) { return PayloadState::APOGEE; } // Check for near-zero altitude change towards end of ascent (ideal case) // and that we are not just undergoing a subsonic transition. else if ((*meas.accel).axes[0] > -1.0) { return PayloadState::APOGEE; } } return PayloadState::FLIGHT; } PayloadState PayloadSystem::ApogeeState(SensorMeasurements meas, WorldEstimate est) { PulseLED(0,0,1,2); // Blue 2 Hz static float sTime = 0.0; // State time // Count continuous time under drogue // TODO(yoos): We might still see this if partially deployed and spinning // around.. static float drogueTime = 0.0; if ((*meas.accel).axes[0] < -0.3) { drogueTime += unit_config::DT; } else { drogueTime = 0.0; } // Wait until successful drogue deployment or 5 seconds max. if (sTime < 5.0) { if (drogueTime > 1.0) { // TODO(yoos): Do we want to wait longer for ensure drogue? return PayloadState::ZERO_G; } // TODO: What if payload doesn't separate? } else { return PayloadState::ZERO_G; } sTime += unit_config::DT; return PayloadState::APOGEE; } PayloadState PayloadSystem::ZeroGState(SensorMeasurements meas, WorldEstimate est) { RGBLED(2); // Rainbows! static float sTime = 0.0; // State time // Release shuttle platform.get<DigitalPlatform>().set(unit_config::PIN_SHUTTLE1_CH, true); platform.get<DigitalPlatform>().set(unit_config::PIN_SHUTTLE2_CH, true); // Run zero-g maneuver for 6 s. if (sTime < 6.0) { if ((*meas.accel).axes[0] < 0.0 && motorDC < 1.0) { motorDC += 0.01; } ActuatorSetpoint actuatorSp {0,0,0,motorDC}; motorMapper.run(true, actuatorSp); // Assumed armed } else if (sTime < 7.0) { motorDC = 0.0; ActuatorSetpoint actuatorSp {0,0,0,motorDC}; motorMapper.run(true, actuatorSp); // Assumed armed } else if (sTime < 10.0) { // Fire drogue pyro platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, true); if ((*meas.accel).axes[0] < -10.0) { // Large negative acceleration due to proper drogue deployment return PayloadState::DESCENT; } } else { // We would deploy main here, but payload avionics doesn't have room. return PayloadState::DESCENT; } sTime += unit_config::DT; return PayloadState::ZERO_G; } PayloadState PayloadSystem::DescentState(SensorMeasurements meas, WorldEstimate est) { SetLED(1,0,1); // Violet static float sTime = 0.0; // State time // Payload does not control its own main. // Stay for at least 1 s static int count = 1000; if (sTime < 1.0) {} // Enter recovery if altitude is unchanging and rotation rate is zero else if (est.loc.dAlt > -2.0 && fabs((*meas.gyro).axes[0] < 0.05) && fabs((*meas.gyro).axes[1] < 0.05) && fabs((*meas.gyro).axes[2] < 0.05)) { count -= 1; } else { count = 1000; } if (count == 0) { return PayloadState::RECOVERY; } sTime += unit_config::DT; return PayloadState::DESCENT; } PayloadState PayloadSystem::RecoveryState(SensorMeasurements meas, WorldEstimate est) { PulseLED(1,0,1,2); // Violet 2 Hz // Turn things off platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, false); return PayloadState::RECOVERY; } void PayloadSystem::SetLED(float r, float g, float b) { platform.get<PWMPlatform>().set(9, 0.1*r); platform.get<PWMPlatform>().set(10, 0.1*g); platform.get<PWMPlatform>().set(11, 0.1*b); } void PayloadSystem::BlinkLED(float r, float g, float b, float freq) { static int count = 0; int period = 1000 / freq; if (count % period < period/2) { SetLED(r,g,b); } else { SetLED(0,0,0); } count = (count+1) % period; } void PayloadSystem::PulseLED(float r, float g, float b, float freq) { int period = 1000 / freq; static int count = 0; float dc = ((float) abs(period/2 - count)) / (period/2); SetLED(dc*r, dc*g, dc*b); count = (count+1) % period; } void PayloadSystem::RGBLED(float freq) { static float dc = 0.0; static int dir = 1; if (dc >= 1.0) { dir = -1; } else if (dc <= 0.0) { dir = 1; } dc += dir * (2*freq * unit_config::DT); float dc_ = dc; float dir_ = dir; for (int i=0; i<3; i++) { dc_ += dir_ * 0.666; if (dc_ > 1.0) { dc_ = 2.0 - dc_; dir_ = -1; } else if (dc_ < 0.0) { dc_ = 0.0 - dc_; dir_ = 1; } platform.get<PWMPlatform>().set(9+i, dc_); } } <commit_msg>Decrease payload IMU stream frequency.<commit_after>#include "system/payload_system.hpp" #include "util/time.hpp" #include "ch.hpp" #include "chprintf.h" PayloadSystem::PayloadSystem( Accelerometer& accel, optional<Accelerometer *> accelH, optional<Barometer *> bar, optional<GPS *> gps, Gyroscope& gyr, optional<Magnetometer *> mag, WorldEstimator& estimator, InputSource& inputSource, MotorMapper& motorMapper, Communicator& communicator, Platform& platform) : VehicleSystem(communicator), MessageListener(communicator), accel(accel), accelH(accelH), bar(bar), gps(gps), gyr(gyr), mag(mag), estimator(estimator), inputSource(inputSource), motorMapper(motorMapper), platform(platform), imuStream(communicator, 10), // TODO(yoos): calculate data link budget and increase if possible systemStream(communicator, 5), state(PayloadState::DISARMED), motorDC(0.0) { // Disarm by default. A set_arm_state_message_t message is required to enable // the control pipeline. setArmed(false); } void PayloadSystem::update() { //static int time = 0; //if (time % 1000 == 0) { // chprintf((BaseSequentialStream*)&SD4, "%d\r\n", RTT2MS(chibios_rt::System::getTime())); //} //time = (time+1) % 1000; // Poll the gyroscope and accelerometer AccelerometerReading accelReading = accel.readAccel(); GyroscopeReading gyrReading = gyr.readGyro(); optional<AccelerometerReading> accelHReading; optional<BarometerReading> barReading; optional<GPSReading> gpsReading; optional<MagnetometerReading> magReading; if (accelH) accelHReading = (*accelH)->readAccel(); if (bar) barReading = (*bar)->readBar(); if (gps) gpsReading = (*gps)->readGPS(); //if (mag) magReading = (*mag)->readMag(); SensorMeasurements meas { .accel = std::experimental::make_optional(accelReading), .accelH = accelHReading, .bar = barReading, .gps = gpsReading, .gyro = std::experimental::make_optional(gyrReading), .mag = magReading }; // Update the world estimate WorldEstimate estimate = estimator.update(meas); // Poll for controller input ControllerInput input = inputSource.read(); // Keep moving average of acceleration static float accel = -1.0f; accel = 0.5*accel + 0.5*accelReading.axes[0]; // Run the controllers //ActuatorSetpoint actuatorSp; // Run state machine switch (state) { case PayloadState::DISARMED: state = DisarmedState(meas, estimate); break; case PayloadState::PRE_ARM: state = PreArmState(meas, estimate); break; case PayloadState::ARMED: state = ArmedState(meas, estimate); break; case PayloadState::FLIGHT: state = FlightState(meas, estimate); break; case PayloadState::APOGEE: state = ApogeeState(meas, estimate); break; case PayloadState::ZERO_G: state = ZeroGState(meas, estimate); break; case PayloadState::DESCENT: state = DescentState(meas, estimate); break; case PayloadState::RECOVERY: state = RecoveryState(meas, estimate); break; default: break; } // Update streams updateStreams(meas, estimate); // Update motor outputs //motorMapper.run(isArmed(), actuatorSp); } bool PayloadSystem::healthy() { bool healthy = accel.healthy() && gyr.healthy(); if(accelH) { healthy &= (*accelH)->healthy(); } if(bar) { healthy &= (*bar)->healthy(); } if(gps) { healthy &= (*gps)->healthy(); } if(mag) { healthy &= (*mag)->healthy(); } return healthy; } void PayloadSystem::on(const protocol::message::set_arm_state_message_t& m) { setArmed(m.armed); } void PayloadSystem::updateStreams(SensorMeasurements meas, WorldEstimate est) { if (imuStream.ready()) { protocol::message::imu_message_t m { .time = ST2MS(chibios_rt::System::getTime()), .gyro = { (*meas.gyro).axes[0], (*meas.gyro).axes[1], (*meas.gyro).axes[2] }, .accel = { (*meas.accel).axes[0], (*meas.accel).axes[1], (*meas.accel).axes[2] } }; imuStream.publish(m); } if (systemStream.ready()) { uint8_t stateNum = 0; switch (state) { case PayloadState::DISARMED: stateNum = 0; break; case PayloadState::PRE_ARM: stateNum = 1; break; case PayloadState::ARMED: stateNum = 2; break; case PayloadState::FLIGHT: stateNum = 3; break; case PayloadState::APOGEE: stateNum = 4; break; case PayloadState::ZERO_G: stateNum = 5; break; case PayloadState::DESCENT: stateNum = 6; break; case PayloadState::RECOVERY: stateNum = 7; break; default: break; } protocol::message::system_message_t m { .time = ST2MS(chibios_rt::System::getTime()), .state = stateNum, .motorDC = motorDC }; systemStream.publish(m); } } PayloadState PayloadSystem::DisarmedState(SensorMeasurements meas, WorldEstimate est) { PulseLED(1,0,0,1); // Red 1 Hz // Proceed directly to PRE_ARM for now. return PayloadState::PRE_ARM; } PayloadState PayloadSystem::PreArmState(SensorMeasurements meas, WorldEstimate est) { PulseLED(1,0,0,4); // Red 4 Hz // Calibrate groundAltitude = est.loc.alt; // TODO(yoos): run sensor calibration here // Proceed to ARMED if all sensors are healthy and GS arm signal received. if (healthy() && isArmed()) { return PayloadState::ARMED; } return PayloadState::PRE_ARM; } PayloadState PayloadSystem::ArmedState(SensorMeasurements meas, WorldEstimate est) { SetLED(1,0,0); // Red static int count = 10; count = ((*meas.accel).axes[0] > 1.1) ? (count-1) : 10; // Revert to PRE_ARM if any sensors are unhealthy or disarm signal received if (!(healthy() && isArmed())) { return PayloadState::PRE_ARM; } // Proceed to FLIGHT on 1.1g sense on X axis. if (count == 0) { return PayloadState::FLIGHT; } return PayloadState::ARMED; } PayloadState PayloadSystem::FlightState(SensorMeasurements meas, WorldEstimate est) { SetLED(0,0,1); // Blue static bool powered = true; // First time we enter, we are in powered flight. // Check for motor cutoff. We should see negative acceleration due to drag. static int count = 100; if (powered) { count = ((*meas.accel).axes[0] < 0.0) ? (count-1) : 100; powered = (count == 0) ? false : true; } // Apogee occurs after motor cutoff if (!powered) { // If falling faster than -40m/s, definitely deploy. if (est.loc.dAlt < -40.0) { return PayloadState::APOGEE; } // Check for near-zero altitude change towards end of ascent (ideal case) // and that we are not just undergoing a subsonic transition. else if ((*meas.accel).axes[0] > -1.0) { return PayloadState::APOGEE; } } return PayloadState::FLIGHT; } PayloadState PayloadSystem::ApogeeState(SensorMeasurements meas, WorldEstimate est) { PulseLED(0,0,1,2); // Blue 2 Hz static float sTime = 0.0; // State time // Count continuous time under drogue // TODO(yoos): We might still see this if partially deployed and spinning // around.. static float drogueTime = 0.0; if ((*meas.accel).axes[0] < -0.3) { drogueTime += unit_config::DT; } else { drogueTime = 0.0; } // Wait until successful drogue deployment or 5 seconds max. if (sTime < 5.0) { if (drogueTime > 1.0) { // TODO(yoos): Do we want to wait longer for ensure drogue? return PayloadState::ZERO_G; } // TODO: What if payload doesn't separate? } else { return PayloadState::ZERO_G; } sTime += unit_config::DT; return PayloadState::APOGEE; } PayloadState PayloadSystem::ZeroGState(SensorMeasurements meas, WorldEstimate est) { RGBLED(2); // Rainbows! static float sTime = 0.0; // State time // Release shuttle platform.get<DigitalPlatform>().set(unit_config::PIN_SHUTTLE1_CH, true); platform.get<DigitalPlatform>().set(unit_config::PIN_SHUTTLE2_CH, true); // Run zero-g maneuver for 6 s. if (sTime < 6.0) { if ((*meas.accel).axes[0] < 0.0 && motorDC < 1.0) { motorDC += 0.01; } ActuatorSetpoint actuatorSp {0,0,0,motorDC}; motorMapper.run(true, actuatorSp); // Assumed armed } else if (sTime < 7.0) { motorDC = 0.0; ActuatorSetpoint actuatorSp {0,0,0,motorDC}; motorMapper.run(true, actuatorSp); // Assumed armed } else if (sTime < 10.0) { // Fire drogue pyro platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, true); if ((*meas.accel).axes[0] < -10.0) { // Large negative acceleration due to proper drogue deployment return PayloadState::DESCENT; } } else { // We would deploy main here, but payload avionics doesn't have room. return PayloadState::DESCENT; } sTime += unit_config::DT; return PayloadState::ZERO_G; } PayloadState PayloadSystem::DescentState(SensorMeasurements meas, WorldEstimate est) { SetLED(1,0,1); // Violet static float sTime = 0.0; // State time // Payload does not control its own main. // Stay for at least 1 s static int count = 1000; if (sTime < 1.0) {} // Enter recovery if altitude is unchanging and rotation rate is zero else if (est.loc.dAlt > -2.0 && fabs((*meas.gyro).axes[0] < 0.05) && fabs((*meas.gyro).axes[1] < 0.05) && fabs((*meas.gyro).axes[2] < 0.05)) { count -= 1; } else { count = 1000; } if (count == 0) { return PayloadState::RECOVERY; } sTime += unit_config::DT; return PayloadState::DESCENT; } PayloadState PayloadSystem::RecoveryState(SensorMeasurements meas, WorldEstimate est) { PulseLED(1,0,1,2); // Violet 2 Hz // Turn things off platform.get<DigitalPlatform>().set(unit_config::PIN_DROGUE_CH, false); return PayloadState::RECOVERY; } void PayloadSystem::SetLED(float r, float g, float b) { platform.get<PWMPlatform>().set(9, 0.1*r); platform.get<PWMPlatform>().set(10, 0.1*g); platform.get<PWMPlatform>().set(11, 0.1*b); } void PayloadSystem::BlinkLED(float r, float g, float b, float freq) { static int count = 0; int period = 1000 / freq; if (count % period < period/2) { SetLED(r,g,b); } else { SetLED(0,0,0); } count = (count+1) % period; } void PayloadSystem::PulseLED(float r, float g, float b, float freq) { int period = 1000 / freq; static int count = 0; float dc = ((float) abs(period/2 - count)) / (period/2); SetLED(dc*r, dc*g, dc*b); count = (count+1) % period; } void PayloadSystem::RGBLED(float freq) { static float dc = 0.0; static int dir = 1; if (dc >= 1.0) { dir = -1; } else if (dc <= 0.0) { dir = 1; } dc += dir * (2*freq * unit_config::DT); float dc_ = dc; float dir_ = dir; for (int i=0; i<3; i++) { dc_ += dir_ * 0.666; if (dc_ > 1.0) { dc_ = 2.0 - dc_; dir_ = -1; } else if (dc_ < 0.0) { dc_ = 0.0 - dc_; dir_ = 1; } platform.get<PWMPlatform>().set(9+i, dc_); } } <|endoftext|>
<commit_before>#include "TerrainMap.hpp" #include <limits> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/bot_core/pose_t.hpp> #include <drc_utils/BotWrapper.hpp> #include <maps/BotWrapper.hpp> #include <maps/ViewClient.hpp> #include <maps/DepthImage.hpp> #include <maps/DepthImageView.hpp> #include "FillMethods.hpp" using namespace terrainmap; struct TerrainMap::Helper { struct Listener : public maps::ViewClient::Listener { Helper* mHelper; Listener(Helper* iHelper) : mHelper(iHelper) {} void notifyCatalog(const bool iChanged) {} void notifyData(const int64_t iViewId) { if (!mHelper->mListening) return; if (iViewId != mHelper->mViewId) return; auto view = std::dynamic_pointer_cast<maps::DepthImageView> (mHelper->mViewClient->getView(mHelper->mViewId)); if (view != NULL) { auto type = maps::DepthImage::TypeDisparity; mHelper->mPreviousDepths = view->getDepthImage()->getData(type); } mHelper->mLatestView = view; mHelper->computeNewDepths(); } }; int64_t mViewId; std::string mMapChannel; Eigen::Vector4d mFillPlane; bool mUseFootPose; bool mOverrideHeights; bool mShouldFillMissing; NormalMethod mNormalMethod; double mNormalRadius; std::shared_ptr<drc::BotWrapper> mBotWrapper; std::shared_ptr<maps::ViewClient> mViewClient; std::shared_ptr<Listener> mListener; std::shared_ptr<maps::DepthImageView> mLatestView; Eigen::Vector4d mLatestFootPlane; std::vector<float> mPreviousDepths; bool mListening; Helper(const std::shared_ptr<drc::BotWrapper>& iBotWrapper) { mBotWrapper = iBotWrapper; mUseFootPose = false; mOverrideHeights = false; mNormalMethod = NormalMethodTriangle; mShouldFillMissing = true; mNormalRadius = 0; mListening = false; mFillPlane << 0,0,1,0; mLatestFootPlane << 0,0,1,0; mViewClient.reset(new maps::ViewClient()); std::shared_ptr<maps::BotWrapper> wrapper (new maps::BotWrapper(mBotWrapper->getLcm(), mBotWrapper->getBotParam(), mBotWrapper->getBotFrames())); mViewClient->setBotWrapper(wrapper); mBotWrapper->getLcm()->subscribe("POSE_GROUND", &Helper::onGround, this); mListener.reset(new Listener(this)); mViewClient->addListener(mListener.get()); } // TODO: need this? could also use bot-frames from ground to local // need to make sure that info is synchronized even when listening paused void onGround(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const bot_core::pose_t* iMessage) { if (!mListening) return; Eigen::Quaterniond q(iMessage->orientation[0], iMessage->orientation[1], iMessage->orientation[2], iMessage->orientation[3]); Eigen::Vector3d pos(iMessage->pos[0], iMessage->pos[1], iMessage->pos[2]); mLatestFootPlane.head<3>() = q.matrix().col(2); mLatestFootPlane[3] = -mLatestFootPlane.head<3>().dot(pos); } Eigen::Vector4d getLatestFootPlane() const { // TODO: below might be slow if called too frequently if (false) { Eigen::Isometry3d groundPose; mBotWrapper->getTransform("ground","local",groundPose); Eigen::Vector4d plane; plane.head<3>() = groundPose.rotation().col(2); plane[3] = -plane.head<3>().dot(groundPose.translation()); return plane; } return mLatestFootPlane; } void computeNewDepths() { auto view = mLatestView; auto plane = mUseFootPose ? getLatestFootPlane() : mFillPlane; if (mOverrideHeights) { FillMethods::fillEntireView(view, plane); } else { if (mShouldFillMissing) { // fill 0.5m square area underneath robot // TODO: could use timestamp of latest view Eigen::Isometry3d groundToLocal; mBotWrapper->getTransform("ground","local",groundToLocal); Eigen::Vector3d pos = groundToLocal.translation(); FillMethods::fillBox(view, pos, 0.5, plane); // fill holes in environment using neighbor values FillMethods::fillHolesIterative(view); // fill remaining areas with selected plane FillMethods::fillMissing(view, plane); } } } }; TerrainMap:: TerrainMap(const std::shared_ptr<drc::BotWrapper>& iBotWrapper) { mHelper.reset(new Helper(iBotWrapper)); } TerrainMap:: ~TerrainMap() { } void TerrainMap:: setInfo(const int64_t iViewId, const std::string& iMapChannel) { mHelper->mViewId = iViewId; mHelper->mMapChannel = iMapChannel; mHelper->mViewClient->removeAllViewChannels(); mHelper->mViewClient->addViewChannel(iMapChannel); } int64_t TerrainMap:: getViewId() const { return mHelper->mViewId; } std::string TerrainMap:: getMapChannel() const { return mHelper->mMapChannel; } void TerrainMap:: setFillPlane(const Eigen::Vector4d& iPlane) { mHelper->mFillPlane = iPlane; mHelper->mFillPlane /= iPlane.head<3>().norm(); } void TerrainMap:: useFootPose(const bool iVal) { mHelper->mUseFootPose = iVal; } void TerrainMap:: overrideHeights(const bool iVal) { mHelper->mOverrideHeights = iVal; } void TerrainMap:: setNormalMethod(const NormalMethod iMethod) { mHelper->mNormalMethod = iMethod; } void TerrainMap:: setNormalRadius(const double iRadius) { mHelper->mNormalRadius = iRadius; } void TerrainMap:: shouldFillMissing(const bool iVal) { mHelper->mShouldFillMissing = iVal; } double TerrainMap:: getNormalRadius() const { return mHelper->mNormalRadius; } bool TerrainMap:: startListening() { if (mHelper->mListening) return false; mHelper->mViewClient->start(); mHelper->mListening = true; return true; } bool TerrainMap:: stopListening() { if (!mHelper->mListening) return false; mHelper->mListening = false; mHelper->mViewClient->stop(); return true; } bool TerrainMap:: sendRequest(const Eigen::Vector3d& iBoxMin, const Eigen::Vector3d& iBoxMax, const double iResolutionMeters, const double iTimeWindowSeconds, const double iFrequencyHz) { maps::ViewBase::Spec spec; spec.mResolution = (float)iResolutionMeters; spec.mWidth = int((iBoxMax[0] - iBoxMin[0]) / spec.mResolution); spec.mHeight = int((iBoxMax[1] - iBoxMin[1]) / spec.mResolution); spec.mTimeMin = -iTimeWindowSeconds*1e6; spec.mClipPlanes.push_back(Eigen::Vector4f( 1, 0, 0, -iBoxMin[0])); spec.mClipPlanes.push_back(Eigen::Vector4f(-1, 0, 0, iBoxMax[0])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0, 1, 0, -iBoxMin[1])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0,-1, 0, iBoxMax[1])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0, 0, 1, -iBoxMin[2])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0, 0,-1, iBoxMax[2])); spec.mMapId = 1; spec.mViewId = getViewId(); spec.mType = maps::ViewBase::TypeDepthImage; spec.mChannel = getMapChannel(); spec.mFrequency = iFrequencyHz; spec.mQuantizationMax = 0; spec.mTimeMax = 0; spec.mTimeMode = maps::ViewBase::TimeModeRelative; spec.mRelativeLocation = true; spec.mActive = true; Eigen::Isometry3f pose = Eigen::Isometry3f::Identity(); pose.translation() = Eigen::Vector3f(0,0,10); pose.linear() << 1,0,0, 0,-1,0, 0,0,-1; Eigen::Affine3f calib = Eigen::Affine3f::Identity(); calib(0,0) = 1/spec.mResolution; calib(1,1) = 1/spec.mResolution; calib(0,3) = -iBoxMin[0]*calib(0,0); calib(1,3) = -iBoxMin[1]*calib(1,1); Eigen::Projective3f projector = calib*pose.inverse(); spec.mTransform = projector; // send request mHelper->mViewClient->request(spec); return true; } std::shared_ptr<TerrainMap::TerrainData> TerrainMap:: getData() const { auto view = mHelper->mLatestView; if (view == NULL) return NULL; std::shared_ptr<TerrainData> data(new TerrainData()); auto type = maps::DepthImage::TypeDepth; auto image = view->getDepthImage(); data->mHeights = image->getData(type); data->mWidth = image->getWidth(); data->mHeight = image->getHeight(); data->mTransform = view->getTransform().cast<double>(); return data; } template <typename T> bool TerrainMap:: getHeightAndNormal(const T iX, const T iY, T& oHeight, Eigen::Matrix<T,3,1>& oNormal) const { bool usePlaneForHeight = mHelper->mOverrideHeights; bool usePlaneForNormal = (mHelper->mNormalMethod == NormalMethodOverride); if (!(usePlaneForHeight && usePlaneForNormal)) { Eigen::Vector3f pt, normal; const auto& view = mHelper->mLatestView; auto normalMethod = maps::DepthImageView::NormalMethodTriangle; switch (mHelper->mNormalMethod) { case NormalMethodOverride: normalMethod = maps::DepthImageView::NormalMethodZ; break; case NormalMethodTriangle: normalMethod = maps::DepthImageView::NormalMethodTriangle; break; case NormalMethodLeastSquares: normalMethod = maps::DepthImageView::NormalMethodLeastSquares; break; case NormalMethodRobustKernel: normalMethod = maps::DepthImageView::NormalMethodRobustKernel; break; case NormalMethodSampleConsensus: normalMethod = maps::DepthImageView::NormalMethodSampleConsensus; break; default: break; } if (view == NULL) usePlaneForHeight = usePlaneForNormal = true; else { view->setNormalMethod(normalMethod); if (!view->getClosest(Eigen::Vector3f(iX, iY, 0), pt, normal)) { usePlaneForHeight = usePlaneForNormal = true; } } oHeight = pt[2]; oNormal = normal.cast<T>(); } const auto& plane = (mHelper->mUseFootPose ? mHelper->getLatestFootPlane() : mHelper->mFillPlane).cast<T>(); if (usePlaneForHeight) { oHeight = -(plane[0]*iX + plane[1]*iY + plane[3])/plane[2]; } if (usePlaneForNormal) { oNormal << plane[0],plane[1],plane[2]; } return true; } // explicit instantiations template bool TerrainMap:: getHeightAndNormal(const float iX, const float iY, float& oHeight, Eigen::Vector3f& oNormal) const; template bool TerrainMap:: getHeightAndNormal(const double iX, const double iY, double& oHeight, Eigen::Vector3d& oNormal) const; <commit_msg>fixed bug in terrainmap; reference was being assigned to temporary<commit_after>#include "TerrainMap.hpp" #include <limits> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/bot_core/pose_t.hpp> #include <drc_utils/BotWrapper.hpp> #include <maps/BotWrapper.hpp> #include <maps/ViewClient.hpp> #include <maps/DepthImage.hpp> #include <maps/DepthImageView.hpp> #include "FillMethods.hpp" using namespace terrainmap; struct TerrainMap::Helper { struct Listener : public maps::ViewClient::Listener { Helper* mHelper; Listener(Helper* iHelper) : mHelper(iHelper) {} void notifyCatalog(const bool iChanged) {} void notifyData(const int64_t iViewId) { if (!mHelper->mListening) return; if (iViewId != mHelper->mViewId) return; auto view = std::dynamic_pointer_cast<maps::DepthImageView> (mHelper->mViewClient->getView(mHelper->mViewId)); if (view != NULL) { auto type = maps::DepthImage::TypeDisparity; mHelper->mPreviousDepths = view->getDepthImage()->getData(type); } mHelper->mLatestView = view; mHelper->computeNewDepths(); } }; int64_t mViewId; std::string mMapChannel; Eigen::Vector4d mFillPlane; bool mUseFootPose; bool mOverrideHeights; bool mShouldFillMissing; NormalMethod mNormalMethod; double mNormalRadius; std::shared_ptr<drc::BotWrapper> mBotWrapper; std::shared_ptr<maps::ViewClient> mViewClient; std::shared_ptr<Listener> mListener; std::shared_ptr<maps::DepthImageView> mLatestView; Eigen::Vector4d mLatestFootPlane; std::vector<float> mPreviousDepths; bool mListening; Helper(const std::shared_ptr<drc::BotWrapper>& iBotWrapper) { mBotWrapper = iBotWrapper; mUseFootPose = false; mOverrideHeights = false; mNormalMethod = NormalMethodTriangle; mShouldFillMissing = true; mNormalRadius = 0; mListening = false; mFillPlane << 0,0,1,0; mLatestFootPlane << 0,0,1,0; mViewClient.reset(new maps::ViewClient()); std::shared_ptr<maps::BotWrapper> wrapper (new maps::BotWrapper(mBotWrapper->getLcm(), mBotWrapper->getBotParam(), mBotWrapper->getBotFrames())); mViewClient->setBotWrapper(wrapper); mBotWrapper->getLcm()->subscribe("POSE_GROUND", &Helper::onGround, this); mListener.reset(new Listener(this)); mViewClient->addListener(mListener.get()); } // TODO: need this? could also use bot-frames from ground to local // need to make sure that info is synchronized even when listening paused void onGround(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const bot_core::pose_t* iMessage) { if (!mListening) return; Eigen::Quaterniond q(iMessage->orientation[0], iMessage->orientation[1], iMessage->orientation[2], iMessage->orientation[3]); Eigen::Vector3d pos(iMessage->pos[0], iMessage->pos[1], iMessage->pos[2]); mLatestFootPlane.head<3>() = q.matrix().col(2); mLatestFootPlane[3] = -mLatestFootPlane.head<3>().dot(pos); } Eigen::Vector4d getLatestFootPlane() const { // TODO: below might be slow if called too frequently if (false) { Eigen::Isometry3d groundPose; mBotWrapper->getTransform("ground","local",groundPose); Eigen::Vector4d plane; plane.head<3>() = groundPose.rotation().col(2); plane[3] = -plane.head<3>().dot(groundPose.translation()); return plane; } return mLatestFootPlane; } void computeNewDepths() { auto view = mLatestView; auto plane = mUseFootPose ? getLatestFootPlane() : mFillPlane; if (mOverrideHeights) { FillMethods::fillEntireView(view, plane); } else { if (mShouldFillMissing) { // fill 0.5m square area underneath robot // TODO: could use timestamp of latest view Eigen::Isometry3d groundToLocal; mBotWrapper->getTransform("ground","local",groundToLocal); Eigen::Vector3d pos = groundToLocal.translation(); FillMethods::fillBox(view, pos, 0.5, plane); // fill holes in environment using neighbor values FillMethods::fillHolesIterative(view); // fill remaining areas with selected plane FillMethods::fillMissing(view, plane); } } } }; TerrainMap:: TerrainMap(const std::shared_ptr<drc::BotWrapper>& iBotWrapper) { mHelper.reset(new Helper(iBotWrapper)); } TerrainMap:: ~TerrainMap() { } void TerrainMap:: setInfo(const int64_t iViewId, const std::string& iMapChannel) { mHelper->mViewId = iViewId; mHelper->mMapChannel = iMapChannel; mHelper->mViewClient->removeAllViewChannels(); mHelper->mViewClient->addViewChannel(iMapChannel); } int64_t TerrainMap:: getViewId() const { return mHelper->mViewId; } std::string TerrainMap:: getMapChannel() const { return mHelper->mMapChannel; } void TerrainMap:: setFillPlane(const Eigen::Vector4d& iPlane) { mHelper->mFillPlane = iPlane; mHelper->mFillPlane /= iPlane.head<3>().norm(); } void TerrainMap:: useFootPose(const bool iVal) { mHelper->mUseFootPose = iVal; } void TerrainMap:: overrideHeights(const bool iVal) { mHelper->mOverrideHeights = iVal; } void TerrainMap:: setNormalMethod(const NormalMethod iMethod) { mHelper->mNormalMethod = iMethod; } void TerrainMap:: setNormalRadius(const double iRadius) { mHelper->mNormalRadius = iRadius; } void TerrainMap:: shouldFillMissing(const bool iVal) { mHelper->mShouldFillMissing = iVal; } double TerrainMap:: getNormalRadius() const { return mHelper->mNormalRadius; } bool TerrainMap:: startListening() { if (mHelper->mListening) return false; mHelper->mViewClient->start(); mHelper->mListening = true; return true; } bool TerrainMap:: stopListening() { if (!mHelper->mListening) return false; mHelper->mListening = false; mHelper->mViewClient->stop(); return true; } bool TerrainMap:: sendRequest(const Eigen::Vector3d& iBoxMin, const Eigen::Vector3d& iBoxMax, const double iResolutionMeters, const double iTimeWindowSeconds, const double iFrequencyHz) { maps::ViewBase::Spec spec; spec.mResolution = (float)iResolutionMeters; spec.mWidth = int((iBoxMax[0] - iBoxMin[0]) / spec.mResolution); spec.mHeight = int((iBoxMax[1] - iBoxMin[1]) / spec.mResolution); spec.mTimeMin = -iTimeWindowSeconds*1e6; spec.mClipPlanes.push_back(Eigen::Vector4f( 1, 0, 0, -iBoxMin[0])); spec.mClipPlanes.push_back(Eigen::Vector4f(-1, 0, 0, iBoxMax[0])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0, 1, 0, -iBoxMin[1])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0,-1, 0, iBoxMax[1])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0, 0, 1, -iBoxMin[2])); spec.mClipPlanes.push_back(Eigen::Vector4f( 0, 0,-1, iBoxMax[2])); spec.mMapId = 1; spec.mViewId = getViewId(); spec.mType = maps::ViewBase::TypeDepthImage; spec.mChannel = getMapChannel(); spec.mFrequency = iFrequencyHz; spec.mQuantizationMax = 0; spec.mTimeMax = 0; spec.mTimeMode = maps::ViewBase::TimeModeRelative; spec.mRelativeLocation = true; spec.mActive = true; Eigen::Isometry3f pose = Eigen::Isometry3f::Identity(); pose.translation() = Eigen::Vector3f(0,0,10); pose.linear() << 1,0,0, 0,-1,0, 0,0,-1; Eigen::Affine3f calib = Eigen::Affine3f::Identity(); calib(0,0) = 1/spec.mResolution; calib(1,1) = 1/spec.mResolution; calib(0,3) = -iBoxMin[0]*calib(0,0); calib(1,3) = -iBoxMin[1]*calib(1,1); Eigen::Projective3f projector = calib*pose.inverse(); spec.mTransform = projector; // send request mHelper->mViewClient->request(spec); return true; } std::shared_ptr<TerrainMap::TerrainData> TerrainMap:: getData() const { auto view = mHelper->mLatestView; if (view == NULL) return NULL; std::shared_ptr<TerrainData> data(new TerrainData()); auto type = maps::DepthImage::TypeDepth; auto image = view->getDepthImage(); data->mHeights = image->getData(type); data->mWidth = image->getWidth(); data->mHeight = image->getHeight(); data->mTransform = view->getTransform().cast<double>(); return data; } template <typename T> bool TerrainMap:: getHeightAndNormal(const T iX, const T iY, T& oHeight, Eigen::Matrix<T,3,1>& oNormal) const { bool usePlaneForHeight = mHelper->mOverrideHeights; bool usePlaneForNormal = (mHelper->mNormalMethod == NormalMethodOverride); if (!(usePlaneForHeight && usePlaneForNormal)) { Eigen::Vector3f pt, normal; const auto& view = mHelper->mLatestView; auto normalMethod = maps::DepthImageView::NormalMethodTriangle; switch (mHelper->mNormalMethod) { case NormalMethodOverride: normalMethod = maps::DepthImageView::NormalMethodZ; break; case NormalMethodTriangle: normalMethod = maps::DepthImageView::NormalMethodTriangle; break; case NormalMethodLeastSquares: normalMethod = maps::DepthImageView::NormalMethodLeastSquares; break; case NormalMethodRobustKernel: normalMethod = maps::DepthImageView::NormalMethodRobustKernel; break; case NormalMethodSampleConsensus: normalMethod = maps::DepthImageView::NormalMethodSampleConsensus; break; default: break; } if (view == NULL) usePlaneForHeight = usePlaneForNormal = true; else { view->setNormalMethod(normalMethod); if (!view->getClosest(Eigen::Vector3f(iX, iY, 0), pt, normal)) { usePlaneForHeight = usePlaneForNormal = true; } } oHeight = pt[2]; oNormal = normal.cast<T>(); } const auto plane = (mHelper->mUseFootPose ? mHelper->getLatestFootPlane() : mHelper->mFillPlane).cast<T>(); if (usePlaneForHeight) { oHeight = -(plane[0]*iX + plane[1]*iY + plane[3])/plane[2]; } if (usePlaneForNormal) { oNormal << plane[0],plane[1],plane[2]; } return true; } // explicit instantiations template bool TerrainMap:: getHeightAndNormal(const float iX, const float iY, float& oHeight, Eigen::Vector3f& oNormal) const; template bool TerrainMap:: getHeightAndNormal(const double iX, const double iY, double& oHeight, Eigen::Vector3d& oNormal) const; <|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; version 3 of the License. * * 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. */ #include "../dbmanager.h" #include "../iconmanager.h" #include "tablewidget.h" TableWidget::TableWidget(QWidget *parent) : AbstractTabWidget(parent) { setupUi(this); setupWidgets(); model = new QSqlTableModel(this); } TableWidget::TableWidget(QString table, QSqlDatabase *db, QWidget *parent) : AbstractTabWidget(parent) { setupUi(this); setupWidgets(); setTable(table, db); } QIcon TableWidget::icon() { return IconManager::get("table"); } QString TableWidget::id() { return QString("t %1 on %2") .arg(m_table) .arg(m_db->databaseName()); } void TableWidget::refresh() { if(!m_db->isOpen()) close(); } void TableWidget::reload() { if(!m_db->isOpen()) return; if(!m_db->tables().contains(m_table)) { qDebug("Unknown table !"); return; } tableView->setTable(m_table, m_db); } void TableWidget::setTable( QString table, QSqlDatabase *db ) { this->m_table = table; this->m_db = db; reload(); } void TableWidget::setupWidgets() { connect(tableView, SIGNAL(reloadRequested()), this, SLOT(reload())); } QString TableWidget::table() { return m_table; } <commit_msg>Bogue ouverture vues<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; version 3 of the License. * * 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. */ #include "../dbmanager.h" #include "../iconmanager.h" #include "tablewidget.h" TableWidget::TableWidget(QWidget *parent) : AbstractTabWidget(parent) { setupUi(this); setupWidgets(); model = new QSqlTableModel(this); } TableWidget::TableWidget(QString table, QSqlDatabase *db, QWidget *parent) : AbstractTabWidget(parent) { setupUi(this); setupWidgets(); setTable(table, db); } QIcon TableWidget::icon() { return IconManager::get("table"); } QString TableWidget::id() { return QString("t %1 on %2") .arg(m_table) .arg(m_db->databaseName()); } void TableWidget::refresh() { if(!m_db->isOpen()) close(); } void TableWidget::reload() { if(!m_db->isOpen()) return; if(!m_db->tables(QSql::Tables).contains(m_table) && !m_db->tables(QSql::Views).contains(m_table) && !m_db->tables(QSql::SystemTables).contains(m_table)) { qDebug("Unknown table !"); return; } tableView->setTable(m_table, m_db); } void TableWidget::setTable( QString table, QSqlDatabase *db ) { this->m_table = table; this->m_db = db; reload(); } void TableWidget::setupWidgets() { connect(tableView, SIGNAL(reloadRequested()), this, SLOT(reload())); } QString TableWidget::table() { return m_table; } <|endoftext|>
<commit_before>// // mc.cpp // // manage c++ code // // Created by Daniel Kozitza // #include <csignal> #include <dirent.h> #include <fstream> #include <iomanip> #include <sys/ioctl.h> #include "commands.hpp" #include "tools.hpp" using namespace tools; void build(vector<string>& argv); void cnt(); void dec(vector<string>& argv); void doc(vector<string>& argv); void env(); void makefile(vector<string>& argv); void mkreadme(vector<string>& argv); void rebuild(vector<string>& argv); void run(vector<string>& argv); int main(int argc, char *argv[]) { vector<string> Argv; string cmd_str; signal(SIGINT, signals_callback_handler); struct winsize ws; ioctl(0, TIOCGWINSZ, &ws); commands cmds; cmds.set_program_name(string(argv[0])); cmds.set_max_line_width(ws.ws_col); cmds.set_cmds_help( "\nmc is a tool for managing c++ source code.\n\n" "Usage:\n\n mc command [arguments]\n"); cmds.handle( "makefile", makefile, "Creates a make file by calling vfnmake [arguments].", "makefile [arguments]"); cmds.handle( "build", build, "Calls vfnmake [arguments] then make.", "build [arguments]"); cmds.handle( "rebuild", rebuild, "Calls make clean, vfnmake [arguments], then make.", "rebuild [arguments]"); cmds.handle( "run", run, "Calls vfnmake, make, then ./program [arguments].", "run [arguments]"); cmds.handle( "doc", doc, "Parses c++ files adding documentation and " "prompting the user for function descriptions.", "doc CPP_FILE"); cmds.handle( "dec", dec, "Ensures that all the functions listed in the given c++ " "source files are declared properly.", "dec CPP_FILE"); cmds.handle( "env", env, "Displays the variables read from vfnmake.conf.", "env"); cmds.handle( "mkreadme", mkreadme, "Make a README.md file from ./program [arguments].", "mkreadme"); cmds.handle( "cnt", cnt, "Counts the number of lines in each of the source files.", "cnt"); if (argc < 2) cmd_str = "help"; else cmd_str = argv[1]; for (int i = 2; i < argc; i++) Argv.push_back(string(argv[i])); cmds.run(cmd_str, Argv); return 0; } void makefile(vector<string>& argv) { string sys_call = "vfnmake"; for (int i = 0; i < argv.size(); i++) sys_call += " " + argv[i]; cout << "mc::makefile: calling `" << sys_call << "`.\n"; require(system(sys_call.c_str())); } void build(vector<string>& argv) { makefile(argv); cout << "mc::build: calling `make`.\n"; require(system("make")); } void rebuild(vector<string>& argv) { cout << "mc::rebuild: calling `make clean`.\n"; require(system("make clean")); build(argv); } void run(vector<string>& argv) { string args; for (int i = 0; i < argv.size(); i++) args += " " + argv[i]; vector<string> junk; build(junk); map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); string named_prog_call = "./"; named_prog_call += vfnconf["name"]; named_prog_call += args; cout << "mc::run: calling `" << named_prog_call << "`.\n\n"; system(named_prog_call.c_str()); } void doc(vector<string>& argv) { vector<string> fnames = argv; if (fnames.size() == 0) { // get .cpp file names by recursing through vfnconf["src_directory"] cout << "mc::doc: auto source file detection is under construction.\n"; } for (int fn_i = 0; fn_i < fnames.size(); fn_i++) { cout << "mc::doc: adding documentation to `" << fnames[fn_i] << "`.\n"; if (fnames.size() > 1) cout << "mc::doc: file " << fn_i+1 << " of " << fnames.size() << ".\n"; add_documentation(fnames[fn_i]); } } void dec(vector<string>& argv) { vector<string> fnames = argv; if (fnames.size() == 0) { cout << "mc::dec: auto source file detection is under construction.\n"; } map<string, vector<string>> scopedecs; // vector of all user defined includes found in fnames vector<string> includes; for (int fn_i = 0; fn_i < fnames.size(); fn_i++) { cout << "mc::dec: getting function declarations from `"; cout << fnames[fn_i] << "`.\n"; if (fnames.size() > 1) cout << "mc::dec: file " << fn_i+1 << " of " << fnames.size() << ".\n"; vector<string> funcdefs; get_func_defs(funcdefs, fnames[fn_i]); cout << "mc::dec: checking funcdefs:\n\n"; for (const auto item : funcdefs) cout << item << endl; cout << endl; form_scoped_declarations(scopedecs, funcdefs); get_includes(includes, fnames[fn_i]); } // do this for each namespace found? // ns_c_pair.first is the name of the namespace or class. // ns_c_pair.second is a vector of strings containing the declarations // created by form_scoped_declarations. for (const auto ns_c_pair : scopedecs) { cout << "mc::dec: searching for namespace definition called `"; cout << ns_c_pair.first << "`.\n"; // now scopedecs is pupulated with all the scoped declarations found in // the files fnames. Search for the header file by first checking the // user defined includes in the source files for the namespace definition. bool found_header_fname = false; string header_fname; // TODO: should try the src dir from all source files given string src_dir = fnames[0]; replace_first(src_dir, R"([^/]+$)", ""); for (const auto inc : includes) { // TODO: make sure this matches what we want string str_re = "^(namespace|class) " + ns_c_pair.first + "\\W"; cout << "mc::dec: trying regex `" << str_re << "` in file `"; cout << src_dir << inc << "`.\n"; // TODO: make sure str_re is properly escaped if (find_in_file(str_re, src_dir + inc)) { cout << " found the header file!\n"; found_header_fname = true; header_fname = src_dir + inc; break; } } // TODO: finish all these methods of searching for the header_fname //if (!found_header_fname) { // // here try to replace the extention of fnames with hpp then h //} //if (!found_header_fname) { // // here try to replace the extention and move up one dir //} // //if (!found_header_fname) { // // here try to look in the fnames files themselves //} // //if (!found_header_fname) { // // here check every file found in the src dir //} cout << "mc::dec: new_declarations:\n\n"; for (const auto item : ns_c_pair.second) cout << item << endl; cout << endl; require( found_header_fname, "mc::dec: could not find namespace `" + ns_c_pair.first + "`."); update_ns_or_class(ns_c_pair.first, ns_c_pair.second, header_fname); } } void env() { map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); cout << "\nvfnmake.conf:\n\n"; for (const auto item : vfnconf) { cout << item.first << ": " << item.second << "\n"; } cout << "\n"; } void mkreadme(vector<string>& argv) { map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); string sys_call = "echo '# " + vfnconf["name"] + "' > README.md"; cout << "mc::mkreadme: calling `" << sys_call << "`.\n"; require(system(sys_call.c_str())); sys_call = "./" + vfnconf["name"]; for (int i = 0; i < argv.size(); ++i) sys_call += argv[i]; sys_call += " >> README.md"; cout << "mc::mkreadme: calling `" << sys_call << "`.\n"; system(sys_call.c_str()); } void cnt() { map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); vector<string> contents; unsigned int total_lines = 0; if (!list_dir_r(vfnconf["src_directory"], contents)) { perror( string("mc::cnt: vfnmake src_directory `" + vfnconf["src_directory"] + "` does not exist").c_str()); return; } vector<string> new_contents; for (int i = 0; i < contents.size(); ++i) { if (matches(contents[i], R"((\.cpp|\.c|\.hpp|\.h)$)")) { new_contents.push_back(contents[i]); } } contents = new_contents; new_contents.clear(); int longest = 0; for (int i = 0; i < contents.size(); ++i) { string fname = vfnconf["src_directory"] + "/" + contents[i]; if (fname.size() > longest) longest = fname.size() + 1; } ifstream fh; for (int i = 0; i < contents.size(); ++i) { string fname = vfnconf["src_directory"] + "/" + contents[i]; fh.open(fname, ifstream::in); if (!fh.is_open()) { cout << "mc::cnt: could not open file: `" << fname << "`\n"; continue; } char c; int file_lines = 0; while (fh.peek() != EOF) { fh.get(c); if (c == '\n') ++file_lines; } fh.close(); total_lines += file_lines; fname += ":"; cout << left << setw(longest) << fname; cout << " " << file_lines << endl; } cout << endl << left << setw(longest) << "total_loc:"; cout << " " << total_lines << "\n\n"; } <commit_msg>minor change<commit_after>// // mc.cpp // // manage c++ code // // Created by Daniel Kozitza // #include <csignal> #include <dirent.h> #include <fstream> #include <iomanip> #include <sys/ioctl.h> #include "commands.hpp" #include "tools.hpp" using namespace tools; void build(vector<string>& argv); void cnt(); void dec(vector<string>& argv); void doc(vector<string>& argv); void env(); void makefile(vector<string>& argv); void mkreadme(vector<string>& argv); void rebuild(vector<string>& argv); void run(vector<string>& argv); int main(int argc, char *argv[]) { vector<string> Argv; string cmd_str; signal(SIGINT, signals_callback_handler); struct winsize ws; ioctl(0, TIOCGWINSZ, &ws); commands cmds; cmds.set_program_name(string(argv[0])); cmds.set_max_line_width(ws.ws_col); cmds.set_cmds_help( "\nmc is a tool for managing c++ source code.\n\n" "Usage:\n\n mc command [arguments]\n"); cmds.handle( "makefile", makefile, "Creates a make file by calling vfnmake [arguments].", "makefile [arguments]"); cmds.handle( "build", build, "Calls vfnmake [arguments] then make.", "build [arguments]"); cmds.handle( "rebuild", rebuild, "Calls make clean, vfnmake [arguments], then make.", "rebuild [arguments]"); cmds.handle( "run", run, "Calls vfnmake, make, then ./program [arguments].", "run [arguments]"); cmds.handle( "doc", doc, "Parses c++ files adding documentation and " "prompting the user for function descriptions.", "doc CPP_FILE"); cmds.handle( "dec", dec, "Ensures that all the functions listed in the given c++ " "source files are declared properly.", "dec CPP_FILE"); cmds.handle( "env", env, "Displays the variables read from vfnmake.conf.", "env"); cmds.handle( "mkreadme", mkreadme, "Make a README.md file from ./program [arguments].", "mkreadme"); cmds.handle( "cnt", cnt, "Counts the number of lines in each of the source files.", "cnt"); if (argc < 2) cmd_str = "help"; else cmd_str = argv[1]; for (int i = 2; i < argc; i++) Argv.push_back(string(argv[i])); cmds.run(cmd_str, Argv); return 0; } void makefile(vector<string>& argv) { string sys_call = "vfnmake"; for (int i = 0; i < argv.size(); i++) sys_call += " " + argv[i]; cout << "mc::makefile: calling `" << sys_call << "`.\n"; require(system(sys_call.c_str())); } void build(vector<string>& argv) { makefile(argv); cout << "mc::build: calling `make`.\n"; require(system("make")); } void rebuild(vector<string>& argv) { cout << "mc::rebuild: calling `make clean`.\n"; require(system("make clean")); build(argv); } void run(vector<string>& argv) { string args; for (int i = 0; i < argv.size(); i++) args += " " + argv[i]; vector<string> junk; build(junk); map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); string named_prog_call = "./"; named_prog_call += vfnconf["name"]; named_prog_call += args; cout << "mc::run: calling `" << named_prog_call << "`.\n\n"; system(named_prog_call.c_str()); } void doc(vector<string>& argv) { vector<string> fnames = argv; if (fnames.size() == 0) { // get .cpp file names by recursing through vfnconf["src_directory"] cout << "mc::doc: auto source file detection is under construction.\n"; } for (int fn_i = 0; fn_i < fnames.size(); fn_i++) { cout << "mc::doc: adding documentation to `" << fnames[fn_i] << "`.\n"; if (fnames.size() > 1) cout << "mc::doc: file " << fn_i+1 << " of " << fnames.size() << ".\n"; add_documentation(fnames[fn_i]); } } void dec(vector<string>& argv) { vector<string> fnames = argv; if (fnames.size() == 0) { cout << "mc::dec: auto source file detection is under construction.\n"; } map<string, vector<string>> scopedecs; // vector of all user defined includes found in fnames vector<string> includes; for (int fn_i = 0; fn_i < fnames.size(); fn_i++) { cout << "mc::dec: getting function declarations from `"; cout << fnames[fn_i] << "`.\n"; if (fnames.size() > 1) cout << "mc::dec: file " << fn_i+1 << " of " << fnames.size() << ".\n"; vector<string> funcdefs; get_func_defs(funcdefs, fnames[fn_i]); cout << "mc::dec: checking funcdefs:\n\n"; for (const auto item : funcdefs) cout << item << endl; cout << endl; form_scoped_declarations(scopedecs, funcdefs); get_includes(includes, fnames[fn_i]); } // do this for each namespace found? // ns_c_pair.first is the name of the namespace or class. // ns_c_pair.second is a vector of strings containing the declarations // created by form_scoped_declarations. for (const auto ns_c_pair : scopedecs) { cout << "mc::dec: searching for namespace definition called `"; cout << ns_c_pair.first << "`.\n"; // now scopedecs is pupulated with all the scoped declarations found in // the files fnames. Search for the header file by first checking the // user defined includes in the source files for the namespace definition. bool found_header_fname = false; string header_fname; // TODO: should try the src dir from all source files given string src_dir = fnames[0]; replace_first(src_dir, R"([^/]+$)", ""); for (const auto inc : includes) { // TODO: make sure this matches what we want string str_re = "^(namespace|class) " + ns_c_pair.first + "\\W"; cout << "mc::dec: trying regex `" << str_re << "` in file `"; cout << src_dir << inc << "`.\n"; // TODO: make sure str_re is properly escaped if (find_in_file(str_re, src_dir + inc)) { cout << " found the header file!\n"; found_header_fname = true; header_fname = src_dir + inc; break; } } // TODO: finish all these methods of searching for the header_fname //if (!found_header_fname) { // // here try to replace the extention of fnames with hpp then h //} //if (!found_header_fname) { // // here try to replace the extention and move up one dir //} // //if (!found_header_fname) { // // here try to look in the fnames files themselves //} // //if (!found_header_fname) { // // here check every file found in the src dir //} cout << "mc::dec: new_declarations:\n\n"; for (const auto item : ns_c_pair.second) cout << item << endl; cout << endl; require( found_header_fname, "mc::dec: could not find namespace `" + ns_c_pair.first + "`."); update_ns_or_class(ns_c_pair.first, ns_c_pair.second, header_fname); } } void env() { map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); cout << "\nvfnmake.conf:\n\n"; for (const auto item : vfnconf) { cout << item.first << ": " << item.second << "\n"; } cout << "\n"; } void mkreadme(vector<string>& argv) { map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); string sys_call = "echo '# " + vfnconf["name"] + "' > README.md"; cout << "mc::mkreadme: calling `" << sys_call << "`.\n"; require(system(sys_call.c_str())); sys_call = "./" + vfnconf["name"]; for (int i = 0; i < argv.size(); ++i) sys_call += " " + argv[i]; sys_call += " >> README.md"; cout << "mc::mkreadme: calling `" << sys_call << "`.\n"; system(sys_call.c_str()); } void cnt() { map<string, string> vfnconf; require(get_vfnmake_conf(vfnconf)); vector<string> contents; unsigned int total_lines = 0; if (!list_dir_r(vfnconf["src_directory"], contents)) { perror( string("mc::cnt: vfnmake src_directory `" + vfnconf["src_directory"] + "` does not exist").c_str()); return; } vector<string> new_contents; for (int i = 0; i < contents.size(); ++i) { if (matches(contents[i], R"((\.cpp|\.c|\.hpp|\.h)$)")) { new_contents.push_back(contents[i]); } } contents = new_contents; new_contents.clear(); int longest = 0; for (int i = 0; i < contents.size(); ++i) { string fname = vfnconf["src_directory"] + "/" + contents[i]; if (fname.size() > longest) longest = fname.size() + 1; } ifstream fh; for (int i = 0; i < contents.size(); ++i) { string fname = vfnconf["src_directory"] + "/" + contents[i]; fh.open(fname, ifstream::in); if (!fh.is_open()) { cout << "mc::cnt: could not open file: `" << fname << "`\n"; continue; } char c; int file_lines = 0; while (fh.peek() != EOF) { fh.get(c); if (c == '\n') ++file_lines; } fh.close(); total_lines += file_lines; fname += ":"; cout << left << setw(longest) << fname; cout << " " << file_lines << endl; } cout << endl << left << setw(longest) << "total_loc:"; cout << " " << total_lines << "\n\n"; } <|endoftext|>
<commit_before>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"; static const char* pszTestKey = "04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return HashKeccak(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(HashKeccak(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <commit_msg>new EDCSA keys<commit_after>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "04f2f9dc483111a7638ba2694ec675cef8d701162b430cd295acf322a18436c00ed5889d5fb289f7c89212484df5ea9d50522bdfad644f55d1b26a0f9c4d3a8f17"; static const char* pszTestKey = "04eda594f49c85300b089920977971fd3ac45445f0a00a2f371e35671e7dd84fe88ee94654048bc9f96f0b2dcc8c07caaee25bcce571be6181c8f385957ad06a76"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return HashKeccak(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(HashKeccak(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <|endoftext|>
<commit_before>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "0417d4b095e451d08bd83111d9ddc7f648af93d8f72e4391940bfa97bde644c0504e1f04a9e7e89be7e1c54c8995f8905be76f50d43fb4a31a7abba5e5291fbc63"; // TestNet alerts pubKey static const char* pszTestKey = "047805b1a52dd1d474ddc6cdbdcfa95021e82e688c2f3ad6cfeb4f094172931fa801419d52c294b2412e904775d6f6ab9421ff746ed0a8a86c1fbc2033621cbcd9"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRId64"\n" " nExpiration = %"PRId64"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything // even possibly remotely dangerous like & or > std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@"); std::string safeStatus; for (std::string::size_type i = 0; i < strStatusBar.size(); i++) { if (safeChars.find(strStatusBar[i]) != std::string::npos) safeStatus.push_back(strStatusBar[i]); } safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <commit_msg>Modified to accept new key structure<commit_after>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "0417d4b095e451d08bd83111d9ddc7f648af93d8f72e4391940bfa97bde644c0504e1f04a9e7e89be7e1c54c8995f8905be76f50d43fb4a31a7abba5e5291fbc63"; // TestNet alerts pubKey static const char* pszTestKey = "047805b1a52dd1d474ddc6cdbdcfa95021e82e688c2f3ad6cfeb4f094172931fa801419d52c294b2412e904775d6f6ab9421ff746ed0a8a86c1fbc2033621cbcd9"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRId64"\n" " nExpiration = %"PRId64"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything // even possibly remotely dangerous like & or > std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@"); std::string safeStatus; for (std::string::size_type i = 0; i < strStatusBar.size(); i++) { if (safeChars.find(strStatusBar[i]) != std::string::npos) safeStatus.push_back(strStatusBar[i]); } safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <|endoftext|>
<commit_before>#include "translator.hpp" #include "decl.hpp" #include "type.hpp" #include "context.hpp" #include "expr.hpp" #include "action.hpp" // for testing only #include <iostream> namespace pip { translator::translator(context& cxt) : cxt(cxt) { } /// program ::= (pip <decl-seq>) decl* translator::trans_program(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; match_list(list, "pip", &decls); return new program_decl(std::move(decls)); } sexpr::throw_unexpected_term(e); } /// decl-seq ::= (<decl*>) decl_seq translator::trans_decls(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; // for (const sexpr::expr* elem : list->exprs) { decl* d = trans_decl(list); decls.push_back(d); // } return decls; } sexpr::throw_unexpected_term(e); } /// decl ::= table-decl | meter-decl decl* translator::trans_decl(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "table") return trans_table(list); sexpr::throw_unexpected_id(cast<sexpr::id_expr>(list->exprs[0])); } sexpr::throw_unexpected_term(e); } /// table-decl ::= (table id <match-kind> <match-seq>) /// /// rule-kind ::= exact | prefix | wildcard | range /// /// FIXME: We actually need parse the key extraction program. This /// would be a sequence of actions that bits from the current offset /// into a "key register". decl* translator::trans_table(const sexpr::list_expr* e) { symbol* id; symbol* kind; action_seq actions; rule_seq rules; match_list(e, "table", &id, &kind, &actions, &rules); // TODO: Actually parse the kind of match. For now, we can simply // assume that all tables are exact. Hint: use the match_list framework // to return a match kind. return new table_decl(id, rk_exact, std::move(rules)); } /// rule_seq ::= (<rule*>) rule_seq translator::trans_rules(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { rule_seq rules; // IN PROGRESS: Match each element in turn. for (const sexpr::expr* elem : list->exprs) { rule* r = trans_rule(elem); rules.push_back(r); } return rules; } sexpr::throw_unexpected_term(e); } rule* translator::trans_rule(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; expr* key; action_seq actions; match_list(list, "rule", key, &actions); // TODO: match_list matches an expr_seq, but rule is constructed // with a single expr*. Resolve this issue. // return new rule(rk_exact, exprs, std::move(actions)); return new rule(rk_exact, key, std::move(actions)); } sexpr::throw_unexpected_term(e); } action_seq translator::trans_actions(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { action_seq actions; for (const sexpr::expr* elem : list->exprs) { action* a = trans_action(elem); actions.push_back(a); } return actions; } sexpr::throw_unexpected_term(e); } // TODO: Implement me. action* translator::trans_action(const sexpr::expr* e) { if (const sexpr::id_expr* name = as<sexpr::id_expr>(e)) { if(*(name->id) == "advance") return new action(ak_advance); if(*(name->id) == "copy") return new action(ak_copy); if(*(name->id) == "set") return new action(ak_set); if(*(name->id) == "write") return new action(ak_write); if(*(name->id) == "clear") return new action(ak_clear); if( *(name->id) == "drop" ) return cxt.make_action(ak_drop); if( *(name->id) == "match" ) return new action(ak_match); if( *(name->id) == "goto" ) return new action(ak_goto); if( *(name->id) == "output" ) return new action(ak_output); } sexpr::throw_unexpected_term(e); } expr* translator::trans_expr(const sexpr::expr* e) { // Match bare integer literals. if (const sexpr::int_expr* num = as<sexpr::int_expr>(e)) return trans_int_expr(num); // Match bare keyword literals. if (const sexpr::id_expr* id = as<sexpr::id_expr>(e)) { if (*id->id == "miss") return trans_miss_expr(id); } // Match phrases. // // FIXME: Use a lookup table + switch. if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "wildcard") return trans_wild_expr(list); if (*sym == "range") return trans_range_expr(list); if (*sym == "port"); // return trans_port_expr(list); } } expr_seq translator::trans_exprs(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; for (const sexpr::expr* elem : list->exprs) { expr* e = trans_expr(elem); exprs.push_back(e); } return exprs; } sexpr::throw_unexpected_term(e); } expr* translator::trans_range_expr(const sexpr::list_expr* e) { // TODO: find proper way to match type?? // TODO: figure out how match_list is supposed to work // type* t; // int_expr* lo; // int_expr* hi; symbol* range_kw; symbol* lo_type; symbol* lo; symbol* hi_type; symbol* hi; match_list(e, &range_kw, &lo_type, &lo, &hi_type, &hi); std::cout << *range_kw << ' ' << *lo_type << ' ' << *lo << ' ' << *hi_type << *hi << '\n'; // return cxt.make_range_expr( new range_type(nullptr), lo->val, hi->val ); return nullptr; } expr* translator::trans_wild_expr(const sexpr::list_expr* e) { } expr* translator::trans_miss_expr(const sexpr::id_expr* e) { } expr* translator::trans_ref_expr(const sexpr::id_expr* e) { } expr* translator::trans_field_expr(const sexpr::id_expr* e) { } expr* translator::trans_int_expr(const sexpr::int_expr* e) { return cxt.make_int_expr( new int_type(32), e->val ); } // -------------------------------------------------------------------------- // // Matching void translator::match(const sexpr::list_expr* list, int n, decl_seq* decls) { *decls = trans_decls(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, rule_seq* rules) { *rules = trans_rules(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr_seq* exprs) { *exprs = trans_exprs(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr* out) { out = trans_expr(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, action_seq* actions) { *actions = trans_actions(get(list, n)); } } // namespace pip <commit_msg>simple tables now translateable<commit_after>#include "translator.hpp" #include "decl.hpp" #include "type.hpp" #include "context.hpp" #include "expr.hpp" #include "action.hpp" #include "dumper.hpp" // for testing only #include <iostream> namespace pip { translator::translator(context& cxt) : cxt(cxt) { } /// program ::= (pip <decl-seq>) decl* translator::trans_program(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; match_list(list, "pip", &decls); return new program_decl(std::move(decls)); } sexpr::throw_unexpected_term(e); } /// decl-seq ::= (<decl*>) decl_seq translator::trans_decls(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { decl_seq decls; // for (const sexpr::expr* elem : list->exprs) { decl* d = trans_decl(list); decls.push_back(d); // } return decls; } sexpr::throw_unexpected_term(e); } /// decl ::= table-decl | meter-decl decl* translator::trans_decl(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "table") return trans_table(list); sexpr::throw_unexpected_id(cast<sexpr::id_expr>(list->exprs[0])); } sexpr::throw_unexpected_term(e); } /// table-decl ::= (table id <match-kind> <match-seq>) /// /// rule-kind ::= exact | prefix | wildcard | range /// /// FIXME: We actually need parse the key extraction program. This /// would be a sequence of actions that bits from the current offset /// into a "key register". decl* translator::trans_table(const sexpr::list_expr* e) { symbol* id; symbol* kind; action_seq actions; rule_seq rules; match_list(e, "table", &id, &kind, &actions, &rules); // TODO: Actually parse the kind of match. For now, we can simply // assume that all tables are exact. Hint: use the match_list framework // to return a match kind. return new table_decl(id, rk_exact, std::move(rules)); } /// rule_seq ::= (<rule*>) rule_seq translator::trans_rules(const sexpr::expr* e) { std::cout << "hello\n"; if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { std::cout << "jello\n"; rule_seq rules; // IN PROGRESS: Match each element in turn. rule* r = trans_rule(e); rules.push_back(r); return rules; } sexpr::throw_unexpected_term(e); } rule* translator::trans_rule(const sexpr::expr* e) { std::cout << "yello\n"; if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { std::cout << "fello\n"; expr_seq exprs; expr* key; action_seq actions; std::cout << "smello\n"; match_list(list, "rule", key, &actions); // TODO: match_list matches an expr_seq, but rule is constructed // with a single expr*. Resolve this issue. // return new rule(rk_exact, exprs, std::move(actions)); return new rule(rk_exact, key, std::move(actions)); } std::cout << "bello\n"; sexpr::throw_unexpected_term(e); } action_seq translator::trans_actions(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { action_seq actions; for (const sexpr::expr* elem : list->exprs) { action* a = trans_action(elem); actions.push_back(a); } return actions; } sexpr::throw_unexpected_term(e); } // TODO: parse extra information (i.e. expr to output for output_action). action* translator::trans_action(const sexpr::expr* e) { if (const sexpr::id_expr* name = as<sexpr::id_expr>(e)) { if(*(name->id) == "advance") return new action(ak_advance); if(*(name->id) == "copy") return new action(ak_copy); if(*(name->id) == "set") return new action(ak_set); if(*(name->id) == "write") return new action(ak_write); if(*(name->id) == "clear") return new action(ak_clear); if( *(name->id) == "drop" ) return cxt.make_action(ak_drop); if( *(name->id) == "match" ) return new action(ak_match); if( *(name->id) == "goto" ) return new action(ak_goto); if( *(name->id) == "output" ) return new action(ak_output); } sexpr::throw_unexpected_term(e); } expr* translator::trans_expr(const sexpr::expr* e) { // Match bare integer literals. if (const sexpr::int_expr* num = as<sexpr::int_expr>(e)) return trans_int_expr(num); // Match bare keyword literals. if (const sexpr::id_expr* id = as<sexpr::id_expr>(e)) { if (*id->id == "miss") return trans_miss_expr(id); } // Match phrases. // // FIXME: Use a lookup table + switch. if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { symbol* sym; match_list(list, &sym); if (*sym == "wildcard") return trans_wild_expr(list); if (*sym == "range") return trans_range_expr(list); if (*sym == "port"); // return trans_port_expr(list); } } expr_seq translator::trans_exprs(const sexpr::expr* e) { if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) { expr_seq exprs; for (const sexpr::expr* elem : list->exprs) { expr* e = trans_expr(elem); exprs.push_back(e); } return exprs; } sexpr::throw_unexpected_term(e); } expr* translator::trans_range_expr(const sexpr::list_expr* e) { // TODO: find proper way to match type?? // TODO: figure out how match_list is supposed to work // type* t; // int_expr* lo; // int_expr* hi; symbol* range_kw; symbol* lo_type; symbol* lo; symbol* hi_type; symbol* hi; match_list(e, &range_kw, &lo_type, &lo, &hi_type, &hi); std::cout << *range_kw << ' ' << *lo_type << ' ' << *lo << ' ' << *hi_type << *hi << '\n'; // return cxt.make_range_expr( new range_type(nullptr), lo->val, hi->val ); return nullptr; } expr* translator::trans_wild_expr(const sexpr::list_expr* e) { } expr* translator::trans_miss_expr(const sexpr::id_expr* e) { } expr* translator::trans_ref_expr(const sexpr::id_expr* e) { } expr* translator::trans_field_expr(const sexpr::id_expr* e) { } expr* translator::trans_int_expr(const sexpr::int_expr* e) { return cxt.make_int_expr( new int_type(32), e->val ); } // -------------------------------------------------------------------------- // // Matching void translator::match(const sexpr::list_expr* list, int n, decl_seq* decls) { *decls = trans_decls(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, rule_seq* rules) { *rules = trans_rules(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr_seq* exprs) { *exprs = trans_exprs(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, expr* out) { out = trans_expr(get(list, n)); } void translator::match(const sexpr::list_expr* list, int n, action_seq* actions) { *actions = trans_actions(get(list, n)); } } // namespace pip <|endoftext|>
<commit_before>// Copyright (c) 2012-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/memory.h> #include <util/system.h> #include <util/time.h> #include <validation.h> #include <test/util/setup_common.h> #include <checkqueue.h> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const unsigned int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b {false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze {false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait(l, []{ return nFrozen.load(std::memory_order_relaxed) == 0;}); } } void swap(FrozenCleanupCheck& x){std::swap(should_freeze, x.should_freeze);}; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ static void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = MakeUnique<Correct_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{small_queue->Thread();}); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (const size_t i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t) InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000/1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = MakeUnique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = MakeUnique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (auto times = 0; times < 10; ++times) { for (const bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r =control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = MakeUnique<Unique_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = MakeUnique<Memory_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i/2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0U); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = MakeUnique<FrozenCleanup_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); bool waitResult = control.Wait(); // Hangs here assert(waitResult); }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, [](){return FrozenCleanupCheck::nFrozen == 1;}); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = MakeUnique<Standard_Queue>(QUEUE_BATCH_SIZE); { boost::thread_group tg; std::atomic<int> nThreads {0}; std::atomic<int> fails {0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&]{ CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; bool has_lock{false}; bool has_tried{false}; bool done{false}; bool done_ack{false}; { std::unique_lock<std::mutex> l(m); tg.create_thread([&]{ CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&]{return has_tried;}); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&]{return done_ack;}); }); // Wait for thread to get the lock cv.wait(l, [&](){return has_lock;}); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&](){return done;}); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>[tests] Don't use TestingSetup in the checkqueue_tests<commit_after>// Copyright (c) 2012-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/memory.h> #include <util/system.h> #include <util/time.h> #include <test/util/setup_common.h> #include <checkqueue.h> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const unsigned int QUEUE_BATCH_SIZE = 128; static const int SCRIPT_CHECK_THREADS = 3; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b {false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze {false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait(l, []{ return nFrozen.load(std::memory_order_relaxed) == 0;}); } } void swap(FrozenCleanupCheck& x){std::swap(should_freeze, x.should_freeze);}; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ static void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = MakeUnique<Correct_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&]{small_queue->Thread();}); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (const size_t i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t) InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000/1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = MakeUnique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = MakeUnique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (auto times = 0; times < 10; ++times) { for (const bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r =control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = MakeUnique<Unique_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&]{queue->Thread();}); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = MakeUnique<Memory_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&]{queue->Thread();}); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i/2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0U); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = MakeUnique<FrozenCleanup_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; bool fails = false; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&]{queue->Thread();}); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); bool waitResult = control.Wait(); // Hangs here assert(waitResult); }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, [](){return FrozenCleanupCheck::nFrozen == 1;}); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = MakeUnique<Standard_Queue>(QUEUE_BATCH_SIZE); { boost::thread_group tg; std::atomic<int> nThreads {0}; std::atomic<int> fails {0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&]{ CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; bool has_lock{false}; bool has_tried{false}; bool done{false}; bool done_ack{false}; { std::unique_lock<std::mutex> l(m); tg.create_thread([&]{ CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&]{return has_tried;}); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&]{return done_ack;}); }); // Wait for thread to get the lock cv.wait(l, [&](){return has_lock;}); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&](){return done;}); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: rsckey.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2005-01-03 17:22:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _RSCKEY_HXX #define _RSCKEY_HXX /****************** C l a s s F o r w a r d s **************************/ class RscTop; #ifndef _RSCALL_H #include <rscall.h> #endif typedef struct { Atom nName; sal_uInt32 nTyp; long yylval; } KEY_STRUCT; class RscNameTable { BOOL bSort; //soll bei jedem einfuegen sortiert werden? sal_uInt32 nEntries; //Anzahl der Eintr�ge KEY_STRUCT * pTable; public: RscNameTable(); ~RscNameTable(); void SetSort( BOOL bSorted = TRUE ); Atom Put( Atom nName, sal_uInt32 nTyp, long nValue ); Atom Put( Atom nName, sal_uInt32 nTyp ); Atom Put( const char * pName, sal_uInt32 nTyp, long nValue ); Atom Put( const char * pName, sal_uInt32 nTyp ); Atom Put( Atom nName, sal_uInt32 nTyp, RscTop * pClass ); Atom Put( const char * pName, sal_uInt32 nTyp, RscTop * pClass ); // TRUE, wurde gefunden BOOL Get( Atom nName, KEY_STRUCT * pEle ); }; #endif// _RSCKEY_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.18); FILE MERGED 2005/09/05 18:46:51 rt 1.3.18.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rsckey.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 13:32:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _RSCKEY_HXX #define _RSCKEY_HXX /****************** C l a s s F o r w a r d s **************************/ class RscTop; #ifndef _RSCALL_H #include <rscall.h> #endif typedef struct { Atom nName; sal_uInt32 nTyp; long yylval; } KEY_STRUCT; class RscNameTable { BOOL bSort; //soll bei jedem einfuegen sortiert werden? sal_uInt32 nEntries; //Anzahl der Eintr�ge KEY_STRUCT * pTable; public: RscNameTable(); ~RscNameTable(); void SetSort( BOOL bSorted = TRUE ); Atom Put( Atom nName, sal_uInt32 nTyp, long nValue ); Atom Put( Atom nName, sal_uInt32 nTyp ); Atom Put( const char * pName, sal_uInt32 nTyp, long nValue ); Atom Put( const char * pName, sal_uInt32 nTyp ); Atom Put( Atom nName, sal_uInt32 nTyp, RscTop * pClass ); Atom Put( const char * pName, sal_uInt32 nTyp, RscTop * pClass ); // TRUE, wurde gefunden BOOL Get( Atom nName, KEY_STRUCT * pEle ); }; #endif// _RSCKEY_HXX <|endoftext|>
<commit_before>#include "Genes/Look_Ahead_Gene.h" #include <cassert> #include <memory> #include <algorithm> #include "Genes/Gene.h" #include "Utility.h" #include "Game/Board.h" #include "Game/Clock.h" class Move; Look_Ahead_Gene::Look_Ahead_Gene() : mean_game_length(50), game_length_uncertainty(0.5), speculation_constant(1.0), capturing_speculation_constant(1.0) { } void Look_Ahead_Gene::reset_properties() const { properties["Mean Game Length"] = mean_game_length; properties["Game Length Uncertainty"] = game_length_uncertainty; properties["Speculation Constant"] = speculation_constant; properties["Capturing Speculation Constant"] = capturing_speculation_constant; } void Look_Ahead_Gene::load_properties() { mean_game_length = properties["Mean Game Length"]; game_length_uncertainty = properties["Game Length Uncertainty"]; speculation_constant = properties["Speculation Constant"]; capturing_speculation_constant = properties["Capturing Speculation Constant"]; } double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const { auto time_left = clock.time_left(board.whose_turn()); auto moves_to_reset = clock.moves_to_reset(board.whose_turn()); auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far); return time_left/std::min(moves_left, double(moves_to_reset)); } void Look_Ahead_Gene::gene_specific_mutation() { switch(Random::random_integer(1, 4)) { case 1: mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0)); break; case 2: game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05)); break; case 3: speculation_constant += Random::random_normal(0.01); break; case 4: capturing_speculation_constant += Random::random_normal(0.01); break; default: assert(false); // If here, random_integer() called with wrong parameters break; } } std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const { return std::make_unique<Look_Ahead_Gene>(*this); } std::string Look_Ahead_Gene::name() const { return "Look Ahead Gene"; } double Look_Ahead_Gene::score_board(const Board&) const { return 0.0; } double Look_Ahead_Gene::speculation_time_factor(const Board& board) const { return board.capture_possible() ? capturing_speculation_constant : speculation_constant; } <commit_msg>Increase mutation rate of speculation constants<commit_after>#include "Genes/Look_Ahead_Gene.h" #include <cassert> #include <memory> #include <algorithm> #include "Genes/Gene.h" #include "Utility.h" #include "Game/Board.h" #include "Game/Clock.h" class Move; Look_Ahead_Gene::Look_Ahead_Gene() : mean_game_length(50), game_length_uncertainty(0.5), speculation_constant(1.0), capturing_speculation_constant(1.0) { } void Look_Ahead_Gene::reset_properties() const { properties["Mean Game Length"] = mean_game_length; properties["Game Length Uncertainty"] = game_length_uncertainty; properties["Speculation Constant"] = speculation_constant; properties["Capturing Speculation Constant"] = capturing_speculation_constant; } void Look_Ahead_Gene::load_properties() { mean_game_length = properties["Mean Game Length"]; game_length_uncertainty = properties["Game Length Uncertainty"]; speculation_constant = properties["Speculation Constant"]; capturing_speculation_constant = properties["Capturing Speculation Constant"]; } double Look_Ahead_Gene::time_to_examine(const Board& board, const Clock& clock) const { auto time_left = clock.time_left(board.whose_turn()); auto moves_to_reset = clock.moves_to_reset(board.whose_turn()); auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player auto moves_left = Math::average_moves_left(mean_game_length, game_length_uncertainty, moves_so_far); return time_left/std::min(moves_left, double(moves_to_reset)); } void Look_Ahead_Gene::gene_specific_mutation() { switch(Random::random_integer(1, 4)) { case 1: mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0)); break; case 2: game_length_uncertainty = std::abs(game_length_uncertainty + Random::random_normal(0.05)); break; case 3: speculation_constant += Random::random_normal(0.05); break; case 4: capturing_speculation_constant += Random::random_normal(0.05); break; default: assert(false); // If here, random_integer() called with wrong parameters break; } } std::unique_ptr<Gene> Look_Ahead_Gene::duplicate() const { return std::make_unique<Look_Ahead_Gene>(*this); } std::string Look_Ahead_Gene::name() const { return "Look Ahead Gene"; } double Look_Ahead_Gene::score_board(const Board&) const { return 0.0; } double Look_Ahead_Gene::speculation_time_factor(const Board& board) const { return board.capture_possible() ? capturing_speculation_constant : speculation_constant; } <|endoftext|>
<commit_before>#include <GuiBase/Viewer/Viewer.hpp> #include <iostream> #include <QTimer> #include <QMouseEvent> #include <QPainter> #include <Core/String/StringUtils.hpp> #include <Core/Log/Log.hpp> #include <Core/Math/ColorPresets.hpp> #include <Core/Math/Math.hpp> #include <Core/Containers/MakeShared.hpp> #include <Core/Image/stb_image_write.h> #include <Engine/Renderer/OpenGL/OpenGL.hpp> #include <Engine/Component/Component.hpp> #include <Engine/Renderer/Renderer.hpp> #include <Engine/Renderer/Light/DirLight.hpp> #include <Engine/Renderer/Camera/Camera.hpp> #include <Engine/Renderer/Texture/Texture.hpp> #include <Engine/Managers/SystemDisplay/SystemDisplay.hpp> #include <Engine/Renderer/Renderers/ForwardRenderer.hpp> #include <GuiBase/Viewer/TrackballCamera.hpp> #include <GuiBase/Viewer/Gizmo/GizmoManager.hpp> #include <GuiBase/Utils/Keyboard.hpp> namespace Ra { Gui::Viewer::Viewer( QWidget* parent ) : QOpenGLWidget( parent ) , m_gizmoManager(new GizmoManager(this)) , m_renderThread( nullptr ) { // Allow Viewer to receive events setFocusPolicy( Qt::StrongFocus ); setMinimumSize( QSize( 800, 600 ) ); m_camera.reset( new Gui::TrackballCamera( width(), height() ) ); /// Intercept events to properly lock the renderer when it is compositing. } Gui::Viewer::~Viewer(){} void Gui::Viewer::initializeGL() { initializeOpenGLFunctions(); LOG( logINFO ) << "*** Radium Engine Viewer ***"; LOG( logINFO ) << "Renderer : " << glGetString( GL_RENDERER ); LOG( logINFO ) << "Vendor : " << glGetString( GL_VENDOR ); LOG( logINFO ) << "OpenGL : " << glGetString( GL_VERSION ); LOG( logINFO ) << "GLSL : " << glGetString( GL_SHADING_LANGUAGE_VERSION ); #if defined (OS_WINDOWS) glewExperimental = GL_TRUE; GLuint result = glewInit(); if ( result != GLEW_OK ) { std::string errorStr; Ra::Core::StringUtils::stringPrintf( errorStr, " GLEW init failed : %s", glewGetErrorString( result ) ); CORE_ERROR( errorStr.c_str() ); } else { LOG( logINFO ) << "GLEW : " << glewGetString( GLEW_VERSION ); glFlushError(); } #endif // FIXME(Charly): Renderer type should not be changed here m_renderers.resize( 1 ); // FIXME(Mathias): width and height might be wrong the first time ResizeGL is called (see QOpenGLWidget doc). This may cause problem on Retina display under MacOsX m_renderers[0].reset( new Engine::ForwardRenderer( width(), height() ) ); for ( auto& renderer : m_renderers ) { renderer->initialize(); } m_currentRenderer = m_renderers[0].get(); auto light = Ra::Core::make_shared<Engine::DirectionalLight>(); for ( auto& renderer : m_renderers ) { renderer->addLight( light ); } m_camera->attachLight( light ); emit rendererReady(); } Gui::CameraInterface* Gui::Viewer::getCameraInterface() { return m_camera.get(); } Gui::GizmoManager* Gui::Viewer::getGizmoManager() { return m_gizmoManager; } const Engine::Renderer* Gui::Viewer::getRenderer() const { return m_currentRenderer; } void Gui::Viewer::onAboutToCompose() { // This slot function is called from the main thread as part of the event loop // when the GUI is about to update. We have to wait for the rendering to finish. m_currentRenderer->lockRendering(); } void Gui::Viewer::onFrameSwapped() { // This slot is called from the main thread as part of the event loop when the // GUI has finished displaying the rendered image, so we unlock the renderer. m_currentRenderer->unlockRendering(); } void Gui::Viewer::onAboutToResize() { // Like swap buffers, resizing is a blocking operation and we have to wait for the rendering // to finish before resizing. m_currentRenderer->lockRendering(); } void Gui::Viewer::onResized() { m_currentRenderer->unlockRendering(); } void Gui::Viewer::resizeGL( int width, int height ) { // FIXME(Mathias) : Problem of glarea dimension on OsX Retina Display (half the size) // Renderer should have been locked by previous events. m_camera->resizeViewport( width, height ); m_currentRenderer->resize( width, height ); } void Gui::Viewer::mousePressEvent( QMouseEvent* event ) { switch ( event->button() ) { case Qt::LeftButton: { #ifdef OS_MACOS // (Mathias) no middle button on Apple (only left, right and wheel) // replace middle button by <ctrl>+left (note : ctrl = "command" // fake the subsistem by setting MiddleButtonEvent and masking ControlModifier if (event->modifiers().testFlag( Qt::ControlModifier ) ) { auto mods = event->modifiers(); mods^=Qt::ControlModifier; QMouseEvent macevent(event->type(), event->localPos(), event->windowPos(), event->screenPos(), Qt::MiddleButton, event->buttons(), mods, event->source() ); m_camera->handleMousePressEvent(&macevent); } #endif if ( isKeyPressed( Qt::Key_Space ) ) { LOG( logINFO ) << "Raycast query launched"; Core::Ray r = m_camera->getCamera()->getRayFromScreen(Core::Vector2(event->x(), event->y())); RA_DISPLAY_POINT(r.origin(), Core::Colors::Cyan(), 0.1f); RA_DISPLAY_RAY(r, Core::Colors::Yellow()); auto ents = Engine::RadiumEngine::getInstance()->getEntityManager()->getEntities(); for (auto e : ents) { e->rayCastQuery(r); } } else { Engine::Renderer::PickingQuery query = { Core::Vector2(event->x(), height() - event->y()), Core::MouseButton::RA_MOUSE_LEFT_BUTTON }; m_currentRenderer->addPickingRequest(query); m_gizmoManager->handleMousePressEvent(event); } } break; case Qt::MiddleButton: { m_camera->handleMousePressEvent(event); } break; case Qt::RightButton: { // Check picking Engine::Renderer::PickingQuery query = { Core::Vector2(event->x(), height() - event->y()), Core::MouseButton::RA_MOUSE_RIGHT_BUTTON }; m_currentRenderer->addPickingRequest(query); } break; default: { } break; } } void Gui::Viewer::mouseReleaseEvent( QMouseEvent* event ) { m_camera->handleMouseReleaseEvent( event ); m_gizmoManager->handleMouseReleaseEvent(event); } void Gui::Viewer::mouseMoveEvent( QMouseEvent* event ) { m_camera->handleMouseMoveEvent( event ); m_gizmoManager->handleMouseMoveEvent(event); } void Gui::Viewer::wheelEvent( QWheelEvent* event ) { m_camera->handleWheelEvent(event); QOpenGLWidget::wheelEvent( event ); } void Gui::Viewer::keyPressEvent( QKeyEvent* event ) { keyPressed(event->key()); m_camera->handleKeyPressEvent( event ); QOpenGLWidget::keyPressEvent(event); } void Gui::Viewer::keyReleaseEvent( QKeyEvent* event ) { keyReleased(event->key()); m_camera->handleKeyReleaseEvent( event ); if (event->key() == Qt::Key_Z && !event->isAutoRepeat()) { m_currentRenderer->toggleWireframe(); } QOpenGLWidget::keyReleaseEvent(event); } void Gui::Viewer::reloadShaders() { // FIXME : check thread-saefty of this. m_currentRenderer->lockRendering(); makeCurrent(); m_currentRenderer->reloadShaders(); doneCurrent(); m_currentRenderer->unlockRendering(); } void Gui::Viewer::displayTexture( const QString &tex ) { m_currentRenderer->lockRendering(); m_currentRenderer->displayTexture( tex.toStdString() ); m_currentRenderer->unlockRendering(); } void Gui::Viewer::changeRenderer( int index ) { // NOTE(Charly): This is probably buggy since it has not been tested. LOG( logWARNING ) << "Changing renderers might be buggy since it has not been tested."; m_currentRenderer->lockRendering(); m_currentRenderer = m_renderers[index].get(); m_currentRenderer->initialize(); m_currentRenderer->resize( width(), height() ); m_currentRenderer->unlockRendering(); } // Asynchronous rendering implementation void Gui::Viewer::startRendering( const Scalar dt ) { makeCurrent(); // Move camera if needed. Disabled for now as it takes too long (see issue #69) //m_camera->update( dt ); Engine::RenderData data; data.dt = dt; data.projMatrix = m_camera->getProjMatrix(); data.viewMatrix = m_camera->getViewMatrix(); m_currentRenderer->render( data ); } void Gui::Viewer::waitForRendering() { } void Gui::Viewer::handleFileLoading( const std::string& file ) { for ( auto& renderer : m_renderers ) { renderer->handleFileLoading( file ); } } void Gui::Viewer::processPicking() { CORE_ASSERT( m_currentRenderer->getPickingQueries().size() == m_currentRenderer->getPickingResults().size(), "There should be one result per query." ); for (uint i = 0 ; i < m_currentRenderer->getPickingQueries().size(); ++i) { const Engine::Renderer::PickingQuery& query = m_currentRenderer->getPickingQueries()[i]; if ( query.m_button == Core::MouseButton::RA_MOUSE_LEFT_BUTTON) { emit leftClickPicking(m_currentRenderer->getPickingResults()[i]); } else if (query.m_button == Core::MouseButton::RA_MOUSE_RIGHT_BUTTON) { emit rightClickPicking(m_currentRenderer->getPickingResults()[i]); } } } void Gui::Viewer::fitCameraToScene( const Core::Aabb& aabb ) { m_camera->fitScene( aabb ); } std::vector<std::string> Gui::Viewer::getRenderersName() const { std::vector<std::string> ret; for ( const auto& r : m_renderers ) { ret.push_back( r->getRendererName() ); } return ret; } void Gui::Viewer::grabFrame( const std::string& filename ) { makeCurrent(); Engine::Texture* tex = m_currentRenderer->getDisplayTexture(); tex->bind(); // Get a buffer to store the pixels of the OpenGL texture (in float format) float* pixels = new float[tex->width() * tex->height() * 4]; // Grab the texture data GL_ASSERT(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, pixels)); // Now we must convert the floats to RGB while flipping the image updisde down. unsigned char* writtenPixels = new uchar[tex->width() * tex->height() * 4]; for (uint j = 0; j < tex->height(); ++j) { for (uint i = 0; i < tex->width(); ++i) { uint in = 4 * (j * tex->width() + i); // Index in the texture buffer uint ou = 4 * ((tex->height() - 1 - j) * tex->width() + i); // Index in the final image (note the j flipping). writtenPixels[ou + 0] = Ra::Core::Math::clamp<uchar>(pixels[in + 0] * 255.f, 0u, 0xffu); writtenPixels[ou + 1] = Ra::Core::Math::clamp<uchar>(pixels[in + 1] * 255.f, 0u, 0xffu); writtenPixels[ou + 2] = Ra::Core::Math::clamp<uchar>(pixels[in + 2] * 255.f, 0u, 0xffu); writtenPixels[ou + 3] = 0xff; } } std::string ext = Core::StringUtils::getFileExt(filename); if (ext == "bmp") { stbi_write_bmp(filename.c_str(), tex->width(), tex->height(), 4, writtenPixels); } else if (ext == "png") { stbi_write_png(filename.c_str(), tex->width(), tex->height(), 4, writtenPixels, tex->width() * 4 * sizeof(uchar)); } else { LOG(logWARNING) << "Cannot write frame to "<<filename<<" : unsupported extension"; } delete[] pixels; delete[] writtenPixels; } void Gui::Viewer::enablePostProcess(int enabled) { m_currentRenderer->enablePostProcess(enabled); } void Gui::Viewer::enableDebugDraw(int enabled) { m_currentRenderer->enableDebugDraw(enabled); } } // namespace Ra <commit_msg>fix viewer<commit_after>#include <GuiBase/Viewer/Viewer.hpp> #include <iostream> #include <QTimer> #include <QMouseEvent> #include <QPainter> #include <Core/String/StringUtils.hpp> #include <Core/Log/Log.hpp> #include <Core/Math/ColorPresets.hpp> #include <Core/Math/Math.hpp> #include <Core/Containers/MakeShared.hpp> #include <Core/Image/stb_image_write.h> #include <Engine/Renderer/OpenGL/OpenGL.hpp> #include <Engine/Component/Component.hpp> #include <Engine/Renderer/Renderer.hpp> #include <Engine/Renderer/Light/DirLight.hpp> #include <Engine/Renderer/Camera/Camera.hpp> #include <Engine/Renderer/Texture/Texture.hpp> #include <Engine/Managers/SystemDisplay/SystemDisplay.hpp> #include <Engine/Renderer/Renderers/ForwardRenderer.hpp> #include <GuiBase/Viewer/TrackballCamera.hpp> #include <GuiBase/Viewer/Gizmo/GizmoManager.hpp> #include <GuiBase/Utils/Keyboard.hpp> namespace Ra { Gui::Viewer::Viewer( QWidget* parent ) : QOpenGLWidget( parent ) , m_gizmoManager(new GizmoManager(this)) , m_renderThread( nullptr ) { // Allow Viewer to receive events setFocusPolicy( Qt::StrongFocus ); setMinimumSize( QSize( 800, 600 ) ); m_camera.reset( new Gui::TrackballCamera( width(), height() ) ); /// Intercept events to properly lock the renderer when it is compositing. } Gui::Viewer::~Viewer(){} void Gui::Viewer::initializeGL() { initializeOpenGLFunctions(); LOG( logINFO ) << "*** Radium Engine Viewer ***"; LOG( logINFO ) << "Renderer : " << glGetString( GL_RENDERER ); LOG( logINFO ) << "Vendor : " << glGetString( GL_VENDOR ); LOG( logINFO ) << "OpenGL : " << glGetString( GL_VERSION ); LOG( logINFO ) << "GLSL : " << glGetString( GL_SHADING_LANGUAGE_VERSION ); #if defined (OS_WINDOWS) glewExperimental = GL_TRUE; GLuint result = glewInit(); if ( result != GLEW_OK ) { std::string errorStr; Ra::Core::StringUtils::stringPrintf( errorStr, " GLEW init failed : %s", glewGetErrorString( result ) ); CORE_ERROR( errorStr.c_str() ); } else { LOG( logINFO ) << "GLEW : " << glewGetString( GLEW_VERSION ); glFlushError(); } #endif // FIXME(Charly): Renderer type should not be changed here m_renderers.resize( 1 ); // FIXME(Mathias): width and height might be wrong the first time ResizeGL is called (see QOpenGLWidget doc). This may cause problem on Retina display under MacOsX m_renderers[0].reset( new Engine::ForwardRenderer( width(), height() ) ); for ( auto& renderer : m_renderers ) { renderer->initialize(); } m_currentRenderer = m_renderers[0].get(); auto light = Ra::Core::make_shared<Engine::DirectionalLight>(); for ( auto& renderer : m_renderers ) { renderer->addLight( light ); } m_camera->attachLight( light ); emit rendererReady(); } Gui::CameraInterface* Gui::Viewer::getCameraInterface() { return m_camera.get(); } Gui::GizmoManager* Gui::Viewer::getGizmoManager() { return m_gizmoManager; } const Engine::Renderer* Gui::Viewer::getRenderer() const { return m_currentRenderer; } void Gui::Viewer::onAboutToCompose() { // This slot function is called from the main thread as part of the event loop // when the GUI is about to update. We have to wait for the rendering to finish. m_currentRenderer->lockRendering(); } void Gui::Viewer::onFrameSwapped() { // This slot is called from the main thread as part of the event loop when the // GUI has finished displaying the rendered image, so we unlock the renderer. m_currentRenderer->unlockRendering(); } void Gui::Viewer::onAboutToResize() { // Like swap buffers, resizing is a blocking operation and we have to wait for the rendering // to finish before resizing. m_currentRenderer->lockRendering(); } void Gui::Viewer::onResized() { m_currentRenderer->unlockRendering(); } void Gui::Viewer::resizeGL( int width, int height ) { // FIXME(Mathias) : Problem of glarea dimension on OsX Retina Display (half the size) // Renderer should have been locked by previous events. m_camera->resizeViewport( width, height ); m_currentRenderer->resize( width, height ); } void Gui::Viewer::mousePressEvent( QMouseEvent* event ) { switch ( event->button() ) { case Qt::LeftButton: { #ifdef OS_MACOS // (Mathias) no middle button on Apple (only left, right and wheel) // replace middle button by <ctrl>+left (note : ctrl = "command" // fake the subsistem by setting MiddleButtonEvent and masking ControlModifier if (event->modifiers().testFlag( Qt::ControlModifier ) ) { auto mods = event->modifiers(); mods^=Qt::ControlModifier; QMouseEvent macevent(event->type(), event->localPos(), event->windowPos(), event->screenPos(), Qt::MiddleButton, event->buttons(), mods, event->source() ); m_camera->handleMousePressEvent(&macevent); } #endif if ( isKeyPressed( Qt::Key_Space ) ) { LOG( logINFO ) << "Raycast query launched"; Core::Ray r = m_camera->getCamera()->getRayFromScreen(Core::Vector2(event->x(), event->y())); RA_DISPLAY_POINT(r.origin(), Core::Colors::Cyan(), 0.1f); RA_DISPLAY_RAY(r, Core::Colors::Yellow()); auto ents = Engine::RadiumEngine::getInstance()->getEntityManager()->getEntities(); for (auto e : ents) { e->rayCastQuery(r); } } else { Engine::Renderer::PickingQuery query = { Core::Vector2(event->x(), height() - event->y()), Core::MouseButton::RA_MOUSE_LEFT_BUTTON }; m_currentRenderer->addPickingRequest(query); m_gizmoManager->handleMousePressEvent(event); } } break; case Qt::MiddleButton: { m_camera->handleMousePressEvent(event); } break; case Qt::RightButton: { // Check picking Engine::Renderer::PickingQuery query = { Core::Vector2(event->x(), height() - event->y()), Core::MouseButton::RA_MOUSE_RIGHT_BUTTON }; m_currentRenderer->addPickingRequest(query); } break; default: { } break; } } void Gui::Viewer::mouseReleaseEvent( QMouseEvent* event ) { m_camera->handleMouseReleaseEvent( event ); m_gizmoManager->handleMouseReleaseEvent(event); } void Gui::Viewer::mouseMoveEvent( QMouseEvent* event ) { m_camera->handleMouseMoveEvent( event ); m_gizmoManager->handleMouseMoveEvent(event); } void Gui::Viewer::wheelEvent( QWheelEvent* event ) { m_camera->handleWheelEvent(event); QOpenGLWidget::wheelEvent( event ); } void Gui::Viewer::keyPressEvent( QKeyEvent* event ) { keyPressed(event->key()); m_camera->handleKeyPressEvent( event ); QOpenGLWidget::keyPressEvent(event); } void Gui::Viewer::keyReleaseEvent( QKeyEvent* event ) { keyReleased(event->key()); m_camera->handleKeyReleaseEvent( event ); if (event->key() == Qt::Key_Z && !event->isAutoRepeat()) { m_currentRenderer->toggleWireframe(); } QOpenGLWidget::keyReleaseEvent(event); } void Gui::Viewer::reloadShaders() { // FIXME : check thread-saefty of this. m_currentRenderer->lockRendering(); makeCurrent(); m_currentRenderer->reloadShaders(); doneCurrent(); m_currentRenderer->unlockRendering(); } void Gui::Viewer::displayTexture( const QString &tex ) { m_currentRenderer->lockRendering(); m_currentRenderer->displayTexture( tex.toStdString() ); m_currentRenderer->unlockRendering(); } void Gui::Viewer::changeRenderer( int index ) { // NOTE(Charly): This is probably buggy since it has not been tested. LOG( logWARNING ) << "Changing renderers might be buggy since it has not been tested."; m_currentRenderer->lockRendering(); m_currentRenderer = m_renderers[index].get(); m_currentRenderer->initialize(); m_currentRenderer->resize( width(), height() ); m_currentRenderer->unlockRendering(); } // Asynchronous rendering implementation void Gui::Viewer::startRendering( const Scalar dt ) { makeCurrent(); // Move camera if needed. Disabled for now as it takes too long (see issue #69) //m_camera->update( dt ); Engine::RenderData data; data.dt = dt; data.projMatrix = m_camera->getProjMatrix(); data.viewMatrix = m_camera->getViewMatrix(); m_currentRenderer->render( data ); } void Gui::Viewer::waitForRendering() { } void Gui::Viewer::handleFileLoading( const std::string& file ) { for ( auto& renderer : m_renderers ) { renderer->handleFileLoading( file ); } } void Gui::Viewer::processPicking() { CORE_ASSERT( m_currentRenderer->getPickingQueries().size() == m_currentRenderer->getPickingResults().size(), "There should be one result per query." ); for (uint i = 0 ; i < m_currentRenderer->getPickingQueries().size(); ++i) { const Engine::Renderer::PickingQuery& query = m_currentRenderer->getPickingQueries()[i]; if ( query.m_button == Core::MouseButton::RA_MOUSE_LEFT_BUTTON) { emit leftClickPicking(m_currentRenderer->getPickingResults()[i]); } else if (query.m_button == Core::MouseButton::RA_MOUSE_RIGHT_BUTTON) { emit rightClickPicking(m_currentRenderer->getPickingResults()[i]); } } } void Gui::Viewer::fitCameraToScene( const Core::Aabb& aabb ) { m_camera->fitScene( aabb ); } std::vector<std::string> Gui::Viewer::getRenderersName() const { std::vector<std::string> ret; for ( const auto& r : m_renderers ) { ret.push_back( r->getRendererName() ); } return ret; } void Gui::Viewer::grabFrame( const std::string& filename ) { makeCurrent(); Engine::Texture* tex = m_currentRenderer->getDisplayTexture(); tex->bind(); // Get a buffer to store the pixels of the OpenGL texture (in float format) float* pixels = new float[tex->width() * tex->height() * 4]; // Grab the texture data GL_ASSERT(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, pixels)); // Now we must convert the floats to RGB while flipping the image updisde down. uchar* writtenPixels = new uchar[tex->width() * tex->height() * 4]; for (uint j = 0; j < tex->height(); ++j) { for (uint i = 0; i < tex->width(); ++i) { uint in = 4 * (j * tex->width() + i); // Index in the texture buffer uint ou = 4 * ((tex->height() - 1 - j) * tex->width() + i); // Index in the final image (note the j flipping). writtenPixels[ou + 0] = (uchar)Ra::Core::Math::clamp<Scalar>(pixels[in + 0] * 255.f, 0, 255); writtenPixels[ou + 1] = (uchar)Ra::Core::Math::clamp<Scalar>(pixels[in + 1] * 255.f, 0, 255); writtenPixels[ou + 2] = (uchar)Ra::Core::Math::clamp<Scalar>(pixels[in + 2] * 255.f, 0, 255); writtenPixels[ou + 3] = 0xff; } } std::string ext = Core::StringUtils::getFileExt(filename); if (ext == "bmp") { stbi_write_bmp(filename.c_str(), tex->width(), tex->height(), 4, writtenPixels); } else if (ext == "png") { stbi_write_png(filename.c_str(), tex->width(), tex->height(), 4, writtenPixels, tex->width() * 4 * sizeof(uchar)); } else { LOG(logWARNING) << "Cannot write frame to "<<filename<<" : unsupported extension"; } delete[] pixels; delete[] writtenPixels; } void Gui::Viewer::enablePostProcess(int enabled) { m_currentRenderer->enablePostProcess(enabled); } void Gui::Viewer::enableDebugDraw(int enabled) { m_currentRenderer->enableDebugDraw(enabled); } } // namespace Ra <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "mediaobject.h" #include "mmf_medianode.h" QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; MMF::MediaNode::MediaNode(QObject *parent) : QObject::QObject(parent) , m_source(0) , m_target(0) , m_isApplied(false) { } bool MMF::MediaNode::connectMediaNode(MediaNode *target) { m_target = target; m_target->setSource(this); return applyNodesOnMediaObject(target); } bool MMF::MediaNode::disconnectMediaNode(MediaNode *target) { Q_UNUSED(target); m_target = 0; m_isApplied = false; return false; } void MMF::MediaNode::setSource(MediaNode *source) { m_source = source; } MMF::MediaNode *MMF::MediaNode::source() const { return m_source; } MMF::MediaNode *MMF::MediaNode::target() const { return m_target; } bool MMF::MediaNode::applyNodesOnMediaObject(MediaNode *) { // Algorithmically, this can be expressed in a more efficient way by // exercising available assumptions, but it complicates code for input // data(length of the graph) which typically is very small. // First, we go to the very beginning of the graph. MMF::MediaNode *current = this; do { MediaNode *const candidate = current->source(); if (candidate) current = candidate; else break; } while (current); // Now we do two things, while walking to the other end: // 1. Find the MediaObject, if present // 2. Collect a list of all unapplied MediaNodes QList<MediaNode *> unapplied; MMF::MediaObject *mo = 0; do { if (!current->m_isApplied) unapplied.append(current); if (!mo) mo = qobject_cast<MMF::MediaObject *>(current); current = current->target(); } while (current); // Now, lets activate all the objects, if we found the MediaObject. if (mo) { for (int i = 0; i < unapplied.count(); ++i) { MediaNode *const at = unapplied.at(i); // We don't want to apply MediaObject on itself. if (at != mo) at->activateOnMediaObject(mo); } } return true; } QT_END_NAMESPACE <commit_msg>Use correct return value.<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "mediaobject.h" #include "mmf_medianode.h" QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; MMF::MediaNode::MediaNode(QObject *parent) : QObject::QObject(parent) , m_source(0) , m_target(0) , m_isApplied(false) { } bool MMF::MediaNode::connectMediaNode(MediaNode *target) { m_target = target; m_target->setSource(this); return applyNodesOnMediaObject(target); } bool MMF::MediaNode::disconnectMediaNode(MediaNode *target) { Q_UNUSED(target); m_target = 0; m_isApplied = false; return true; } void MMF::MediaNode::setSource(MediaNode *source) { m_source = source; } MMF::MediaNode *MMF::MediaNode::source() const { return m_source; } MMF::MediaNode *MMF::MediaNode::target() const { return m_target; } bool MMF::MediaNode::applyNodesOnMediaObject(MediaNode *) { // Algorithmically, this can be expressed in a more efficient way by // exercising available assumptions, but it complicates code for input // data(length of the graph) which typically is very small. // First, we go to the very beginning of the graph. MMF::MediaNode *current = this; do { MediaNode *const candidate = current->source(); if (candidate) current = candidate; else break; } while (current); // Now we do two things, while walking to the other end: // 1. Find the MediaObject, if present // 2. Collect a list of all unapplied MediaNodes QList<MediaNode *> unapplied; MMF::MediaObject *mo = 0; do { if (!current->m_isApplied) unapplied.append(current); if (!mo) mo = qobject_cast<MMF::MediaObject *>(current); current = current->target(); } while (current); // Now, lets activate all the objects, if we found the MediaObject. if (mo) { for (int i = 0; i < unapplied.count(); ++i) { MediaNode *const at = unapplied.at(i); // We don't want to apply MediaObject on itself. if (at != mo) at->activateOnMediaObject(mo); } } return true; } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include <babylon/materialslibrary/gradient/gradient_material.h> #include <nlohmann/json.hpp> #include <babylon/buffers/vertex_buffer.h> #include <babylon/cameras/camera.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/effect.h> #include <babylon/materials/effect_fallbacks.h> #include <babylon/materials/ieffect_creation_options.h> #include <babylon/materials/image_processing_configuration.h> #include <babylon/materials/material_helper.h> #include <babylon/materialslibrary/gradient/gradient_fragment_fx.h> #include <babylon/materialslibrary/gradient/gradient_vertex_fx.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/sub_mesh.h> namespace BABYLON { namespace MaterialsLibrary { GradientMaterial::GradientMaterial(const std::string& iName, Scene* scene) : PushMaterial{iName, scene} , maxSimultaneousLights{this, &GradientMaterial::get_maxSimultaneousLights, &GradientMaterial::set_maxSimultaneousLights} , topColor{Color3(1.f, 0.f, 0.f)} , topColorAlpha{1.f} , bottomColor{Color3(0.f, 0.f, 1.f)} , bottomColorAlpha{1.f} , offset{0} , scale{1.f} , smoothness{1.f} , disableLighting{this, &GradientMaterial::get_disableLighting, &GradientMaterial::set_disableLighting} , _maxSimultaneousLights{4} , _disableLighting{false} { // Vertex shader Effect::ShadersStore()["gradientVertexShader"] = gradientVertexShader; // Fragment shader Effect::ShadersStore()["gradientPixelShader"] = gradientPixelShader; } GradientMaterial::~GradientMaterial() = default; unsigned int GradientMaterial::get_maxSimultaneousLights() const { return _maxSimultaneousLights; } void GradientMaterial::set_maxSimultaneousLights(unsigned int value) { if (_maxSimultaneousLights != value) { _maxSimultaneousLights = value; _markAllSubMeshesAsLightsDirty(); } } bool GradientMaterial::get_disableLighting() const { return _disableLighting; } void GradientMaterial::set_disableLighting(bool value) { if (_disableLighting != value) { _disableLighting = value; _markAllSubMeshesAsLightsDirty(); } } bool GradientMaterial::needAlphaBlending() const { return (alpha < 1.f || topColorAlpha < 1.f || bottomColorAlpha < 1.f); } bool GradientMaterial::needAlphaTesting() const { return true; } BaseTexturePtr GradientMaterial::getAlphaTestTexture() { return nullptr; } bool GradientMaterial::isReadyForSubMesh(AbstractMesh* mesh, SubMesh* subMesh, bool useInstances) { if (isFrozen()) { if (subMesh->effect() && subMesh->effect()->_wasPreviouslyReady) { return true; } } if (!subMesh->_materialDefines) { subMesh->materialDefines = std::make_shared<GradientMaterialDefines>(); } auto definesPtr = std::static_pointer_cast<GradientMaterialDefines>(subMesh->_materialDefines); auto& defines = *definesPtr.get(); auto scene = getScene(); if (_isReadyForSubMesh(subMesh)) { return true; } auto engine = scene->getEngine(); MaterialHelper::PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances); MaterialHelper::PrepareDefinesForMisc(mesh, scene, false, pointsCloud(), fogEnabled(), _shouldTurnAlphaTestOn(mesh), defines); defines._needNormals = MaterialHelper::PrepareDefinesForLights( scene, mesh, defines, false, _maxSimultaneousLights, _disableLighting); defines.boolDef["EMISSIVE"] = _disableLighting; // Attribs MaterialHelper::PrepareDefinesForAttributes(mesh, defines, false, true); // Get correct effect if (defines.isDirty()) { defines.markAsProcessed(); scene->resetCachedMaterial(); // Fallbacks auto fallbacks = std::make_unique<EffectFallbacks>(); if (defines["FOG"]) { fallbacks->addFallback(1, "FOG"); } MaterialHelper::HandleFallbacksForShadows(defines, *fallbacks); if (defines.intDef["NUM_BONE_INFLUENCERS"] > 0) { fallbacks->addCPUSkinningFallback(0, mesh); } defines.boolDef["IMAGEPROCESSINGPOSTPROCESS"] = scene->imageProcessingConfiguration()->applyByPostProcess(); // Attributes std::vector<std::string> attribs{VertexBuffer::PositionKind}; if (defines["NORMAL"]) { attribs.emplace_back(VertexBuffer::NormalKind); } if (defines["UV1"]) { attribs.emplace_back(VertexBuffer::UVKind); } if (defines["UV2"]) { attribs.emplace_back(VertexBuffer::UV2Kind); } if (defines["VERTEXCOLOR"]) { attribs.emplace_back(VertexBuffer::ColorKind); } MaterialHelper::PrepareAttributesForBones(attribs, mesh, defines, *fallbacks); MaterialHelper::PrepareAttributesForInstances(attribs, defines); // Legacy browser patch const std::string shaderName{"gradient"}; auto join = defines.toString(); const std::vector<std::string> uniforms{ "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vFogInfos", "vFogColor", "pointSize", "mBones", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "topColor", "bottomColor", "offset", "smoothness", "scale"}; const std::vector<std::string> samplers{"diffuseSampler"}; const std::vector<std::string> uniformBuffers{}; IEffectCreationOptions options; options.attributes = std::move(attribs); options.uniformsNames = std::move(uniforms); options.uniformBuffersNames = std::move(uniformBuffers); options.samplers = std::move(samplers); options.materialDefines = &defines; options.defines = std::move(join); options.maxSimultaneousLights = 4; options.fallbacks = std::move(fallbacks); options.onCompiled = onCompiled; options.onError = onError; options.indexParameters = {{"maxSimultaneousLights", 4}}; MaterialHelper::PrepareUniformsAndSamplersList(options); subMesh->setEffect(scene->getEngine()->createEffect(shaderName, options, engine), definesPtr, _materialContext); } if (!subMesh->effect() || !subMesh->effect()->isReady()) { return false; } defines._renderId = scene->getRenderId(); subMesh->effect()->_wasPreviouslyReady = true; return true; } void GradientMaterial::bindForSubMesh(Matrix& world, Mesh* mesh, SubMesh* subMesh) { auto scene = getScene(); auto defines = static_cast<GradientMaterialDefines*>(subMesh->_materialDefines.get()); if (!defines) { return; } auto effect = subMesh->effect(); if (!effect) { return; } _activeEffect = effect; // Matrices bindOnlyWorldMatrix(world); _activeEffect->setMatrix("viewProjection", scene->getTransformMatrix()); // Bones MaterialHelper::BindBonesParameters(mesh, effect.get()); if (_mustRebind(scene, effect)) { // Clip plane MaterialHelper::BindClipPlane(effect, scene); // Point size if (pointsCloud()) { _activeEffect->setFloat("pointSize", pointSize); } scene->bindEyePosition(effect.get()); } if (scene->lightsEnabled() && !disableLighting) { MaterialHelper::BindLights(scene, mesh, _activeEffect.get(), *defines, maxSimultaneousLights); } // View if (scene->fogEnabled() && mesh->applyFog() && scene->fogMode() != Scene::FOGMODE_NONE) { _activeEffect->setMatrix("view", scene->getViewMatrix()); } // Fog MaterialHelper::BindFogParameters(scene, mesh, _activeEffect); _activeEffect->setColor4("topColor", topColor, topColorAlpha); _activeEffect->setColor4("bottomColor", bottomColor, bottomColorAlpha); _activeEffect->setFloat("offset", offset); _activeEffect->setFloat("scale", scale); _activeEffect->setFloat("smoothness", smoothness); _afterBind(mesh, _activeEffect); } std::vector<IAnimatablePtr> GradientMaterial::getAnimatables() { return std::vector<IAnimatablePtr>(); } void GradientMaterial::dispose(bool forceDisposeEffect, bool forceDisposeTextures, bool /*notBoundToMesh*/) { PushMaterial::dispose(forceDisposeEffect, forceDisposeTextures); } MaterialPtr GradientMaterial::clone(const std::string& /*name*/, bool /*cloneChildren*/) const { return nullptr; } json GradientMaterial::serialize() const { return nullptr; } std::string GradientMaterial::getClassName() const { return "GradientMaterial"; } GradientMaterial* GradientMaterial::Parse(const json& /*source*/, Scene* /*scene*/, const std::string& /*rootUrl*/) { return nullptr; } } // end of namespace MaterialsLibrary } // end of namespace BABYLON <commit_msg>const correctness<commit_after>#include <babylon/materialslibrary/gradient/gradient_material.h> #include <nlohmann/json.hpp> #include <babylon/buffers/vertex_buffer.h> #include <babylon/cameras/camera.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/effect.h> #include <babylon/materials/effect_fallbacks.h> #include <babylon/materials/ieffect_creation_options.h> #include <babylon/materials/image_processing_configuration.h> #include <babylon/materials/material_helper.h> #include <babylon/materialslibrary/gradient/gradient_fragment_fx.h> #include <babylon/materialslibrary/gradient/gradient_vertex_fx.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/sub_mesh.h> namespace BABYLON { namespace MaterialsLibrary { GradientMaterial::GradientMaterial(const std::string& iName, Scene* scene) : PushMaterial{iName, scene} , maxSimultaneousLights{this, &GradientMaterial::get_maxSimultaneousLights, &GradientMaterial::set_maxSimultaneousLights} , topColor{Color3(1.f, 0.f, 0.f)} , topColorAlpha{1.f} , bottomColor{Color3(0.f, 0.f, 1.f)} , bottomColorAlpha{1.f} , offset{0} , scale{1.f} , smoothness{1.f} , disableLighting{this, &GradientMaterial::get_disableLighting, &GradientMaterial::set_disableLighting} , _maxSimultaneousLights{4} , _disableLighting{false} { // Vertex shader Effect::ShadersStore()["gradientVertexShader"] = gradientVertexShader; // Fragment shader Effect::ShadersStore()["gradientPixelShader"] = gradientPixelShader; } GradientMaterial::~GradientMaterial() = default; unsigned int GradientMaterial::get_maxSimultaneousLights() const { return _maxSimultaneousLights; } void GradientMaterial::set_maxSimultaneousLights(unsigned int value) { if (_maxSimultaneousLights != value) { _maxSimultaneousLights = value; _markAllSubMeshesAsLightsDirty(); } } bool GradientMaterial::get_disableLighting() const { return _disableLighting; } void GradientMaterial::set_disableLighting(bool value) { if (_disableLighting != value) { _disableLighting = value; _markAllSubMeshesAsLightsDirty(); } } bool GradientMaterial::needAlphaBlending() const { return (alpha < 1.f || topColorAlpha < 1.f || bottomColorAlpha < 1.f); } bool GradientMaterial::needAlphaTesting() const { return true; } BaseTexturePtr GradientMaterial::getAlphaTestTexture() { return nullptr; } bool GradientMaterial::isReadyForSubMesh(AbstractMesh* mesh, SubMesh* subMesh, bool useInstances) { if (isFrozen()) { if (subMesh->effect() && subMesh->effect()->_wasPreviouslyReady) { return true; } } if (!subMesh->_materialDefines) { subMesh->materialDefines = std::make_shared<GradientMaterialDefines>(); } auto definesPtr = std::static_pointer_cast<GradientMaterialDefines>(subMesh->_materialDefines); auto& defines = *definesPtr.get(); const auto scene = getScene(); if (_isReadyForSubMesh(subMesh)) { return true; } const auto engine = scene->getEngine(); MaterialHelper::PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances); MaterialHelper::PrepareDefinesForMisc(mesh, scene, false, pointsCloud(), fogEnabled(), _shouldTurnAlphaTestOn(mesh), defines); defines._needNormals = MaterialHelper::PrepareDefinesForLights( scene, mesh, defines, false, _maxSimultaneousLights, _disableLighting); defines.boolDef["EMISSIVE"] = _disableLighting; // Attribs MaterialHelper::PrepareDefinesForAttributes(mesh, defines, false, true); // Get correct effect if (defines.isDirty()) { defines.markAsProcessed(); scene->resetCachedMaterial(); // Fallbacks auto fallbacks = std::make_unique<EffectFallbacks>(); if (defines["FOG"]) { fallbacks->addFallback(1, "FOG"); } MaterialHelper::HandleFallbacksForShadows(defines, *fallbacks); if (defines.intDef["NUM_BONE_INFLUENCERS"] > 0) { fallbacks->addCPUSkinningFallback(0, mesh); } defines.boolDef["IMAGEPROCESSINGPOSTPROCESS"] = scene->imageProcessingConfiguration()->applyByPostProcess(); // Attributes std::vector<std::string> attribs{VertexBuffer::PositionKind}; if (defines["NORMAL"]) { attribs.emplace_back(VertexBuffer::NormalKind); } if (defines["UV1"]) { attribs.emplace_back(VertexBuffer::UVKind); } if (defines["UV2"]) { attribs.emplace_back(VertexBuffer::UV2Kind); } if (defines["VERTEXCOLOR"]) { attribs.emplace_back(VertexBuffer::ColorKind); } MaterialHelper::PrepareAttributesForBones(attribs, mesh, defines, *fallbacks); MaterialHelper::PrepareAttributesForInstances(attribs, defines); // Legacy browser patch const std::string shaderName{"gradient"}; auto join = defines.toString(); const std::vector<std::string> uniforms{ "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vFogInfos", "vFogColor", "pointSize", "mBones", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "topColor", "bottomColor", "offset", "smoothness", "scale"}; const std::vector<std::string> samplers{"diffuseSampler"}; const std::vector<std::string> uniformBuffers{}; IEffectCreationOptions options; options.attributes = std::move(attribs); options.uniformsNames = std::move(uniforms); options.uniformBuffersNames = std::move(uniformBuffers); options.samplers = std::move(samplers); options.materialDefines = &defines; options.defines = std::move(join); options.maxSimultaneousLights = 4; options.fallbacks = std::move(fallbacks); options.onCompiled = onCompiled; options.onError = onError; options.indexParameters = {{"maxSimultaneousLights", 4}}; MaterialHelper::PrepareUniformsAndSamplersList(options); subMesh->setEffect(scene->getEngine()->createEffect(shaderName, options, engine), definesPtr, _materialContext); } if (!subMesh->effect() || !subMesh->effect()->isReady()) { return false; } defines._renderId = scene->getRenderId(); subMesh->effect()->_wasPreviouslyReady = true; return true; } void GradientMaterial::bindForSubMesh(Matrix& world, Mesh* mesh, SubMesh* subMesh) { const auto scene = getScene(); auto defines = static_cast<GradientMaterialDefines*>(subMesh->_materialDefines.get()); if (!defines) { return; } const auto effect = subMesh->effect(); if (!effect) { return; } _activeEffect = effect; // Matrices bindOnlyWorldMatrix(world); _activeEffect->setMatrix("viewProjection", scene->getTransformMatrix()); // Bones MaterialHelper::BindBonesParameters(mesh, effect.get()); if (_mustRebind(scene, effect)) { // Clip plane MaterialHelper::BindClipPlane(effect, scene); // Point size if (pointsCloud()) { _activeEffect->setFloat("pointSize", pointSize); } scene->bindEyePosition(effect.get()); } if (scene->lightsEnabled() && !disableLighting) { MaterialHelper::BindLights(scene, mesh, _activeEffect.get(), *defines, maxSimultaneousLights); } // View if (scene->fogEnabled() && mesh->applyFog() && scene->fogMode() != Scene::FOGMODE_NONE) { _activeEffect->setMatrix("view", scene->getViewMatrix()); } // Fog MaterialHelper::BindFogParameters(scene, mesh, _activeEffect); _activeEffect->setColor4("topColor", topColor, topColorAlpha); _activeEffect->setColor4("bottomColor", bottomColor, bottomColorAlpha); _activeEffect->setFloat("offset", offset); _activeEffect->setFloat("scale", scale); _activeEffect->setFloat("smoothness", smoothness); _afterBind(mesh, _activeEffect); } std::vector<IAnimatablePtr> GradientMaterial::getAnimatables() { return std::vector<IAnimatablePtr>(); } void GradientMaterial::dispose(bool forceDisposeEffect, bool forceDisposeTextures, bool /*notBoundToMesh*/) { PushMaterial::dispose(forceDisposeEffect, forceDisposeTextures); } MaterialPtr GradientMaterial::clone(const std::string& /*name*/, bool /*cloneChildren*/) const { return nullptr; } json GradientMaterial::serialize() const { return nullptr; } std::string GradientMaterial::getClassName() const { return "GradientMaterial"; } GradientMaterial* GradientMaterial::Parse(const json& /*source*/, Scene* /*scene*/, const std::string& /*rootUrl*/) { return nullptr; } } // end of namespace MaterialsLibrary } // end of namespace BABYLON <|endoftext|>
<commit_before>// TODO(ralntdir): // Think how to clean SDL if the programs ends with some crash // Finished the program if there is a problem at SDL/IMG init or // when creating the window or the renderer #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> // TODO(ralntdir): read this from a scene file? #define WIDTH 400 #define HEIGHT 200 #define MAX_COLOR 255 int main(int argc, char* argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *surface; SDL_Texture *texture; // Init SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Error in SDL_Init(): " << SDL_GetError() << "\n"; } // Init SDL_Image if (IMG_Init(0) < 0) { std::cout << "Error in IMG_Init(): " << IMG_GetError() << "\n"; } // Create a Window // NOTE(ralntdir): SDL_WINDOW_SHOWN is ignored by SDL_CreateWindow(). // The SDL_Window is implicitly shown if SDL_WINDOW_HIDDEN is not set. window = SDL_CreateWindow("Devember RT", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (window == 0) { std::cout << "Error in SDL_CreateWindow(): " << SDL_GetError() << "\n"; } // Create a Renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == 0) { std::cout << "Error in SDL_CreateRenderer(): " << SDL_GetError() << "\n"; } // Create a .ppm file std::cout << "P3\n"; std::cout << "# image.ppm\n"; std::cout << WIDTH << " " << HEIGHT << "\n"; std::cout << MAX_COLOR << "\n"; // NOTE(ralntdir): From top to bottom for (int i = HEIGHT; i > 0 ; i--) { for (int j = 0; j < WIDTH; j++) { int r = 0; int g = (255.00*i/HEIGHT); int b = (255.00*j/WIDTH); std::cout << r << " " << g << " " << b << "\n"; } } // Load the image // TODO(ralntdir): right now I'm loading the image from the previous // execution!!!! Change this!!!!! surface = IMG_Load("image.ppm"); if (surface == 0) { std::cout << "Error in IMG_Load(): " << IMG_GetError() << "\n"; } texture = SDL_CreateTextureFromSurface(renderer, surface); if (texture == 0) { std::cout << "Error in SDL_CreateTextureFromSurface(): " << SDL_GetError() << "\n"; } SDL_FreeSurface(surface); // Show the texture SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); SDL_Delay(5000); // Free the texture SDL_DestroyTexture(texture); // Quit IMG IMG_Quit(); // Quit SDL SDL_Quit(); return(0); } <commit_msg>Create and save the image and then load it and show it in the SDL window<commit_after>// TODO(ralntdir): // Think how to clean SDL if the programs ends with some crash // Finished the program if there is a problem at SDL/IMG init or // when creating the window or the renderer // // Features to add: // sphere "class" // ray "class" // ray->sphere intersection #include <iostream> #include <fstream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> // TODO(ralntdir): read this from a scene file? #define WIDTH 400 #define HEIGHT 200 #define MAX_COLOR 255 int main(int argc, char* argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *surface; SDL_Texture *texture; // Init SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Error in SDL_Init(): " << SDL_GetError() << "\n"; } // Init SDL_Image if (IMG_Init(0) < 0) { std::cout << "Error in IMG_Init(): " << IMG_GetError() << "\n"; } // Create a Window // NOTE(ralntdir): SDL_WINDOW_SHOWN is ignored by SDL_CreateWindow(). // The SDL_Window is implicitly shown if SDL_WINDOW_HIDDEN is not set. window = SDL_CreateWindow("Devember RT", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (window == 0) { std::cout << "Error in SDL_CreateWindow(): " << SDL_GetError() << "\n"; } // Create a Renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == 0) { std::cout << "Error in SDL_CreateRenderer(): " << SDL_GetError() << "\n"; } // Create a .ppm file std::ofstream ofs("image.ppm", std::ofstream::out | std::ofstream::binary); ofs << "P3\n"; ofs << "# image.ppm\n"; ofs << WIDTH << " " << HEIGHT << "\n"; ofs << MAX_COLOR << "\n"; // NOTE(ralntdir): From top to bottom for (int i = HEIGHT; i > 0 ; i--) { for (int j = 0; j < WIDTH; j++) { int g = 0; int r = (255.00*i/HEIGHT); int b = (255.00*j/WIDTH); ofs << r << " " << g << " " << b << "\n"; } } ofs.close(); // Load the image // TODO(ralntdir): right now I'm loading the image from the previous // execution!!!! Change this!!!!! surface = IMG_Load("image.ppm"); if (surface == 0) { std::cout << "Error in IMG_Load(): " << IMG_GetError() << "\n"; } texture = SDL_CreateTextureFromSurface(renderer, surface); if (texture == 0) { std::cout << "Error in SDL_CreateTextureFromSurface(): " << SDL_GetError() << "\n"; } SDL_FreeSurface(surface); // Show the texture SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); SDL_Delay(5000); // Free the texture SDL_DestroyTexture(texture); // Quit IMG IMG_Quit(); // Quit SDL SDL_Quit(); return(0); } <|endoftext|>
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SelectFirstResultSearchService.h" #include "SearchQueryPerformer.h" #include "InteriorInteractionModel.h" #include "IMenuOption.h" #include "SearchResultModel.h" #include "ISearchResultRepository.h" #include "IMenuModel.h" namespace ExampleApp { namespace Search { namespace SelectFirstResult { namespace SdkModel { SelectFirstResultSearchService::SelectFirstResultSearchService(Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Menu::View::IMenuSectionViewModel& searchSectionViewModel, Search::SdkModel::ISearchResultRepository& searchResultRepository) : m_searchQueryPerformer(searchQueryPerformer) , m_searchResultRepository(searchResultRepository) , m_searchSectionViewModel(searchSectionViewModel) , m_searchResultAddedCallback(this, &SelectFirstResultSearchService::OnSearchResultAdded) , m_didTransition(false) { m_searchResultRepository.InsertItemAddedCallback(m_searchResultAddedCallback); } SelectFirstResultSearchService::~SelectFirstResultSearchService() { m_searchResultRepository.RemoveItemAddedCallback(m_searchResultAddedCallback); } void SelectFirstResultSearchService::HandleSearch(std::string& queryString, const std::string& interiorId) { m_searchQueryPerformer.RemoveSearchQueryResults(); m_searchQueryPerformer.PerformSearchQuery(queryString.c_str(), false, true, interiorId); m_didTransition = false; } void SelectFirstResultSearchService::OnSearchResultAdded(Search::SdkModel::SearchResultModel*& pSearchResultModel) { if(!m_didTransition) { if(m_searchSectionViewModel.Size() > 0) { m_searchSectionViewModel.GetItemAtIndex(0).MenuOption().Select(); m_didTransition = true; } } } } } } } <commit_msg>Fixed a bug with searchfirstresultsearchservice It no longer transition to the first result on a normal search in example app. Buddy: Sam A<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SelectFirstResultSearchService.h" #include "SearchQueryPerformer.h" #include "InteriorInteractionModel.h" #include "IMenuOption.h" #include "SearchResultModel.h" #include "ISearchResultRepository.h" #include "IMenuModel.h" namespace ExampleApp { namespace Search { namespace SelectFirstResult { namespace SdkModel { SelectFirstResultSearchService::SelectFirstResultSearchService(Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Menu::View::IMenuSectionViewModel& searchSectionViewModel, Search::SdkModel::ISearchResultRepository& searchResultRepository) : m_searchQueryPerformer(searchQueryPerformer) , m_searchResultRepository(searchResultRepository) , m_searchSectionViewModel(searchSectionViewModel) , m_searchResultAddedCallback(this, &SelectFirstResultSearchService::OnSearchResultAdded) , m_didTransition(true) { m_searchResultRepository.InsertItemAddedCallback(m_searchResultAddedCallback); } SelectFirstResultSearchService::~SelectFirstResultSearchService() { m_searchResultRepository.RemoveItemAddedCallback(m_searchResultAddedCallback); } void SelectFirstResultSearchService::HandleSearch(std::string& queryString, const std::string& interiorId) { m_searchQueryPerformer.RemoveSearchQueryResults(); m_searchQueryPerformer.PerformSearchQuery(queryString.c_str(), false, true, interiorId); m_didTransition = false; } void SelectFirstResultSearchService::OnSearchResultAdded(Search::SdkModel::SearchResultModel*& pSearchResultModel) { if(!m_didTransition) { if(m_searchSectionViewModel.Size() > 0) { m_searchSectionViewModel.GetItemAtIndex(0).MenuOption().Select(); m_didTransition = true; } } } } } } } <|endoftext|>
<commit_before>/* ** Copyright (C) 2012, 2013 Aldebaran Robotics ** See COPYING for the license */ #include <qi/type/detail/staticobjecttype.hpp> #include <qi/anyobject.hpp> #include <qi/signal.hpp> #include <qi/property.hpp> #include <qi/jsoncodec.hpp> #include <qi/strand.hpp> qiLogCategory("qitype.object"); namespace qi { namespace detail { void StaticObjectTypeBase::initialize(const MetaObject& mo, const ObjectTypeData& data) { _metaObject = mo; _data = data; } ObjectUid StaticObjectTypeBase::uid(void* instance) const { QI_ASSERT_TRUE(instance); return os::ptrUid(instance); } const MetaObject& StaticObjectTypeBase::metaObject(void* ) { return _metaObject; } namespace { template <typename T> void noopDeleter(T* obj) {} } qi::Future<AnyReference> StaticObjectTypeBase::metaCall(void* instance, AnyObject context, unsigned int methodId, const GenericFunctionParameters& params, MetaCallType callType, Signature returnSignature) { ObjectTypeData::MethodMap::iterator i; i = _data.methodMap.find(methodId); if (i == _data.methodMap.end()) { return qi::makeFutureError<AnyReference>("No such method"); } if (returnSignature.isValid()) { const MetaMethod *mm = metaObject(instance).method(methodId); if (!mm) return makeFutureError<AnyReference>("Unexpected error: MetaMethod not found"); if (mm->returnSignature().isConvertibleTo(returnSignature) == 0) { if (returnSignature.isConvertibleTo(mm->returnSignature())==0) return makeFutureError<AnyReference>( "Call error: will not be able to convert return type from " + mm->returnSignature().toString() + " to " + returnSignature.toString()); else qiLogWarning() << "Return signature might be incorrect depending on the value, from " + mm->returnSignature().toString() + " to " + returnSignature.toString(); } } MetaCallType methodThreadingModel = i->second.second; ExecutionContext* ec = getExecutionContext(instance, context, methodThreadingModel); AnyFunction method = i->second.first; AnyReference self; if (methodId >= Manageable::startId && methodId < Manageable::endId) { self = AnyReference(qi::typeOf<Manageable>(), static_cast<Manageable*>(context.asGenericObject())); } else { self = AnyReference(this, instance); } GenericFunctionParameters p2; p2.reserve(params.size()+1); p2.push_back(self); p2.insert(p2.end(), params.begin(), params.end()); return ::qi::metaCall(ec, _data.threadingModel, methodThreadingModel, callType, context, methodId, method, p2, true); } ExecutionContext* StaticObjectTypeBase::getExecutionContext( void* instance, qi::AnyObject context, MetaCallType methodThreadingModel) { ExecutionContext* ec = context.executionContext(); if (_data.threadingModel == ObjectThreadingModel_SingleThread) { // execute queued methods on global eventloop if they are of queued type if (methodThreadingModel == MetaCallType_Queued) ec = 0; else if (!ec) { boost::shared_ptr<Manageable> manageable = context.managedObjectPtr(); boost::mutex::scoped_lock l(manageable->initMutex()); if (!manageable->executionContext()) { if (_data.strandAccessor) manageable->forceExecutionContext(boost::shared_ptr<qi::Strand>( _data.strandAccessor.call<qi::Strand*>(instance), &noopDeleter<qi::Strand>)); else manageable->forceExecutionContext(boost::shared_ptr<qi::Strand>( new qi::Strand(*::qi::getEventLoop()))); } ec = context.executionContext(); } } return ec; } static PropertyBase* property(ObjectTypeData& data, void* instance, unsigned int signal) { ObjectTypeData::PropertyGetterMap::iterator i; i = data.propertyGetterMap.find(signal); if (i == data.propertyGetterMap.end()) return nullptr; PropertyBase* sig = i->second(instance); if (!sig) { qiLogError() << "Property getter returned NULL"; return nullptr; } return sig; } static SignalBase* getSignal(ObjectTypeData& data, void* instance, unsigned int signal) { ObjectTypeData::SignalGetterMap::iterator i; i = data.signalGetterMap.find(signal); if (i == data.signalGetterMap.end()) { PropertyBase* prop = property(data, instance, signal); if (prop) return prop->signal(); return nullptr; } SignalBase* sig = i->second(instance); if (!sig) { qiLogError() << "Signal getter returned NULL"; return nullptr; } return sig; } static void reportError(qi::Future<AnyReference> fut) { if (fut.hasError()) { qiLogWarning() << "metaPost failed: " << fut.error(); return; } qi::AnyReference ref = fut.value(); ref.destroy(); } void StaticObjectTypeBase::metaPost(void* instance, AnyObject context, unsigned int signal, const GenericFunctionParameters& params) { if (SignalBase* sb = getSignal(_data, instance, signal)) { sb->trigger(params); } else if (_data.methodMap.find(signal) != _data.methodMap.end()) { // try method qi::Future<AnyReference> fut = metaCall(instance, context, signal, params, MetaCallType_Queued, Signature()); fut.connect(&reportError); } else { qiLogWarning() << "post: no such signal or method " << signal; return; } } qi::Future<SignalLink> StaticObjectTypeBase::connect(void* instance, AnyObject context, unsigned int event, const SignalSubscriber& subscriber) { if (event >= Manageable::startId && event < Manageable::endId) instance = static_cast<Manageable*>(context.asGenericObject()); SignalBase* sb = getSignal(_data, instance, event); if (!sb) { qiLogWarning() << "connect: no such signal: " << event; return qi::makeFutureError<SignalLink>("Cant find signal"); } SignalLink id = sb->connect(subscriber); if (id == SignalBase::invalidSignalLink) return qi::Future<SignalLink>(id); SignalLink link = ((SignalLink)event << 32) + id; QI_ASSERT(link >> 32 == event); QI_ASSERT((link & 0xFFFFFFFF) == id); qiLogDebug() << "Connect " << event <<' ' << id << ' ' << link; return qi::Future<SignalLink>(link); } qi::Future<void> StaticObjectTypeBase::disconnect(void* instance, AnyObject context, SignalLink linkId) { qiLogDebug() << "Disconnect " << linkId; unsigned int event = linkId >> 32; unsigned int link = linkId & 0xFFFFFFFF; if (event >= Manageable::startId && event < Manageable::endId) instance = static_cast<Manageable*>(context.asGenericObject()); SignalBase* sb = getSignal(_data, instance, event); if (!sb) { qiLogWarning() << "disconnect: no such signal: " << event; return qi::makeFutureError<void>("Cant find signal"); } return sb->disconnectAsync(link).andThen([](bool successful) { if (!successful) throw std::runtime_error("signal registration failed"); }); } qi::Future<AnyValue> StaticObjectTypeBase::property(void* instance, AnyObject context, unsigned int id) { PropertyBase* p = ::qi::detail::property(_data, instance, id); if (!p) { qiLogWarning() << "property: no such property: " << id; return qi::makeFutureError<AnyValue>("Cant find property"); } ExecutionContext* ec = getExecutionContext(instance, context); if (ec) return ec->async([p]{ return p->value().async(); }).unwrap(); else return p->value(); } static void setPropertyValue(PropertyBase* property, AnyValue value) { property->setValue(value.asReference()); } qi::Future<void> StaticObjectTypeBase::setProperty(void* instance, AnyObject context, unsigned int id, AnyValue value) { PropertyBase* p = ::qi::detail::property(_data, instance, id); if (!p) { qiLogWarning() << "setProperty: no such property: " << id; return qi::makeFutureError<void>("Cant find property"); } qiLogDebug() << "SetProperty " << id << " " << encodeJSON(value); ExecutionContext* ec = getExecutionContext(instance, context); if (ec) return ec->async(boost::bind(&setPropertyValue, p, value)); else { try { p->setValue(value.asReference()); } catch(const std::exception& e) { return qi::makeFutureError<void>(std::string("setProperty: ") + e.what()); } return qi::Future<void>(0); } } const std::vector<std::pair<TypeInterface*, std::ptrdiff_t> >& StaticObjectTypeBase::parentTypes() { return _data.parentTypes; } const TypeInfo& StaticObjectTypeBase::info() { return _data.classType->info(); } void* StaticObjectTypeBase::initializeStorage(void* ptr) { return _data.classType->initializeStorage(ptr); } void* StaticObjectTypeBase::ptrFromStorage(void** ptr) { return _data.classType->ptrFromStorage(ptr); } void* StaticObjectTypeBase::clone(void* inst) { return _data.classType->clone(inst); } void StaticObjectTypeBase::destroy(void* inst) { _data.classType->destroy(inst); } bool StaticObjectTypeBase::less(void* a, void* b) { return a<b; } } } <commit_msg>qi.type: Removes wait in `StaticObjectTypeBase::setProperty`.<commit_after>/* ** Copyright (C) 2012, 2013 Aldebaran Robotics ** See COPYING for the license */ #include <qi/type/detail/staticobjecttype.hpp> #include <qi/anyobject.hpp> #include <qi/signal.hpp> #include <qi/property.hpp> #include <qi/jsoncodec.hpp> #include <qi/strand.hpp> qiLogCategory("qitype.object"); namespace qi { namespace detail { void StaticObjectTypeBase::initialize(const MetaObject& mo, const ObjectTypeData& data) { _metaObject = mo; _data = data; } ObjectUid StaticObjectTypeBase::uid(void* instance) const { QI_ASSERT_TRUE(instance); return os::ptrUid(instance); } const MetaObject& StaticObjectTypeBase::metaObject(void* ) { return _metaObject; } namespace { template <typename T> void noopDeleter(T* obj) {} } qi::Future<AnyReference> StaticObjectTypeBase::metaCall(void* instance, AnyObject context, unsigned int methodId, const GenericFunctionParameters& params, MetaCallType callType, Signature returnSignature) { ObjectTypeData::MethodMap::iterator i; i = _data.methodMap.find(methodId); if (i == _data.methodMap.end()) { return qi::makeFutureError<AnyReference>("No such method"); } if (returnSignature.isValid()) { const MetaMethod *mm = metaObject(instance).method(methodId); if (!mm) return makeFutureError<AnyReference>("Unexpected error: MetaMethod not found"); if (mm->returnSignature().isConvertibleTo(returnSignature) == 0) { if (returnSignature.isConvertibleTo(mm->returnSignature())==0) return makeFutureError<AnyReference>( "Call error: will not be able to convert return type from " + mm->returnSignature().toString() + " to " + returnSignature.toString()); else qiLogWarning() << "Return signature might be incorrect depending on the value, from " + mm->returnSignature().toString() + " to " + returnSignature.toString(); } } MetaCallType methodThreadingModel = i->second.second; ExecutionContext* ec = getExecutionContext(instance, context, methodThreadingModel); AnyFunction method = i->second.first; AnyReference self; if (methodId >= Manageable::startId && methodId < Manageable::endId) { self = AnyReference(qi::typeOf<Manageable>(), static_cast<Manageable*>(context.asGenericObject())); } else { self = AnyReference(this, instance); } GenericFunctionParameters p2; p2.reserve(params.size()+1); p2.push_back(self); p2.insert(p2.end(), params.begin(), params.end()); return ::qi::metaCall(ec, _data.threadingModel, methodThreadingModel, callType, context, methodId, method, p2, true); } ExecutionContext* StaticObjectTypeBase::getExecutionContext( void* instance, qi::AnyObject context, MetaCallType methodThreadingModel) { ExecutionContext* ec = context.executionContext(); if (_data.threadingModel == ObjectThreadingModel_SingleThread) { // execute queued methods on global eventloop if they are of queued type if (methodThreadingModel == MetaCallType_Queued) ec = 0; else if (!ec) { boost::shared_ptr<Manageable> manageable = context.managedObjectPtr(); boost::mutex::scoped_lock l(manageable->initMutex()); if (!manageable->executionContext()) { if (_data.strandAccessor) manageable->forceExecutionContext(boost::shared_ptr<qi::Strand>( _data.strandAccessor.call<qi::Strand*>(instance), &noopDeleter<qi::Strand>)); else manageable->forceExecutionContext(boost::shared_ptr<qi::Strand>( new qi::Strand(*::qi::getEventLoop()))); } ec = context.executionContext(); } } return ec; } static PropertyBase* property(ObjectTypeData& data, void* instance, unsigned int signal) { ObjectTypeData::PropertyGetterMap::iterator i; i = data.propertyGetterMap.find(signal); if (i == data.propertyGetterMap.end()) return nullptr; PropertyBase* sig = i->second(instance); if (!sig) { qiLogError() << "Property getter returned NULL"; return nullptr; } return sig; } static SignalBase* getSignal(ObjectTypeData& data, void* instance, unsigned int signal) { ObjectTypeData::SignalGetterMap::iterator i; i = data.signalGetterMap.find(signal); if (i == data.signalGetterMap.end()) { PropertyBase* prop = property(data, instance, signal); if (prop) return prop->signal(); return nullptr; } SignalBase* sig = i->second(instance); if (!sig) { qiLogError() << "Signal getter returned NULL"; return nullptr; } return sig; } static void reportError(qi::Future<AnyReference> fut) { if (fut.hasError()) { qiLogWarning() << "metaPost failed: " << fut.error(); return; } qi::AnyReference ref = fut.value(); ref.destroy(); } void StaticObjectTypeBase::metaPost(void* instance, AnyObject context, unsigned int signal, const GenericFunctionParameters& params) { if (SignalBase* sb = getSignal(_data, instance, signal)) { sb->trigger(params); } else if (_data.methodMap.find(signal) != _data.methodMap.end()) { // try method qi::Future<AnyReference> fut = metaCall(instance, context, signal, params, MetaCallType_Queued, Signature()); fut.connect(&reportError); } else { qiLogWarning() << "post: no such signal or method " << signal; return; } } qi::Future<SignalLink> StaticObjectTypeBase::connect(void* instance, AnyObject context, unsigned int event, const SignalSubscriber& subscriber) { if (event >= Manageable::startId && event < Manageable::endId) instance = static_cast<Manageable*>(context.asGenericObject()); SignalBase* sb = getSignal(_data, instance, event); if (!sb) { qiLogWarning() << "connect: no such signal: " << event; return qi::makeFutureError<SignalLink>("Cant find signal"); } SignalLink id = sb->connect(subscriber); if (id == SignalBase::invalidSignalLink) return qi::Future<SignalLink>(id); SignalLink link = ((SignalLink)event << 32) + id; QI_ASSERT(link >> 32 == event); QI_ASSERT((link & 0xFFFFFFFF) == id); qiLogDebug() << "Connect " << event <<' ' << id << ' ' << link; return qi::Future<SignalLink>(link); } qi::Future<void> StaticObjectTypeBase::disconnect(void* instance, AnyObject context, SignalLink linkId) { qiLogDebug() << "Disconnect " << linkId; unsigned int event = linkId >> 32; unsigned int link = linkId & 0xFFFFFFFF; if (event >= Manageable::startId && event < Manageable::endId) instance = static_cast<Manageable*>(context.asGenericObject()); SignalBase* sb = getSignal(_data, instance, event); if (!sb) { qiLogWarning() << "disconnect: no such signal: " << event; return qi::makeFutureError<void>("Cant find signal"); } return sb->disconnectAsync(link).andThen([](bool successful) { if (!successful) throw std::runtime_error("signal registration failed"); }); } qi::Future<AnyValue> StaticObjectTypeBase::property(void* instance, AnyObject context, unsigned int id) { PropertyBase* p = ::qi::detail::property(_data, instance, id); if (!p) { qiLogWarning() << "property: no such property: " << id; return qi::makeFutureError<AnyValue>("Cant find property"); } ExecutionContext* ec = getExecutionContext(instance, context); if (ec) return ec->async([p]{ return p->value().async(); }).unwrap(); else return p->value(); } static void setPropertyValue(PropertyBase* property, AnyValue value) { property->setValue(value.asReference()); } qi::Future<void> StaticObjectTypeBase::setProperty(void* instance, AnyObject context, unsigned int id, AnyValue value) { PropertyBase* p = ::qi::detail::property(_data, instance, id); if (!p) { qiLogWarning() << "setProperty: no such property: " << id; return qi::makeFutureError<void>("Cant find property"); } qiLogDebug() << "SetProperty " << id << " " << encodeJSON(value); ExecutionContext* ec = getExecutionContext(instance, context); if (ec) return ec->async(boost::bind(&setPropertyValue, p, value)); else { const auto asyncSetValue = [&]{ return p->setValue(value.asReference()).async(); }; const auto formatError = [&](const std::string& err) { return str(boost::format("Failed to set object property '%1%', reason: %2%") % id % err); }; return ka::invoke_catch(futureErrorFromException<void>(formatError), asyncSetValue); } } const std::vector<std::pair<TypeInterface*, std::ptrdiff_t> >& StaticObjectTypeBase::parentTypes() { return _data.parentTypes; } const TypeInfo& StaticObjectTypeBase::info() { return _data.classType->info(); } void* StaticObjectTypeBase::initializeStorage(void* ptr) { return _data.classType->initializeStorage(ptr); } void* StaticObjectTypeBase::ptrFromStorage(void** ptr) { return _data.classType->ptrFromStorage(ptr); } void* StaticObjectTypeBase::clone(void* inst) { return _data.classType->clone(inst); } void StaticObjectTypeBase::destroy(void* inst) { _data.classType->destroy(inst); } bool StaticObjectTypeBase::less(void* a, void* b) { return a<b; } } } <|endoftext|>
<commit_before>#ifndef BTREEINC #include <binarytree.h> #define BTREEINC #endif template <class T> BinaryTree<T>::BinaryTree() : root(nullptr), levels(0) {} template <class T> BinaryTree<T>::~BinaryTree() { delete root; } template <class T> unsigned int BinaryTree<T>::Levels() const { return levels; } template <class T> void BinaryTree<T>::Add(T i) { levels++; if (root == nullptr) { root = NewNode<T>(i); return; } if (root->Value < i) { return add(i, root->Right); } add(i, root->Left); return; } template <class T> void BinaryTree<T>::add(T i, Tree<T>* &leaf) { if (leaf == nullptr) { leaf = NewNode<T>(i); return; } if (leaf->Value < i) { return add(i, leaf->Right); } return add(i, leaf->Left); } template <class T> vector<T> BinaryTree<T>::Walk() { vector<T> out; if (root == nullptr) { cout << "here\n"; return out; } walk(root->Left, out); out.push_back(root->Value); walk(root->Right, out); return out; } template <class T> vector<T> BinaryTree<T>::walk(Tree<T> *leaf, vector<T>& out) { if (leaf == nullptr) { return out; } walk(leaf->Left, out); out.push_back(leaf->Value); walk(leaf->Right, out); return out; } int main() { BinaryTree<int> btree; vector<int> tree; btree.Add(0); btree.Add(4); btree.Add(5); btree.Add(-2); btree.Add(-1); btree.Add(8); tree = btree.Walk(); cout << "[ "; for (auto x = tree.begin(); x != tree.end(); ++x) { cout << (*x) << " "; } cout << "]\n"; BinaryTree<string> btreestr; vector<string> treestr; btreestr.Add("YoYo"); btreestr.Add("Hi"); btreestr.Add("Howdy"); btreestr.Add("Sup"); btreestr.Add("Hello"); btreestr.Add("Wassup"); treestr = btreestr.Walk(); cout << "[ "; for (auto x = treestr.begin(); x != treestr.end(); ++x) { cout << (*x) << " "; } cout << "]\n"; BinaryTree<double> btreedbl; vector<double> treedbl; btreedbl.Add(0.001); btreedbl.Add(-0.001); btreedbl.Add(0.0123); btreedbl.Add(123123.00); btreedbl.Add(123121.001); btreedbl.Add(0.021); treedbl = btreedbl.Walk(); cout << "[ "; for (auto x = treedbl.begin(); x != treedbl.end(); ++x) { cout << (*x) << " "; } cout << "]\n"; { BinaryTree<int> nbtree; } return 0; } <commit_msg>Removed main<commit_after>#ifndef BTREEINC #include <binarytree.h> #define BTREEINC #endif template <class T> BinaryTree<T>::BinaryTree() : root(nullptr), levels(0) {} template <class T> BinaryTree<T>::~BinaryTree() { delete root; } template <class T> unsigned int BinaryTree<T>::Levels() const { return levels; } template <class T> void BinaryTree<T>::Add(T i) { levels++; if (root == nullptr) { root = NewNode<T>(i); return; } if (root->Value < i) { return add(i, root->Right); } add(i, root->Left); return; } template <class T> void BinaryTree<T>::add(T i, Tree<T>* &leaf) { if (leaf == nullptr) { leaf = NewNode<T>(i); return; } if (leaf->Value < i) { return add(i, leaf->Right); } return add(i, leaf->Left); } template <class T> vector<T> BinaryTree<T>::Walk() { vector<T> out; if (root == nullptr) { cout << "here\n"; return out; } walk(root->Left, out); out.push_back(root->Value); walk(root->Right, out); return out; } template <class T> vector<T> BinaryTree<T>::walk(Tree<T> *leaf, vector<T>& out) { if (leaf == nullptr) { return out; } walk(leaf->Left, out); out.push_back(leaf->Value); walk(leaf->Right, out); return out; } <|endoftext|>
<commit_before>// Time: O(n^2 * l), l is the average length of words // Space: O(n) class Solution { public: int numSimilarGroups(vector<string>& A) { UnionFind union_find(A.size()); for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < i; ++j) { if (isSimilar(A[i], A[j])) { union_find.union_set(i, j); } } } return union_find.size(); } private: bool isSimilar(const string& a, const string& b) { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { ++diff; } } return diff == 2; } class UnionFind { public: UnionFind(const int n) : set_(n), size_(n) { iota(set_.begin(), set_.end(), 0); } int find_set(const int x) { if (set_[x] != x) { set_[x] = find_set(set_[x]); // Path compression. } return set_[x]; } bool union_set(const int x, const int y) { int x_root = find_set(x), y_root = find_set(y); if (x_root == y_root) { return false; } set_[min(x_root, y_root)] = max(x_root, y_root); --size_; return true; } int size() const { return size_; } private: vector<int> set_; int size_; }; }; // Time: O(n^2 * l) ~ O(n * l^4) // Space: O(n) ~ O(n * l^3) class Solution_MLE { public: int numSimilarGroups(vector<string>& A) { const int N = A.size(), L = A[0].length(); UnionFind union_find(A.size()); if (N < L*L) { for (int i = 0; i < N; ++i) { for (int j = 0; j < i; ++j) { if (isSimilar(A[i], A[j])) { union_find.union_set(i, j); } } } } else { unordered_map<string, vector<int>> buckets; unordered_set<string> lookup; for (int i = 0; i < A.size(); ++i) { auto word = A[i]; if (!lookup.count(word)) { buckets[word].emplace_back(i); lookup.emplace(word); } for (int j1 = 0; j1 < L; ++j1) { for (int j2 = 0; j2 < j1; ++j2) { swap(word[j1], word[j2]); buckets[word].emplace_back(i); swap(word[j1], word[j2]); } } } for (const auto& word : A) { for (int i = 0; i < buckets[word].size(); ++i) { for (int j = 0; j < i; ++j) { union_find.union_set(buckets[word][i], buckets[word][j]); } } } } return union_find.size(); } private: bool isSimilar(const string &a, const string &b) { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { ++diff; } } return diff == 2; } class UnionFind { public: UnionFind(const int n) : set_(n), size_(n) { iota(set_.begin(), set_.end(), 0); } int find_set(const int x) { if (set_[x] != x) { set_[x] = find_set(set_[x]); // Path compression. } return set_[x]; } bool union_set(const int x, const int y) { int x_root = find_set(x), y_root = find_set(y); if (x_root == y_root) { return false; } set_[min(x_root, y_root)] = max(x_root, y_root); --size_; return true; } int size() const { return size_; } private: vector<int> set_; int size_; }; }; <commit_msg>Update similar-string-groups.cpp<commit_after>// Time: O(n^2 * l), l is the average length of words // Space: O(n) class Solution { public: int numSimilarGroups(vector<string>& A) { UnionFind union_find(A.size()); for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < i; ++j) { if (isSimilar(A[i], A[j])) { union_find.union_set(i, j); } } } return union_find.size(); } private: bool isSimilar(const string& a, const string& b) { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { if (++diff > 2) { return false; } } } return diff == 2; } class UnionFind { public: UnionFind(const int n) : set_(n), size_(n) { iota(set_.begin(), set_.end(), 0); } int find_set(const int x) { if (set_[x] != x) { set_[x] = find_set(set_[x]); // Path compression. } return set_[x]; } bool union_set(const int x, const int y) { int x_root = find_set(x), y_root = find_set(y); if (x_root == y_root) { return false; } set_[min(x_root, y_root)] = max(x_root, y_root); --size_; return true; } int size() const { return size_; } private: vector<int> set_; int size_; }; }; // Time: O(n^2 * l) ~ O(n * l^4) // Space: O(n) ~ O(n * l^3) class Solution_MLE { public: int numSimilarGroups(vector<string>& A) { const int N = A.size(), L = A[0].length(); UnionFind union_find(A.size()); if (N < L*L) { for (int i = 0; i < N; ++i) { for (int j = 0; j < i; ++j) { if (isSimilar(A[i], A[j])) { union_find.union_set(i, j); } } } } else { unordered_map<string, vector<int>> buckets; unordered_set<string> lookup; for (int i = 0; i < A.size(); ++i) { auto word = A[i]; if (!lookup.count(word)) { buckets[word].emplace_back(i); lookup.emplace(word); } for (int j1 = 0; j1 < L; ++j1) { for (int j2 = 0; j2 < j1; ++j2) { swap(word[j1], word[j2]); buckets[word].emplace_back(i); swap(word[j1], word[j2]); } } } for (const auto& word : A) { for (int i = 0; i < buckets[word].size(); ++i) { for (int j = 0; j < i; ++j) { union_find.union_set(buckets[word][i], buckets[word][j]); } } } } return union_find.size(); } private: bool isSimilar(const string& a, const string& b) { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { if (++diff > 2) { return false; } } } return diff == 2; } class UnionFind { public: UnionFind(const int n) : set_(n), size_(n) { iota(set_.begin(), set_.end(), 0); } int find_set(const int x) { if (set_[x] != x) { set_[x] = find_set(set_[x]); // Path compression. } return set_[x]; } bool union_set(const int x, const int y) { int x_root = find_set(x), y_root = find_set(y); if (x_root == y_root) { return false; } set_[min(x_root, y_root)] = max(x_root, y_root); --size_; return true; } int size() const { return size_; } private: vector<int> set_; int size_; }; }; <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007, Trustees of Leland Stanford Junior University 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 Stanford University 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. */ /*vc.cpp * *this class describes a virtual channel in a router *it includes buffers and virtual channel state and controls * *This class calls the routing functions */ #include "globals.hpp" #include "booksim.hpp" #include "vc.hpp" int VC::total_cycles = 0; VC::state_info_t VC::state_info[] = {{"idle", 0}, {"routing", 0}, {"vc_alloc", 0}, {"active", 0}, {"vc_spec", 0}, {"vc_spec_grant", 0}}; int VC::occupancy = 0; VC::VC( const Configuration& config, int outputs ) : Module( ) { _Init( config, outputs ); } VC::VC( const Configuration& config, int outputs, Module *parent, const string& name ) : Module( parent, name ) { _Init( config, outputs ); } VC::~VC( ) { } void VC::_Init( const Configuration& config, int outputs ) { _state = idle; _state_time = 0; _size = int( config.GetInt( "vc_buf_size" ) ); _route_set = new OutputSet( outputs ); _occupied_cnt = 0; _total_cycles = 0; _vc_alloc_cycles = 0; _active_cycles = 0; _idle_cycles = 0; _routing_cycles = 0; _pri = 0; _out_port = 0 ; _out_vc = 0 ; _watched = false; } bool VC::AddFlit( Flit *f ) { bool success = false; if ( (int)_buffer.size( ) != _size ) { _buffer.push( f ); success = true; } return success; } Flit *VC::FrontFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); } else { f = 0; } return f; } Flit *VC::RemoveFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); _buffer.pop( ); } else { f = 0; } return f; } bool VC::Empty( ) const { return _buffer.empty( ); } bool VC::Full( ) const { return (int)_buffer.size( ) == _size; } VC::eVCState VC::GetState( ) const { return _state; } int VC::GetStateTime( ) const { return _state_time; } void VC::SetState( eVCState s ) { Flit * f = FrontFlit(); if(f && f->watch) cout << "VC " << _fullname << " changed state" << " at time " << GetSimTime() << endl << " Old: " << state_info[_state].name << " New: " << state_info[s].name << endl; // do not reset state time for speculation-related pseudo state transitions if(!((_state == vc_spec) && (s == vc_spec_grant)) && !((_state == vc_spec_grant) && (s == active))) _state_time = 0; if ( (_state == idle) && (s != idle) ) { if ( f ) { _pri = f->pri; } _occupied_cnt++; } _state = s; } const OutputSet *VC::GetRouteSet( ) const { return _route_set; } void VC::SetOutput( int port, int vc ) { _out_port = port; _out_vc = vc; } int VC::GetOutputPort( ) const { return _out_port; } int VC::GetOutputVC( ) const { return _out_vc; } int VC::GetPriority( ) const { return _pri; } int VC::GetSize() const { return (int)_buffer.size(); } void VC::Route( tRoutingFunction rf, const Router* router, const Flit* f, int in_channel ) { rf( router, f, in_channel, _route_set, false ); } void VC::AdvanceTime( ) { _state_time++; _total_cycles++; total_cycles++; switch( _state ) { case idle : _idle_cycles++; break; case active : _active_cycles++; break; case vc_spec_grant : _active_cycles++; break; case vc_alloc : _vc_alloc_cycles++; break; case vc_spec : _vc_alloc_cycles++; break; case routing : _routing_cycles++; break; } state_info[_state].cycles++; occupancy += _buffer.size(); } // ==== Debug functions ==== void VC::SetWatch( bool watch ) { _watched = watch; } bool VC::IsWatched( ) const { return _watched; } void VC::Display( ) const { // cout << _fullname << " : " // << "idle " << 100.0 * (double)_idle_cycles / (double)_total_cycles << "% " // << "vc_alloc " << 100.0 * (double)_vc_alloc_cycles / (double)_total_cycles << "% " // << "active " << 100.0 * (double)_active_cycles / (double)_total_cycles << "% " // << endl; if ( _state != VC::idle ) { cout << _fullname << ": " << " state: " << state_info[_state].name << " out_port: " << _out_port << " out_vc: " << _out_vc << " fill: " << _buffer.size() << endl ; } } void VC::DisplayStats( ) { cout << "VC state breakdown:" << endl; for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << " " << state_info[state].name << ": " << (float)state_info[state].cycles/(float)total_cycles << endl; } } <commit_msg>re-add occupancy counter to VC class<commit_after>// $Id$ /* Copyright (c) 2007, Trustees of Leland Stanford Junior University 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 Stanford University 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. */ /*vc.cpp * *this class describes a virtual channel in a router *it includes buffers and virtual channel state and controls * *This class calls the routing functions */ #include "globals.hpp" #include "booksim.hpp" #include "vc.hpp" int VC::total_cycles = 0; VC::state_info_t VC::state_info[] = {{"idle", 0}, {"routing", 0}, {"vc_alloc", 0}, {"active", 0}, {"vc_spec", 0}, {"vc_spec_grant", 0}}; int VC::occupancy = 0; VC::VC( const Configuration& config, int outputs ) : Module( ) { _Init( config, outputs ); } VC::VC( const Configuration& config, int outputs, Module *parent, const string& name ) : Module( parent, name ) { _Init( config, outputs ); } VC::~VC( ) { } void VC::_Init( const Configuration& config, int outputs ) { _state = idle; _state_time = 0; _size = int( config.GetInt( "vc_buf_size" ) ); _route_set = new OutputSet( outputs ); _occupied_cnt = 0; _total_cycles = 0; _vc_alloc_cycles = 0; _active_cycles = 0; _idle_cycles = 0; _routing_cycles = 0; _pri = 0; _out_port = 0 ; _out_vc = 0 ; _watched = false; } bool VC::AddFlit( Flit *f ) { bool success = false; if ( (int)_buffer.size( ) != _size ) { _buffer.push( f ); success = true; } return success; } Flit *VC::FrontFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); } else { f = 0; } return f; } Flit *VC::RemoveFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); _buffer.pop( ); } else { f = 0; } return f; } bool VC::Empty( ) const { return _buffer.empty( ); } bool VC::Full( ) const { return (int)_buffer.size( ) == _size; } VC::eVCState VC::GetState( ) const { return _state; } int VC::GetStateTime( ) const { return _state_time; } void VC::SetState( eVCState s ) { Flit * f = FrontFlit(); if(f && f->watch) cout << "VC " << _fullname << " changed state" << " at time " << GetSimTime() << endl << " Old: " << state_info[_state].name << " New: " << state_info[s].name << endl; // do not reset state time for speculation-related pseudo state transitions if(!((_state == vc_spec) && (s == vc_spec_grant)) && !((_state == vc_spec_grant) && (s == active))) _state_time = 0; if ( (_state == idle) && (s != idle) ) { if ( f ) { _pri = f->pri; } _occupied_cnt++; } _state = s; } const OutputSet *VC::GetRouteSet( ) const { return _route_set; } void VC::SetOutput( int port, int vc ) { _out_port = port; _out_vc = vc; } int VC::GetOutputPort( ) const { return _out_port; } int VC::GetOutputVC( ) const { return _out_vc; } int VC::GetPriority( ) const { return _pri; } int VC::GetSize() const { return (int)_buffer.size(); } void VC::Route( tRoutingFunction rf, const Router* router, const Flit* f, int in_channel ) { rf( router, f, in_channel, _route_set, false ); } void VC::AdvanceTime( ) { _state_time++; _total_cycles++; total_cycles++; switch( _state ) { case idle : _idle_cycles++; break; case active : _active_cycles++; break; case vc_spec_grant : _active_cycles++; break; case vc_alloc : _vc_alloc_cycles++; break; case vc_spec : _vc_alloc_cycles++; break; case routing : _routing_cycles++; break; } state_info[_state].cycles++; occupancy += _buffer.size(); } // ==== Debug functions ==== void VC::SetWatch( bool watch ) { _watched = watch; } bool VC::IsWatched( ) const { return _watched; } void VC::Display( ) const { // cout << _fullname << " : " // << "idle " << 100.0 * (double)_idle_cycles / (double)_total_cycles << "% " // << "vc_alloc " << 100.0 * (double)_vc_alloc_cycles / (double)_total_cycles << "% " // << "active " << 100.0 * (double)_active_cycles / (double)_total_cycles << "% " // << endl; if ( _state != VC::idle ) { cout << _fullname << ": " << " state: " << state_info[_state].name << " out_port: " << _out_port << " out_vc: " << _out_vc << " fill: " << _buffer.size() << endl ; } } void VC::DisplayStats( ) { cout << "VC state breakdown:" << endl; for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << " " << state_info[state].name << ": " << (float)state_info[state].cycles/(float)total_cycles << endl; } cout << " occupancy: " << (float)occupancy/(float)total_cycles << endl; } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "lxqtmainmenu.h" #include "lxqtmainmenuconfiguration.h" #include <QDebug> #include <XdgDesktopFile> #include <XmlHelper> #include <QSettings> #include <QFileInfo> #include <QAction> #include <QTimer> #include <QMessageBox> #include <QEvent> #include <QKeyEvent> #include <LXQt/PowerManager> #include <LXQt/ScreenSaver> #include <lxqt-globalkeys.h> #include <KF5/KWindowSystem/KWindowSystem> #include <XdgIcon> #include <XdgDesktopFile> #include <XdgMenuWidget> #ifdef HAVE_MENU_CACHE #include "xdgcachedmenu.h" #endif #include <QPixmap> #include <QStack> #include <QCursor> #define DEFAULT_SHORTCUT "Alt+F1" /************************************************ ************************************************/ KeyPressEventFilter::KeyPressEventFilter(QMenu *menu, QObject *parent): QObject(parent), mPreviousAction(0) { mMenu = menu; } /************************************************ ************************************************/ bool KeyPressEventFilter::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); QMenu* menu=0; if (obj == mMenu) { menu = mMenu; } else { foreach (QAction* action, mMenu->actions()) { if (action->menu() && action->menu() == obj) { menu = action->menu(); break; } } } if (menu == 0) return QObject::eventFilter(obj, event); QAction* currentAction = 0; if (menu->actions().indexOf(mPreviousAction) > -1) { for (int i=menu->actions().indexOf(mPreviousAction)+1; i<menu->actions().count(); i++) { if (menu->actions().at(i)->text().startsWith(QChar(keyEvent->key()), Qt::CaseInsensitive)) { currentAction = menu->actions().at(i); break; } } } if (!currentAction) { foreach (QAction* action, menu->actions()) { if (action->text().startsWith(QChar(keyEvent->key()), Qt::CaseInsensitive)) { currentAction = action; break; } } } if (currentAction) { mPreviousAction = currentAction; menu->setActiveAction(currentAction); if (currentAction->menu()) { currentAction->menu()->hide(); } } } return QObject::eventFilter(obj, event); } /************************************************ ************************************************/ LxQtMainMenu::LxQtMainMenu(const ILxQtPanelPluginStartupInfo &startupInfo): QObject(), ILxQtPanelPlugin(startupInfo), mMenu(0), mShortcut(0), mLockCascadeChanges(false) { #ifdef HAVE_MENU_CACHE mMenuCache = NULL; mMenuCacheNotify = 0; #endif mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); mButton.installEventFilter(this); connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu())); settingsChanged(); connect(mShortcut, SIGNAL(activated()), this, SLOT(showHideMenu())); connect(mShortcut, SIGNAL(shortcutChanged(QString,QString)), this, SLOT(shortcutChanged(QString,QString))); } /************************************************ ************************************************/ LxQtMainMenu::~LxQtMainMenu() { mButton.removeEventFilter(this); #ifdef HAVE_MENU_CACHE if(mMenuCache) { menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify); menu_cache_unref(mMenuCache); } #endif } /************************************************ ************************************************/ void LxQtMainMenu::showHideMenu() { if (mMenu && mMenu->isVisible()) mMenu->hide(); else showMenu(); } /************************************************ ************************************************/ void LxQtMainMenu::shortcutChanged(const QString &/*oldShortcut*/, const QString &newShortcut) { if (!newShortcut.isEmpty()) { mLockCascadeChanges = true; settings()->setValue("dialog/shortcut", newShortcut); settings()->sync(); mLockCascadeChanges = false; } } /************************************************ ************************************************/ void LxQtMainMenu::showMenu() { if (!mMenu) return; int x=0, y=0; switch (panel()->position()) { case ILxQtPanel::PositionTop: x = mButton.mapToGlobal(QPoint(0, 0)).x(); y = panel()->globalGometry().bottom(); break; case ILxQtPanel::PositionBottom: x = mButton.mapToGlobal(QPoint(0, 0)).x(); y = panel()->globalGometry().top() - mMenu->sizeHint().height(); break; case ILxQtPanel::PositionLeft: x = panel()->globalGometry().right(); y = mButton.mapToGlobal(QPoint(0, 0)).y(); break; case ILxQtPanel::PositionRight: x = panel()->globalGometry().left() - mMenu->sizeHint().width(); y = mButton.mapToGlobal(QPoint(0, 0)).y(); break; } // Just using Qt`s activateWindow() won't work on some WMs like Kwin. // Solution is to execute menu 1ms later using timer mButton.activateWindow(); mMenu->exec(QPoint(x, y)); } #ifdef HAVE_MENU_CACHE // static void LxQtMainMenu::menuCacheReloadNotify(MenuCache* cache, gpointer user_data) { reinterpret_cast<LxQtMainMenu*>(user_data)->buildMenu(); } #endif /************************************************ ************************************************/ void LxQtMainMenu::settingsChanged() { if (mLockCascadeChanges) return; if (settings()->value("showText", false).toBool()) { mButton.setText(settings()->value("text", "Start").toString()); mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon); } else { mButton.setText(""); mButton.setToolButtonStyle(Qt::ToolButtonIconOnly); } mLogDir = settings()->value("log_dir", "").toString(); QString mMenuFile = settings()->value("menu_file", "").toString(); if (mMenuFile.isEmpty()) mMenuFile = XdgMenu::getMenuFileName(); #ifdef HAVE_MENU_CACHE menu_cache_init(0); if(mMenuCache) { menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify); menu_cache_unref(mMenuCache); } mMenuCache = menu_cache_lookup(mMenuFile.toLocal8Bit()); mMenuCacheNotify = menu_cache_add_reload_notify(mMenuCache, (MenuCacheReloadNotify)menuCacheReloadNotify, this); #else mXdgMenu.setEnvironments(QStringList() << "X-LXQT" << "LxQt"); mXdgMenu.setLogDir(mLogDir); bool res = mXdgMenu.read(mMenuFile); connect(&mXdgMenu, SIGNAL(changed()), this, SLOT(buildMenu())); if (res) { QTimer::singleShot(1000, this, SLOT(buildMenu())); } else { QMessageBox::warning(0, "Parse error", mXdgMenu.errorString()); return; } #endif QString shortcut = settings()->value("shortcut", DEFAULT_SHORTCUT).toString(); if (shortcut.isEmpty()) shortcut = DEFAULT_SHORTCUT; if (!mShortcut) mShortcut = GlobalKeyShortcut::Client::instance()->addAction(shortcut, QString("/panel/%1/show_hide").arg(settings()->group()), tr("Show/hide main menu"), this); else if (mShortcut->shortcut() != shortcut) { mShortcut->changeShortcut(shortcut); } realign(); } /************************************************ ************************************************/ void LxQtMainMenu::buildMenu() { #ifdef HAVE_MENU_CACHE XdgCachedMenu* menu = new XdgCachedMenu(mMenuCache, &mButton); #else XdgMenuWidget *menu = new XdgMenuWidget(mXdgMenu, "", &mButton); #endif menu->setObjectName("TopLevelMainMenu"); menu->setStyle(&mTopMenuStyle); menu->addSeparator(); mEventFilter = new KeyPressEventFilter(menu, this); foreach (QAction* action, menu->actions()) { if (action->menu()) action->menu()->installEventFilter(mEventFilter); } menu->installEventFilter(mEventFilter); QMenu *oldMenu = mMenu; mMenu = menu; delete oldMenu; if(settings()->value("customFont", false).toBool()) { QFont menuFont = mMenu->font(); menuFont.setPointSize(settings()->value("customFontSize").toInt()); mMenu->setFont(menuFont); QList<QMenu*> subMenuList = mMenu->findChildren<QMenu*>(); foreach (QMenu* subMenu, subMenuList) { subMenu->setFont(menuFont); } } } /************************************************ ************************************************/ QDialog *LxQtMainMenu::configureDialog() { return new LxQtMainMenuConfiguration(*settings(), DEFAULT_SHORTCUT); } /************************************************ ************************************************/ bool LxQtMainMenu::eventFilter(QObject *obj, QEvent *event) { if(obj == &mButton) { // the application is given a new QStyle if(event->type() == QEvent::StyleChange) { // reset proxy style for the menus so they can apply the new styles mTopMenuStyle.setBaseStyle(NULL); mMenuStyle.setBaseStyle(NULL); } } return false; } #undef DEFAULT_SHORTCUT <commit_msg>Fix mainmenu's focus<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "lxqtmainmenu.h" #include "lxqtmainmenuconfiguration.h" #include <QDebug> #include <XdgDesktopFile> #include <XmlHelper> #include <QSettings> #include <QFileInfo> #include <QAction> #include <QTimer> #include <QMessageBox> #include <QEvent> #include <QKeyEvent> #include <LXQt/PowerManager> #include <LXQt/ScreenSaver> #include <lxqt-globalkeys.h> #include <KF5/KWindowSystem/KWindowSystem> #include <XdgIcon> #include <XdgDesktopFile> #include <XdgMenuWidget> #ifdef HAVE_MENU_CACHE #include "xdgcachedmenu.h" #endif #include <QPixmap> #include <QStack> #include <QCursor> #define DEFAULT_SHORTCUT "Alt+F1" /************************************************ ************************************************/ KeyPressEventFilter::KeyPressEventFilter(QMenu *menu, QObject *parent): QObject(parent), mPreviousAction(0) { mMenu = menu; } /************************************************ ************************************************/ bool KeyPressEventFilter::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); QMenu* menu=0; if (obj == mMenu) { menu = mMenu; } else { foreach (QAction* action, mMenu->actions()) { if (action->menu() && action->menu() == obj) { menu = action->menu(); break; } } } if (menu == 0) return QObject::eventFilter(obj, event); QAction* currentAction = 0; if (menu->actions().indexOf(mPreviousAction) > -1) { for (int i=menu->actions().indexOf(mPreviousAction)+1; i<menu->actions().count(); i++) { if (menu->actions().at(i)->text().startsWith(QChar(keyEvent->key()), Qt::CaseInsensitive)) { currentAction = menu->actions().at(i); break; } } } if (!currentAction) { foreach (QAction* action, menu->actions()) { if (action->text().startsWith(QChar(keyEvent->key()), Qt::CaseInsensitive)) { currentAction = action; break; } } } if (currentAction) { mPreviousAction = currentAction; menu->setActiveAction(currentAction); if (currentAction->menu()) { currentAction->menu()->hide(); } } } return QObject::eventFilter(obj, event); } /************************************************ ************************************************/ LxQtMainMenu::LxQtMainMenu(const ILxQtPanelPluginStartupInfo &startupInfo): QObject(), ILxQtPanelPlugin(startupInfo), mMenu(0), mShortcut(0), mLockCascadeChanges(false) { #ifdef HAVE_MENU_CACHE mMenuCache = NULL; mMenuCacheNotify = 0; #endif mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); mButton.installEventFilter(this); settingsChanged(); connect(mShortcut, SIGNAL(activated()), this, SLOT(showHideMenu())); connect(mShortcut, SIGNAL(shortcutChanged(QString,QString)), this, SLOT(shortcutChanged(QString,QString))); } /************************************************ ************************************************/ LxQtMainMenu::~LxQtMainMenu() { mButton.removeEventFilter(this); #ifdef HAVE_MENU_CACHE if(mMenuCache) { menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify); menu_cache_unref(mMenuCache); } #endif } /************************************************ ************************************************/ void LxQtMainMenu::showHideMenu() { if (mMenu && mMenu->isVisible()) mMenu->hide(); else showMenu(); } /************************************************ ************************************************/ void LxQtMainMenu::shortcutChanged(const QString &/*oldShortcut*/, const QString &newShortcut) { if (!newShortcut.isEmpty()) { mLockCascadeChanges = true; settings()->setValue("dialog/shortcut", newShortcut); settings()->sync(); mLockCascadeChanges = false; } } /************************************************ ************************************************/ void LxQtMainMenu::showMenu() { if (!mMenu) return; int x=0, y=0; switch (panel()->position()) { case ILxQtPanel::PositionTop: x = mButton.mapToGlobal(QPoint(0, 0)).x(); y = panel()->globalGometry().bottom(); break; case ILxQtPanel::PositionBottom: x = mButton.mapToGlobal(QPoint(0, 0)).x(); y = panel()->globalGometry().top() - mMenu->sizeHint().height(); break; case ILxQtPanel::PositionLeft: x = panel()->globalGometry().right(); y = mButton.mapToGlobal(QPoint(0, 0)).y(); break; case ILxQtPanel::PositionRight: x = panel()->globalGometry().left() - mMenu->sizeHint().width(); y = mButton.mapToGlobal(QPoint(0, 0)).y(); break; } mButton.activateWindow(); mMenu->popup(QPoint(x, y)); KWindowSystem::forceActiveWindow(mMenu->winId()); mMenu->setFocus(Qt::ActiveWindowFocusReason); } #ifdef HAVE_MENU_CACHE // static void LxQtMainMenu::menuCacheReloadNotify(MenuCache* cache, gpointer user_data) { reinterpret_cast<LxQtMainMenu*>(user_data)->buildMenu(); } #endif /************************************************ ************************************************/ void LxQtMainMenu::settingsChanged() { if (mLockCascadeChanges) return; if (settings()->value("showText", false).toBool()) { mButton.setText(settings()->value("text", "Start").toString()); mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon); } else { mButton.setText(""); mButton.setToolButtonStyle(Qt::ToolButtonIconOnly); } mLogDir = settings()->value("log_dir", "").toString(); QString mMenuFile = settings()->value("menu_file", "").toString(); if (mMenuFile.isEmpty()) mMenuFile = XdgMenu::getMenuFileName(); #ifdef HAVE_MENU_CACHE menu_cache_init(0); if(mMenuCache) { menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify); menu_cache_unref(mMenuCache); } mMenuCache = menu_cache_lookup(mMenuFile.toLocal8Bit()); mMenuCacheNotify = menu_cache_add_reload_notify(mMenuCache, (MenuCacheReloadNotify)menuCacheReloadNotify, this); #else mXdgMenu.setEnvironments(QStringList() << "X-LXQT" << "LxQt"); mXdgMenu.setLogDir(mLogDir); bool res = mXdgMenu.read(mMenuFile); connect(&mXdgMenu, SIGNAL(changed()), this, SLOT(buildMenu())); if (res) { QTimer::singleShot(1000, this, SLOT(buildMenu())); } else { QMessageBox::warning(0, "Parse error", mXdgMenu.errorString()); return; } #endif QString shortcut = settings()->value("shortcut", DEFAULT_SHORTCUT).toString(); if (shortcut.isEmpty()) shortcut = DEFAULT_SHORTCUT; if (!mShortcut) mShortcut = GlobalKeyShortcut::Client::instance()->addAction(shortcut, QString("/panel/%1/show_hide").arg(settings()->group()), tr("Show/hide main menu"), this); else if (mShortcut->shortcut() != shortcut) { mShortcut->changeShortcut(shortcut); } realign(); } /************************************************ ************************************************/ void LxQtMainMenu::buildMenu() { #ifdef HAVE_MENU_CACHE XdgCachedMenu* menu = new XdgCachedMenu(mMenuCache, &mButton); #else XdgMenuWidget *menu = new XdgMenuWidget(mXdgMenu, "", &mButton); #endif // needed for menu's focus and for making invisible on taskbar menu->setWindowFlags(Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); menu->setAttribute(Qt::WA_TranslucentBackground); KWindowSystem::setType(menu->winId(), NET::Menu); menu->setObjectName("TopLevelMainMenu"); menu->setStyle(&mTopMenuStyle); menu->addSeparator(); mEventFilter = new KeyPressEventFilter(menu, this); foreach (QAction* action, menu->actions()) { if (action->menu()) action->menu()->installEventFilter(mEventFilter); } menu->installEventFilter(mEventFilter); QMenu *oldMenu = mMenu; mMenu = menu; delete oldMenu; if(settings()->value("customFont", false).toBool()) { QFont menuFont = mMenu->font(); menuFont.setPointSize(settings()->value("customFontSize").toInt()); mMenu->setFont(menuFont); QList<QMenu*> subMenuList = mMenu->findChildren<QMenu*>(); foreach (QMenu* subMenu, subMenuList) { subMenu->setFont(menuFont); } } } /************************************************ ************************************************/ QDialog *LxQtMainMenu::configureDialog() { return new LxQtMainMenuConfiguration(*settings(), DEFAULT_SHORTCUT); } /************************************************ ************************************************/ bool LxQtMainMenu::eventFilter(QObject *obj, QEvent *event) { if(obj == &mButton) { // the application is given a new QStyle if(event->type() == QEvent::StyleChange) { // reset proxy style for the menus so they can apply the new styles mTopMenuStyle.setBaseStyle(NULL); mMenuStyle.setBaseStyle(NULL); return true; } if (event->type() == QEvent::MouseButtonRelease) { showHideMenu(); return true; } } if (obj == mMenu) { if (event->type() == QEvent::FocusOut) { showHideMenu(); return true; } } return false; } #undef DEFAULT_SHORTCUT <|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/browser/ui/views/frame/browser_desktop_root_window_host_win.h" #include <dwmapi.h> #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/views/frame/browser_frame.h" #include "chrome/browser/ui/views/frame/browser_frame_common_win.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/system_menu_insertion_delegate_win.h" #include "chrome/browser/ui/views/tabs/tab_strip.h" #include "chrome/browser/ui/views/theme_image_mapper.h" #include "grit/theme_resources.h" #include "ui/base/theme_provider.h" #include "ui/views/controls/menu/native_menu_win.h" #pragma comment(lib, "dwmapi.lib") namespace { const int kClientEdgeThickness = 3; // We need to offset the DWMFrame into the toolbar so that the blackness // doesn't show up on our rounded corners. const int kDWMFrameTopOffset = 3; // DesktopThemeProvider maps resource ids using MapThemeImage(). This is // necessary for BrowserDesktopRootWindowHostWin so that it uses the windows // theme images rather than the ash theme images. class DesktopThemeProvider : public ui::ThemeProvider { public: explicit DesktopThemeProvider(ui::ThemeProvider* delegate) : delegate_(delegate) { } virtual gfx::ImageSkia* GetImageSkiaNamed(int id) const OVERRIDE { return delegate_->GetImageSkiaNamed( chrome::MapThemeImage(chrome::HOST_DESKTOP_TYPE_NATIVE, id)); } virtual SkColor GetColor(int id) const OVERRIDE { return delegate_->GetColor(id); } virtual bool GetDisplayProperty(int id, int* result) const OVERRIDE { return delegate_->GetDisplayProperty(id, result); } virtual bool ShouldUseNativeFrame() const OVERRIDE { return delegate_->ShouldUseNativeFrame(); } virtual bool HasCustomImage(int id) const OVERRIDE { return delegate_->HasCustomImage(chrome::MapThemeImage( chrome::HOST_DESKTOP_TYPE_NATIVE, id)); } virtual base::RefCountedMemory* GetRawData( int id, ui::ScaleFactor scale_factor) const OVERRIDE { return delegate_->GetRawData(id, scale_factor); } private: ui::ThemeProvider* delegate_; DISALLOW_COPY_AND_ASSIGN(DesktopThemeProvider); }; } // namespace //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, public: BrowserDesktopRootWindowHostWin::BrowserDesktopRootWindowHostWin( views::internal::NativeWidgetDelegate* native_widget_delegate, views::DesktopNativeWidgetAura* desktop_native_widget_aura, const gfx::Rect& initial_bounds, BrowserView* browser_view, BrowserFrame* browser_frame) : DesktopRootWindowHostWin(native_widget_delegate, desktop_native_widget_aura, initial_bounds), browser_view_(browser_view), browser_frame_(browser_frame) { scoped_ptr<ui::ThemeProvider> theme_provider( new DesktopThemeProvider(ThemeServiceFactory::GetForProfile( browser_view->browser()->profile()))); browser_frame->SetThemeProvider(theme_provider.Pass()); } BrowserDesktopRootWindowHostWin::~BrowserDesktopRootWindowHostWin() { } views::NativeMenuWin* BrowserDesktopRootWindowHostWin::GetSystemMenu() { if (!system_menu_.get()) { SystemMenuInsertionDelegateWin insertion_delegate; system_menu_.reset( new views::NativeMenuWin(browser_frame_->GetSystemMenuModel(), GetHWND())); system_menu_->Rebuild(&insertion_delegate); } return system_menu_.get(); } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, BrowserDesktopRootWindowHost implementation: views::DesktopRootWindowHost* BrowserDesktopRootWindowHostWin::AsDesktopRootWindowHost() { return this; } int BrowserDesktopRootWindowHostWin::GetMinimizeButtonOffset() const { return minimize_button_metrics_.GetMinimizeButtonOffsetX(); } bool BrowserDesktopRootWindowHostWin::UsesNativeSystemMenu() const { return true; } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, views::DesktopRootWindowHostWin overrides: int BrowserDesktopRootWindowHostWin::GetInitialShowState() const { STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; GetStartupInfo(&si); return si.wShowWindow; } bool BrowserDesktopRootWindowHostWin::GetClientAreaInsets( gfx::Insets* insets) const { // Use the default client insets for an opaque frame or a glass popup/app // frame. if (!GetWidget()->ShouldUseNativeFrame() || !browser_view_->IsBrowserTypeNormal()) { return false; } int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); // In fullscreen mode, we have no frame. In restored mode, we draw our own // client edge over part of the default frame. if (GetWidget()->IsFullscreen()) border_thickness = 0; else if (!IsMaximized()) border_thickness -= kClientEdgeThickness; insets->Set(0, border_thickness, border_thickness, border_thickness); return true; } void BrowserDesktopRootWindowHostWin::HandleFrameChanged() { // We need to update the glass region on or off before the base class adjusts // the window region. UpdateDWMFrame(); DesktopRootWindowHostWin::HandleFrameChanged(); } bool BrowserDesktopRootWindowHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { switch (message) { case WM_ACTIVATE: if (LOWORD(w_param) != WA_INACTIVE) minimize_button_metrics_.OnHWNDActivated(); return false; case WM_ENDSESSION: browser::SessionEnding(); return true; case WM_INITMENUPOPUP: GetSystemMenu()->UpdateStates(); return true; } return DesktopRootWindowHostWin::PreHandleMSG( message, w_param, l_param, result); } void BrowserDesktopRootWindowHostWin::PostHandleMSG(UINT message, WPARAM w_param, LPARAM l_param) { switch (message) { case WM_CREATE: minimize_button_metrics_.Init(GetHWND()); break; case WM_WINDOWPOSCHANGED: UpdateDWMFrame(); // Windows lies to us about the position of the minimize button before a // window is visible. We use this position to place the OTR avatar in RTL // mode, so when the window is shown, we need to re-layout and schedule a // paint for the non-client frame view so that the icon top has the correct // position when the window becomes visible. This fixes bugs where the icon // appears to overlay the minimize button. // Note that we will call Layout every time SetWindowPos is called with // SWP_SHOWWINDOW, however callers typically are careful about not // specifying this flag unless necessary to avoid flicker. // This may be invoked during creation on XP and before the non_client_view // has been created. WINDOWPOS* window_pos = reinterpret_cast<WINDOWPOS*>(l_param); if (window_pos->flags & SWP_SHOWWINDOW && GetWidget()->non_client_view()) { GetWidget()->non_client_view()->Layout(); GetWidget()->non_client_view()->SchedulePaint(); } break; } } bool BrowserDesktopRootWindowHostWin::IsUsingCustomFrame() const { // App panel windows draw their own frame. if (browser_view_->IsPanel()) return true; // We don't theme popup or app windows, so regardless of whether or not a // theme is active for normal browser windows, we don't want to use the custom // frame for popups/apps. if (!browser_view_->IsBrowserTypeNormal() && !DesktopRootWindowHostWin::IsUsingCustomFrame()) { return false; } // Otherwise, we use the native frame when we're told we should by the theme // provider (e.g. no custom theme is active). return !GetWidget()->GetThemeProvider()->ShouldUseNativeFrame(); } bool BrowserDesktopRootWindowHostWin::ShouldUseNativeFrame() { if (!views::DesktopRootWindowHostWin::ShouldUseNativeFrame()) return false; return chrome::ShouldUseNativeFrame(browser_view_, GetWidget()->GetThemeProvider()); } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, private: void BrowserDesktopRootWindowHostWin::UpdateDWMFrame() { // For "normal" windows on Aero, we always need to reset the glass area // correctly, even if we're not currently showing the native frame (e.g. // because a theme is showing), so we explicitly check for that case rather // than checking browser_frame_->ShouldUseNativeFrame() here. Using that here // would mean we wouldn't reset the glass area to zero when moving from the // native frame to an opaque frame, leading to graphical glitches behind the // opaque frame. Instead, we use that function below to tell us whether the // frame is currently native or opaque. if (!GetWidget()->client_view() || !browser_view_->IsBrowserTypeNormal() || !DesktopRootWindowHostWin::ShouldUseNativeFrame()) return; MARGINS margins = { 0 }; // If the opaque frame is visible, we use the default (zero) margins. // Otherwise, we need to figure out how to extend the glass in. if (GetWidget()->ShouldUseNativeFrame()) { // In fullscreen mode, we don't extend glass into the client area at all, // because the GDI-drawn text in the web content composited over it will // become semi-transparent over any glass area. if (!IsMaximized() && !GetWidget()->IsFullscreen()) { margins.cxLeftWidth = kClientEdgeThickness + 1; margins.cxRightWidth = kClientEdgeThickness + 1; margins.cyBottomHeight = kClientEdgeThickness + 1; margins.cyTopHeight = kClientEdgeThickness + 1; } // In maximized mode, we only have a titlebar strip of glass, no side/bottom // borders. if (!browser_view_->IsFullscreen()) { gfx::Rect tabstrip_bounds( browser_frame_->GetBoundsForTabStrip(browser_view_->tabstrip())); margins.cyTopHeight = tabstrip_bounds.bottom() + kDWMFrameTopOffset; } } DwmExtendFrameIntoClientArea(GetHWND(), &margins); } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHost, public: // static BrowserDesktopRootWindowHost* BrowserDesktopRootWindowHost::CreateBrowserDesktopRootWindowHost( views::internal::NativeWidgetDelegate* native_widget_delegate, views::DesktopNativeWidgetAura* desktop_native_widget_aura, const gfx::Rect& initial_bounds, BrowserView* browser_view, BrowserFrame* browser_frame) { return new BrowserDesktopRootWindowHostWin(native_widget_delegate, desktop_native_widget_aura, initial_bounds, browser_view, browser_frame); } <commit_msg>Fix an AURA browser crash which occurs at times when the browser window is being closed.<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/browser/ui/views/frame/browser_desktop_root_window_host_win.h" #include <dwmapi.h> #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/views/frame/browser_frame.h" #include "chrome/browser/ui/views/frame/browser_frame_common_win.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/system_menu_insertion_delegate_win.h" #include "chrome/browser/ui/views/tabs/tab_strip.h" #include "chrome/browser/ui/views/theme_image_mapper.h" #include "grit/theme_resources.h" #include "ui/base/theme_provider.h" #include "ui/views/controls/menu/native_menu_win.h" #pragma comment(lib, "dwmapi.lib") namespace { const int kClientEdgeThickness = 3; // We need to offset the DWMFrame into the toolbar so that the blackness // doesn't show up on our rounded corners. const int kDWMFrameTopOffset = 3; // DesktopThemeProvider maps resource ids using MapThemeImage(). This is // necessary for BrowserDesktopRootWindowHostWin so that it uses the windows // theme images rather than the ash theme images. class DesktopThemeProvider : public ui::ThemeProvider { public: explicit DesktopThemeProvider(ui::ThemeProvider* delegate) : delegate_(delegate) { } virtual gfx::ImageSkia* GetImageSkiaNamed(int id) const OVERRIDE { return delegate_->GetImageSkiaNamed( chrome::MapThemeImage(chrome::HOST_DESKTOP_TYPE_NATIVE, id)); } virtual SkColor GetColor(int id) const OVERRIDE { return delegate_->GetColor(id); } virtual bool GetDisplayProperty(int id, int* result) const OVERRIDE { return delegate_->GetDisplayProperty(id, result); } virtual bool ShouldUseNativeFrame() const OVERRIDE { return delegate_->ShouldUseNativeFrame(); } virtual bool HasCustomImage(int id) const OVERRIDE { return delegate_->HasCustomImage(chrome::MapThemeImage( chrome::HOST_DESKTOP_TYPE_NATIVE, id)); } virtual base::RefCountedMemory* GetRawData( int id, ui::ScaleFactor scale_factor) const OVERRIDE { return delegate_->GetRawData(id, scale_factor); } private: ui::ThemeProvider* delegate_; DISALLOW_COPY_AND_ASSIGN(DesktopThemeProvider); }; } // namespace //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, public: BrowserDesktopRootWindowHostWin::BrowserDesktopRootWindowHostWin( views::internal::NativeWidgetDelegate* native_widget_delegate, views::DesktopNativeWidgetAura* desktop_native_widget_aura, const gfx::Rect& initial_bounds, BrowserView* browser_view, BrowserFrame* browser_frame) : DesktopRootWindowHostWin(native_widget_delegate, desktop_native_widget_aura, initial_bounds), browser_view_(browser_view), browser_frame_(browser_frame) { scoped_ptr<ui::ThemeProvider> theme_provider( new DesktopThemeProvider(ThemeServiceFactory::GetForProfile( browser_view->browser()->profile()))); browser_frame->SetThemeProvider(theme_provider.Pass()); } BrowserDesktopRootWindowHostWin::~BrowserDesktopRootWindowHostWin() { } views::NativeMenuWin* BrowserDesktopRootWindowHostWin::GetSystemMenu() { if (!system_menu_.get()) { SystemMenuInsertionDelegateWin insertion_delegate; system_menu_.reset( new views::NativeMenuWin(browser_frame_->GetSystemMenuModel(), GetHWND())); system_menu_->Rebuild(&insertion_delegate); } return system_menu_.get(); } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, BrowserDesktopRootWindowHost implementation: views::DesktopRootWindowHost* BrowserDesktopRootWindowHostWin::AsDesktopRootWindowHost() { return this; } int BrowserDesktopRootWindowHostWin::GetMinimizeButtonOffset() const { return minimize_button_metrics_.GetMinimizeButtonOffsetX(); } bool BrowserDesktopRootWindowHostWin::UsesNativeSystemMenu() const { return true; } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, views::DesktopRootWindowHostWin overrides: int BrowserDesktopRootWindowHostWin::GetInitialShowState() const { STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; GetStartupInfo(&si); return si.wShowWindow; } bool BrowserDesktopRootWindowHostWin::GetClientAreaInsets( gfx::Insets* insets) const { // Use the default client insets for an opaque frame or a glass popup/app // frame. if (!GetWidget()->ShouldUseNativeFrame() || !browser_view_->IsBrowserTypeNormal()) { return false; } int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); // In fullscreen mode, we have no frame. In restored mode, we draw our own // client edge over part of the default frame. if (GetWidget()->IsFullscreen()) border_thickness = 0; else if (!IsMaximized()) border_thickness -= kClientEdgeThickness; insets->Set(0, border_thickness, border_thickness, border_thickness); return true; } void BrowserDesktopRootWindowHostWin::HandleFrameChanged() { // We need to update the glass region on or off before the base class adjusts // the window region. UpdateDWMFrame(); DesktopRootWindowHostWin::HandleFrameChanged(); } bool BrowserDesktopRootWindowHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { switch (message) { case WM_ACTIVATE: if (LOWORD(w_param) != WA_INACTIVE) minimize_button_metrics_.OnHWNDActivated(); return false; case WM_ENDSESSION: browser::SessionEnding(); return true; case WM_INITMENUPOPUP: GetSystemMenu()->UpdateStates(); return true; } return DesktopRootWindowHostWin::PreHandleMSG( message, w_param, l_param, result); } void BrowserDesktopRootWindowHostWin::PostHandleMSG(UINT message, WPARAM w_param, LPARAM l_param) { switch (message) { case WM_CREATE: minimize_button_metrics_.Init(GetHWND()); break; case WM_WINDOWPOSCHANGED: UpdateDWMFrame(); // Windows lies to us about the position of the minimize button before a // window is visible. We use this position to place the OTR avatar in RTL // mode, so when the window is shown, we need to re-layout and schedule a // paint for the non-client frame view so that the icon top has the correct // position when the window becomes visible. This fixes bugs where the icon // appears to overlay the minimize button. // Note that we will call Layout every time SetWindowPos is called with // SWP_SHOWWINDOW, however callers typically are careful about not // specifying this flag unless necessary to avoid flicker. // This may be invoked during creation on XP and before the non_client_view // has been created. WINDOWPOS* window_pos = reinterpret_cast<WINDOWPOS*>(l_param); if (window_pos->flags & SWP_SHOWWINDOW && GetWidget()->non_client_view()) { GetWidget()->non_client_view()->Layout(); GetWidget()->non_client_view()->SchedulePaint(); } break; } } bool BrowserDesktopRootWindowHostWin::IsUsingCustomFrame() const { // App panel windows draw their own frame. if (browser_view_->IsPanel()) return true; // We don't theme popup or app windows, so regardless of whether or not a // theme is active for normal browser windows, we don't want to use the custom // frame for popups/apps. if (!browser_view_->IsBrowserTypeNormal() && !DesktopRootWindowHostWin::IsUsingCustomFrame()) { return false; } // Otherwise, we use the native frame when we're told we should by the theme // provider (e.g. no custom theme is active). return !GetWidget()->GetThemeProvider()->ShouldUseNativeFrame(); } bool BrowserDesktopRootWindowHostWin::ShouldUseNativeFrame() { if (!views::DesktopRootWindowHostWin::ShouldUseNativeFrame()) return false; // This function can get called when the Browser window is closed i.e. in the // context of the BrowserView destructor. if (!browser_view_->browser()) return false; return chrome::ShouldUseNativeFrame(browser_view_, GetWidget()->GetThemeProvider()); } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHostWin, private: void BrowserDesktopRootWindowHostWin::UpdateDWMFrame() { // For "normal" windows on Aero, we always need to reset the glass area // correctly, even if we're not currently showing the native frame (e.g. // because a theme is showing), so we explicitly check for that case rather // than checking browser_frame_->ShouldUseNativeFrame() here. Using that here // would mean we wouldn't reset the glass area to zero when moving from the // native frame to an opaque frame, leading to graphical glitches behind the // opaque frame. Instead, we use that function below to tell us whether the // frame is currently native or opaque. if (!GetWidget()->client_view() || !browser_view_->IsBrowserTypeNormal() || !DesktopRootWindowHostWin::ShouldUseNativeFrame()) return; MARGINS margins = { 0 }; // If the opaque frame is visible, we use the default (zero) margins. // Otherwise, we need to figure out how to extend the glass in. if (GetWidget()->ShouldUseNativeFrame()) { // In fullscreen mode, we don't extend glass into the client area at all, // because the GDI-drawn text in the web content composited over it will // become semi-transparent over any glass area. if (!IsMaximized() && !GetWidget()->IsFullscreen()) { margins.cxLeftWidth = kClientEdgeThickness + 1; margins.cxRightWidth = kClientEdgeThickness + 1; margins.cyBottomHeight = kClientEdgeThickness + 1; margins.cyTopHeight = kClientEdgeThickness + 1; } // In maximized mode, we only have a titlebar strip of glass, no side/bottom // borders. if (!browser_view_->IsFullscreen()) { gfx::Rect tabstrip_bounds( browser_frame_->GetBoundsForTabStrip(browser_view_->tabstrip())); margins.cyTopHeight = tabstrip_bounds.bottom() + kDWMFrameTopOffset; } } DwmExtendFrameIntoClientArea(GetHWND(), &margins); } //////////////////////////////////////////////////////////////////////////////// // BrowserDesktopRootWindowHost, public: // static BrowserDesktopRootWindowHost* BrowserDesktopRootWindowHost::CreateBrowserDesktopRootWindowHost( views::internal::NativeWidgetDelegate* native_widget_delegate, views::DesktopNativeWidgetAura* desktop_native_widget_aura, const gfx::Rect& initial_bounds, BrowserView* browser_view, BrowserFrame* browser_frame) { return new BrowserDesktopRootWindowHostWin(native_widget_delegate, desktop_native_widget_aura, initial_bounds, browser_view, browser_frame); } <|endoftext|>
<commit_before>#ifndef SUCCINCT_GRAPH_SG_HPP #define SUCCINCT_GRAPH_SG_HPP #include <iostream> #include <fstream> #include <map> #include <omp.h> #include "cpp/vg.pb.h" #include "sdsl/bit_vectors.hpp" #include "sdsl/enc_vector.hpp" #include "sdsl/dac_vector.hpp" #include "sdsl/vlc_vector.hpp" #include "sdsl/wavelet_trees.hpp" //#include "sdsl/csa_bitcompressed.hpp" #include "sdsl/csa_wt.hpp" #include "sdsl/suffix_arrays.hpp" #include "dynamic.hpp" namespace xg { using namespace std; using namespace sdsl; using namespace vg; class Traversal { public: int64_t id; bool rev; Traversal(int64_t i, bool r) : id(i), rev(r) { } }; class XGPath; typedef pair<int64_t, bool> Side; class XG { public: XG(void) : start_marker('#'), end_marker('$'), seq_length(0), node_count(0), edge_count(0), path_count(0) { } ~XG(void) { } XG(istream& in); XG(Graph& graph); void from_stream(istream& in, bool validate_graph = false, bool print_graph = false); void from_graph(Graph& graph, bool validate_graph = false, bool print_graph = false); void build(map<int64_t, string>& node_label, map<Side, set<Side> >& from_to, map<Side, set<Side> >& to_from, map<string, map<int, Mapping>>& path_nodes, bool validate_graph, bool print_graph); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* v = NULL, std::string name = ""); size_t seq_length; size_t node_count; size_t edge_count; size_t path_count; size_t id_to_rank(int64_t id) const; int64_t rank_to_id(size_t rank) const; size_t max_node_rank(void) const; Node node(int64_t id) const; // gets node sequence string node_sequence(int64_t id) const; vector<Edge> edges_of(int64_t id) const; vector<Edge> edges_to(int64_t id) const; vector<Edge> edges_from(int64_t id) const; vector<Edge> edges_on_start(int64_t id) const; vector<Edge> edges_on_end(int64_t id) const; size_t node_rank_as_entity(int64_t id) const; size_t edge_rank_as_entity(int64_t id1, bool from_start, int64_t id2, bool to_end) const; bool entity_is_node(size_t rank) const; size_t entity_rank_as_node_rank(size_t rank) const; bool has_edge(int64_t id1, bool is_start, int64_t id2, bool is_end) const; Path path(const string& name) const; size_t path_rank(const string& name) const; size_t max_path_rank(void) const; string path_name(size_t rank) const; vector<size_t> paths_of_entity(size_t rank) const; vector<size_t> paths_of_node(int64_t id) const; vector<size_t> paths_of_edge(int64_t id1, bool from_start, int64_t id2, bool to_end) const; map<string, vector<Mapping>> node_mappings(int64_t id) const; bool path_contains_node(const string& name, int64_t id) const; bool path_contains_edge(const string& name, int64_t id1, bool from_start, int64_t id2, bool to_end) const; bool path_contains_entity(const string& name, size_t rank) const; void add_paths_to_graph(map<int64_t, Node*>& nodes, Graph& g) const; size_t node_occs_in_path(int64_t id, const string& name) const; vector<size_t> node_ranks_in_path(int64_t id, const string& name) const; vector<size_t> node_positions_in_path(int64_t id, const string& name) const; int64_t node_at_path_position(const string& name, size_t pos) const; Mapping mapping_at_path_position(const string& name, size_t pos) const; size_t path_length(const string& name) const; void neighborhood(int64_t id, size_t steps, Graph& g) const; //void for_path_range(string& name, int64_t start, int64_t stop, function<void(Node)> lambda); void get_path_range(string& name, int64_t start, int64_t stop, Graph& g) const; // basic method to query regions of the graph // add_paths flag allows turning off the (potentially costly, and thread-locking) addition of paths // when these are not necessary void expand_context(Graph& g, size_t steps, bool add_paths = true) const; void get_connected_nodes(Graph& g) const; void get_id_range(int64_t id1, int64_t id2, Graph& g) const; // gPBWT interface // Insert a thread. Path name must be unique or empty. void insert_thread(const Path& t); // Read all the threads embedded in the graph. list<Path> extract_threads() const; // Extract a particular thread by name. Name may not be empty. Path extract_thread(const string& name) const; // Count matches to a subthread among embedded threads size_t count_matches(const Path& t) const; /** * Represents the search state for the graph PBWT, so that you can continue * a search with more of a thread, or backtrack. * * By default, represents an un-started search (with no first visited side) * that can be extended to the whole collection of visits to a side. */ struct ThreadSearchState { // What side have we just arrived at in the search? int64_t currentSide = 0; // What is the first visit at that side that is selected? int64_t rangeStart = 0; // And what is the past-the-last visit that is selected? int64_t rangeEnd = numeric_limits<int64_t>::max(); // How many visits are selected? inline int64_t count() { return rangeEnd - rangeStart; } // Return true if the range has nothing selected. inline bool isEmpty() { return rangeEnd <= rangeStart; } }; // Extend a search with the given section of a thread. void extend(ThreadSearchState& state, const Path& t) const; char start_marker; char end_marker; private: // sequence/integer vector int_vector<> s_iv; // node starts in sequence, provides id schema // rank_1(i) = id // select_1(id) = i bit_vector s_bv; // node positions in siv rank_support_v<1> s_bv_rank; bit_vector::select_1_type s_bv_select; // compressed version, unused... rrr_vector<> s_cbv; rrr_vector<>::rank_1_type s_cbv_rank; rrr_vector<>::select_1_type s_cbv_select; // maintain old ids from input, ranked as in s_iv and s_bv int_vector<> i_iv; int64_t min_id; // id ranges don't have to start at 0 int64_t max_id; int_vector<> r_iv; // ids-id_min is the rank // maintain forward links int_vector<> f_iv; bit_vector f_bv; rank_support_v<1> f_bv_rank; bit_vector::select_1_type f_bv_select; bit_vector f_from_start_bv; bit_vector f_to_end_bv; sd_vector<> f_from_start_cbv; sd_vector<> f_to_end_cbv; // and the same data in the reverse direction int_vector<> t_iv; bit_vector t_bv; rank_support_v<1> t_bv_rank; bit_vector::select_1_type t_bv_select; // these bit vectors are only used during construction // perhaps they should be moved? bit_vector t_from_start_bv; bit_vector t_to_end_bv; // used at runtime sd_vector<> t_from_start_cbv; sd_vector<> t_to_end_cbv; // edge table, allows o(1) determination of edge existence int_vector<> e_iv; //csa_wt<> e_csa; //csa_sada<> e_csa; // allows lookups of id->rank mapping //wt_int<> i_wt; // paths: serialized as bitvectors over nodes and edges int_vector<> pn_iv; // path names csa_wt<> pn_csa; // path name compressed suffix array bit_vector pn_bv; // path name starts in uncompressed version of csa rank_support_v<1> pn_bv_rank; bit_vector::select_1_type pn_bv_select; int_vector<> pi_iv; // path ids by rank in the path names // probably these should get compressed, for when we have whole genomes with many chromosomes // the growth in required memory is quadratic but the stored matrix is sparse vector<XGPath*> paths; // path entity membership // entity->path membership int_vector<> ep_iv; bit_vector ep_bv; // entity delimiters in ep_iv rank_support_v<1> ep_bv_rank; bit_vector::select_1_type ep_bv_select; // Succinct thread storage // Threads are haplotype paths in the graph with no edits allowed, starting // and stopping at node boundaries. // We keep our strings in this dynamic succinct rank-select string from DYNAMIC. using dynamic_int_vector = dyn::rle_str; // TODO: Explain the whole graph PBWT extension here // Basically we keep usage counts for every element in the graph, and and // array of next-node-start sides for each side in the graph. We number // sides as 2 * xg internal node ID, +1 if it's a right side. This leaves us // 0 and 1 free for representing the null destination side and to use as a // per-side array run separator, respectively. // This holds, for each node and edge (with indexes as in the entity vector // f_iv), the usage count (i.e. the number of times it is visited by encoded // threads). This doesn't have to be dynamic since the length will never // change. int_vector<> h_iv; // This holds the concatenated Benedict arrays (holding the next node's // entry side visited after the current entry side for the threads sorted in // reverse prefix lexicographic order). They are separated with 1s, with 0s // noting the null side (i.e. the thread ends at this node). dynamic_int_vector bs_iv; // We need the w function, which we call the "where_to" function. It tells // you, from a given visit at a given side, what visit offset if you go to // another side. int64_t where_to(int64_t current_side, int64_t visit_offset, int64_t new_side); }; class XGPath { public: XGPath(void) : member_count(0) { } ~XGPath(void) { } XGPath(const string& path_name, const vector<Mapping>& path, size_t entity_count, XG& graph, const map<int64_t, string>& node_label); string name; size_t member_count; sd_vector<> members; wt_int<> ids; sd_vector<> directions; // forward or backward through nodes int_vector<> positions; int_vector<> ranks; bit_vector offsets; rank_support_v<1> offsets_rank; bit_vector::select_1_type offsets_select; void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* v = NULL, std::string name = ""); Mapping mapping(size_t offset); // 0-based }; Mapping new_mapping(const string& name, int64_t id, size_t rank, bool is_reverse); void parse_region(const string& target, string& name, int64_t& start, int64_t& end); void to_text(ostream& out, Graph& graph); } #endif <commit_msg>Add a cache for thread start counts<commit_after>#ifndef SUCCINCT_GRAPH_SG_HPP #define SUCCINCT_GRAPH_SG_HPP #include <iostream> #include <fstream> #include <map> #include <omp.h> #include "cpp/vg.pb.h" #include "sdsl/bit_vectors.hpp" #include "sdsl/enc_vector.hpp" #include "sdsl/dac_vector.hpp" #include "sdsl/vlc_vector.hpp" #include "sdsl/wavelet_trees.hpp" //#include "sdsl/csa_bitcompressed.hpp" #include "sdsl/csa_wt.hpp" #include "sdsl/suffix_arrays.hpp" #include "dynamic.hpp" namespace xg { using namespace std; using namespace sdsl; using namespace vg; class Traversal { public: int64_t id; bool rev; Traversal(int64_t i, bool r) : id(i), rev(r) { } }; class XGPath; typedef pair<int64_t, bool> Side; class XG { public: XG(void) : start_marker('#'), end_marker('$'), seq_length(0), node_count(0), edge_count(0), path_count(0) { } ~XG(void) { } XG(istream& in); XG(Graph& graph); void from_stream(istream& in, bool validate_graph = false, bool print_graph = false); void from_graph(Graph& graph, bool validate_graph = false, bool print_graph = false); void build(map<int64_t, string>& node_label, map<Side, set<Side> >& from_to, map<Side, set<Side> >& to_from, map<string, map<int, Mapping>>& path_nodes, bool validate_graph, bool print_graph); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* v = NULL, std::string name = ""); size_t seq_length; size_t node_count; size_t edge_count; size_t path_count; size_t id_to_rank(int64_t id) const; int64_t rank_to_id(size_t rank) const; size_t max_node_rank(void) const; Node node(int64_t id) const; // gets node sequence string node_sequence(int64_t id) const; vector<Edge> edges_of(int64_t id) const; vector<Edge> edges_to(int64_t id) const; vector<Edge> edges_from(int64_t id) const; vector<Edge> edges_on_start(int64_t id) const; vector<Edge> edges_on_end(int64_t id) const; size_t node_rank_as_entity(int64_t id) const; size_t edge_rank_as_entity(int64_t id1, bool from_start, int64_t id2, bool to_end) const; bool entity_is_node(size_t rank) const; size_t entity_rank_as_node_rank(size_t rank) const; bool has_edge(int64_t id1, bool is_start, int64_t id2, bool is_end) const; Path path(const string& name) const; size_t path_rank(const string& name) const; size_t max_path_rank(void) const; string path_name(size_t rank) const; vector<size_t> paths_of_entity(size_t rank) const; vector<size_t> paths_of_node(int64_t id) const; vector<size_t> paths_of_edge(int64_t id1, bool from_start, int64_t id2, bool to_end) const; map<string, vector<Mapping>> node_mappings(int64_t id) const; bool path_contains_node(const string& name, int64_t id) const; bool path_contains_edge(const string& name, int64_t id1, bool from_start, int64_t id2, bool to_end) const; bool path_contains_entity(const string& name, size_t rank) const; void add_paths_to_graph(map<int64_t, Node*>& nodes, Graph& g) const; size_t node_occs_in_path(int64_t id, const string& name) const; vector<size_t> node_ranks_in_path(int64_t id, const string& name) const; vector<size_t> node_positions_in_path(int64_t id, const string& name) const; int64_t node_at_path_position(const string& name, size_t pos) const; Mapping mapping_at_path_position(const string& name, size_t pos) const; size_t path_length(const string& name) const; void neighborhood(int64_t id, size_t steps, Graph& g) const; //void for_path_range(string& name, int64_t start, int64_t stop, function<void(Node)> lambda); void get_path_range(string& name, int64_t start, int64_t stop, Graph& g) const; // basic method to query regions of the graph // add_paths flag allows turning off the (potentially costly, and thread-locking) addition of paths // when these are not necessary void expand_context(Graph& g, size_t steps, bool add_paths = true) const; void get_connected_nodes(Graph& g) const; void get_id_range(int64_t id1, int64_t id2, Graph& g) const; // gPBWT interface // Insert a thread. Path name must be unique or empty. void insert_thread(const Path& t); // Read all the threads embedded in the graph. list<Path> extract_threads() const; // Extract a particular thread by name. Name may not be empty. Path extract_thread(const string& name) const; // Count matches to a subthread among embedded threads size_t count_matches(const Path& t) const; /** * Represents the search state for the graph PBWT, so that you can continue * a search with more of a thread, or backtrack. * * By default, represents an un-started search (with no first visited side) * that can be extended to the whole collection of visits to a side. */ struct ThreadSearchState { // What side have we just arrived at in the search? int64_t currentSide = 0; // What is the first visit at that side that is selected? int64_t rangeStart = 0; // And what is the past-the-last visit that is selected? int64_t rangeEnd = numeric_limits<int64_t>::max(); // How many visits are selected? inline int64_t count() { return rangeEnd - rangeStart; } // Return true if the range has nothing selected. inline bool isEmpty() { return rangeEnd <= rangeStart; } }; // Extend a search with the given section of a thread. void extend(ThreadSearchState& state, const Path& t) const; char start_marker; char end_marker; private: // sequence/integer vector int_vector<> s_iv; // node starts in sequence, provides id schema // rank_1(i) = id // select_1(id) = i bit_vector s_bv; // node positions in siv rank_support_v<1> s_bv_rank; bit_vector::select_1_type s_bv_select; // compressed version, unused... rrr_vector<> s_cbv; rrr_vector<>::rank_1_type s_cbv_rank; rrr_vector<>::select_1_type s_cbv_select; // maintain old ids from input, ranked as in s_iv and s_bv int_vector<> i_iv; int64_t min_id; // id ranges don't have to start at 0 int64_t max_id; int_vector<> r_iv; // ids-id_min is the rank // maintain forward links int_vector<> f_iv; bit_vector f_bv; rank_support_v<1> f_bv_rank; bit_vector::select_1_type f_bv_select; bit_vector f_from_start_bv; bit_vector f_to_end_bv; sd_vector<> f_from_start_cbv; sd_vector<> f_to_end_cbv; // and the same data in the reverse direction int_vector<> t_iv; bit_vector t_bv; rank_support_v<1> t_bv_rank; bit_vector::select_1_type t_bv_select; // these bit vectors are only used during construction // perhaps they should be moved? bit_vector t_from_start_bv; bit_vector t_to_end_bv; // used at runtime sd_vector<> t_from_start_cbv; sd_vector<> t_to_end_cbv; // edge table, allows o(1) determination of edge existence int_vector<> e_iv; //csa_wt<> e_csa; //csa_sada<> e_csa; // allows lookups of id->rank mapping //wt_int<> i_wt; // paths: serialized as bitvectors over nodes and edges int_vector<> pn_iv; // path names csa_wt<> pn_csa; // path name compressed suffix array bit_vector pn_bv; // path name starts in uncompressed version of csa rank_support_v<1> pn_bv_rank; bit_vector::select_1_type pn_bv_select; int_vector<> pi_iv; // path ids by rank in the path names // probably these should get compressed, for when we have whole genomes with many chromosomes // the growth in required memory is quadratic but the stored matrix is sparse vector<XGPath*> paths; // path entity membership // entity->path membership int_vector<> ep_iv; bit_vector ep_bv; // entity delimiters in ep_iv rank_support_v<1> ep_bv_rank; bit_vector::select_1_type ep_bv_select; // Succinct thread storage // Threads are haplotype paths in the graph with no edits allowed, starting // and stopping at node boundaries. // We keep our strings in this dynamic succinct rank-select string from DYNAMIC. using dynamic_int_vector = dyn::rle_str; // TODO: Explain the whole graph PBWT extension here // Basically we keep usage counts for every element in the graph, and and // array of next-node-start sides for each side in the graph. We number // sides as 2 * xg internal node ID, +1 if it's a right side. This leaves us // 0 and 1 free for representing the null destination side and to use as a // per-side array run separator, respectively. // This holds, for each node and edge (with indexes as in the entity vector // f_iv), the usage count (i.e. the number of times it is visited by encoded // threads). This doesn't have to be dynamic since the length will never // change. int_vector<> h_iv; // This (as an extension to the algorithm described in the paper) holds the // number of threads beginning at each node. This isn't any extra // information relative to what's in the usage count array, but it's cheaper // (probably) to maintain this rather than to scan through all the edges on // a side every time. // ts stands for "thread start" int_vector<> ts_iv; // This holds the concatenated Benedict arrays (holding the next node's // entry side visited after the current entry side for the threads sorted in // reverse prefix lexicographic order). They are separated with 1s, with 0s // noting the null side (i.e. the thread ends at this node). dynamic_int_vector bs_iv; // We need the w function, which we call the "where_to" function. It tells // you, from a given visit at a given side, what visit offset if you go to // another side. int64_t where_to(int64_t current_side, int64_t visit_offset, int64_t new_side); }; class XGPath { public: XGPath(void) : member_count(0) { } ~XGPath(void) { } XGPath(const string& path_name, const vector<Mapping>& path, size_t entity_count, XG& graph, const map<int64_t, string>& node_label); string name; size_t member_count; sd_vector<> members; wt_int<> ids; sd_vector<> directions; // forward or backward through nodes int_vector<> positions; int_vector<> ranks; bit_vector offsets; rank_support_v<1> offsets_rank; bit_vector::select_1_type offsets_select; void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* v = NULL, std::string name = ""); Mapping mapping(size_t offset); // 0-based }; Mapping new_mapping(const string& name, int64_t id, size_t rank, bool is_reverse); void parse_region(const string& target, string& name, int64_t& start, int64_t& end); void to_text(ostream& out, Graph& graph); } #endif <|endoftext|>
<commit_before>/* * Copyright 2016 Nu-book Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ReadBarcode.h" #include "TextUtfEncoding.h" #include "ZXNumeric.h" #include <iostream> #include <cstring> #include <string> #include <algorithm> #include <cctype> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" using namespace ZXing; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-fast] [-rotate] [-format <FORMAT[,...]>] <png image path>\n" << " -fast Skip some lines/pixels during detection\n" << " -rotate Also try rotated image during detection\n" << " -format Only detect given format(s)\n" << " -ispure Assume the image contains only a 'pure'/perfect code\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without underscore, separated by ',', '|' and/or ' '\n"; } static bool ParseOptions(int argc, char* argv[], DecodeHints* hints, std::string* filePath) { hints->setTryHarder(true); for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-fast") == 0) { hints->setTryHarder(false); } else if (strcmp(argv[i], "-rotate") == 0) { hints->setTryRotate(true); } else if (strcmp(argv[i], "-ispure") == 0) { hints->setIsPure(true); hints->setBinarizer(Binarizer::FixedThreshold); } else if (strcmp(argv[i], "-format") == 0) { if (++i == argc) return false; try { hints->setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else { *filePath = argv[i]; } } return !filePath->empty(); } std::ostream& operator<<(std::ostream& os, const Position& points) { for (const auto& p : points) os << p.x << "x" << p.y << " "; return os; } int main(int argc, char* argv[]) { DecodeHints hints; std::string filePath; if (!ParseOptions(argc, argv, &hints, &filePath)) { PrintUsage(argv[0]); return -1; } int width, height, channels; std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << "\n"; return -1; } auto result = ReadBarcode({buffer.get(), width, height, ImageFormat::RGBX}, hints); std::cout << "Text: \"" << TextUtfEncoding::ToUtf8(result.text()) << "\"\n" << "Format: " << ToString(result.format()) << "\n" << "Position: " << result.position() << "\n" << "Rotation: " << std::lround(result.position().rotation() * kDegPerRad) << "\n" << "Error: " << ToString(result.status()) << "\n"; auto errLevel = result.metadata().getString(ResultMetadata::Key::ERROR_CORRECTION_LEVEL); if (!errLevel.empty()) { std::cout << "EC Level: " << TextUtfEncoding::ToUtf8(errLevel) << "\n"; } return static_cast<int>(result.status()); } <commit_msg>ZXingReader: output more metadata<commit_after>/* * Copyright 2016 Nu-book Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ReadBarcode.h" #include "TextUtfEncoding.h" #include "ZXNumeric.h" #include <iostream> #include <cstring> #include <string> #include <algorithm> #include <cctype> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" using namespace ZXing; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-fast] [-rotate] [-format <FORMAT[,...]>] <png image path>\n" << " -fast Skip some lines/pixels during detection\n" << " -rotate Also try rotated image during detection\n" << " -format Only detect given format(s)\n" << " -ispure Assume the image contains only a 'pure'/perfect code\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without underscore, separated by ',', '|' and/or ' '\n"; } static bool ParseOptions(int argc, char* argv[], DecodeHints* hints, std::string* filePath) { hints->setTryHarder(true); for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-fast") == 0) { hints->setTryHarder(false); } else if (strcmp(argv[i], "-rotate") == 0) { hints->setTryRotate(true); } else if (strcmp(argv[i], "-ispure") == 0) { hints->setIsPure(true); hints->setBinarizer(Binarizer::FixedThreshold); } else if (strcmp(argv[i], "-format") == 0) { if (++i == argc) return false; try { hints->setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else { *filePath = argv[i]; } } return !filePath->empty(); } std::ostream& operator<<(std::ostream& os, const Position& points) { for (const auto& p : points) os << p.x << "x" << p.y << " "; return os; } int main(int argc, char* argv[]) { DecodeHints hints; std::string filePath; if (!ParseOptions(argc, argv, &hints, &filePath)) { PrintUsage(argv[0]); return -1; } int width, height, channels; std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << "\n"; return -1; } auto result = ReadBarcode({buffer.get(), width, height, ImageFormat::RGBX}, hints); std::cout << "Text: \"" << TextUtfEncoding::ToUtf8(result.text()) << "\"\n" << "Format: " << ToString(result.format()) << "\n" << "Position: " << result.position() << "\n" << "Rotation: " << std::lround(result.position().rotation() * kDegPerRad) << "\n" << "Error: " << ToString(result.status()) << "\n"; std::map<ResultMetadata::Key, const char*> keys = {{ResultMetadata::ERROR_CORRECTION_LEVEL, "EC Level: "}, {ResultMetadata::SUGGESTED_PRICE, "Price: "}, {ResultMetadata::ISSUE_NUMBER, "Issue # "}, {ResultMetadata::UPC_EAN_EXTENSION, "Extension:"}}; for (auto key : keys) { auto value = TextUtfEncoding::ToUtf8(result.metadata().getString(key.first)); if (value.size()) std::cout << key.second << value << "\n"; } return static_cast<int>(result.status()); } <|endoftext|>
<commit_before>// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "common.h" #include "sal.h" #include "gcenv.structs.h" #include "gcenv.base.h" #include <stdlib.h> #pragma warning(disable:4297) extern "C" Object * RhNewObject(MethodTable * pMT); extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements); extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT); extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT); extern "C" void RhpStelemRef(void * pArray, int index, void * pObj); extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT); extern "C" __declspec(noreturn) void RhpThrowEx(void * pEx); #ifdef CPPCODEGEN extern "C" Object * __allocate_object(MethodTable * pMT) { return RhNewObject(pMT); } extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT) { return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch } extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_CheckCast(obj, pTargetMT); } extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT); } extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj) { RhpStelemRef(pArray, idx, obj); } extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type) { return RhpLdelemaRef(pArray, idx, type); } extern "C" void __throw_exception(void * pEx) { RhpThrowEx(pEx); } void __range_check_fail() { throw "ThrowRangeOverflowException"; } #endif // CPPCODEGEN extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame); extern "C" void RhpReversePInvokeReturn(ReversePInvokeFrame* pRevFrame); extern "C" int32_t RhpEnableConservativeStackReporting(); extern "C" void RhpRegisterSimpleModule(SimpleModuleHeader* pModule); extern "C" void * RhpHandleAlloc(void * pObject, int handleType); #define DLL_PROCESS_ATTACH 1 extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved); #include "platform.h" int __initialize_runtime() { RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL); RhpEnableConservativeStackReporting(); return 0; } void __shutdown_runtime() { } void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame) { RhpReversePInvoke2(pRevFrame); } void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame) { RhpReversePInvokeReturn(pRevFrame); } void __register_module(SimpleModuleHeader* pModule) { RhpRegisterSimpleModule(pModule); } namespace System_Private_CoreLib { namespace System { class Object { public: MethodTable * get_EEType() { return *(MethodTable **)this; } }; class Array : public Object { public: int32_t GetArrayLength() { return *(int32_t *)((void **)this + 1); } void * GetArrayData() { return (void **)this + 2; } }; class String : public Object { public: static MethodTable * __getMethodTable(); }; class String__Array : public Object { public: static MethodTable * __getMethodTable(); }; class EETypePtr { public: intptr_t m_value; }; }; }; using namespace System_Private_CoreLib; extern "C" void __EEType_System_Private_CoreLib_System_String(); extern "C" void __EEType_System_Private_CoreLib_System_String__Array(); Object * __allocate_string(int32_t len) { #ifdef CPPCODEGEN return RhNewArray(System::String::__getMethodTable(), len); #else return RhNewArray((MethodTable*)__EEType_System_Private_CoreLib_System_String, len); #endif } void PrintStringObject(System::String *pStringToPrint) { // Get the number of characters in managed string (stored as UTF16) int32_t length = *((int32_t*)((char*)(pStringToPrint)+sizeof(intptr_t))); // Get the pointer to the start of the character array uint16_t *pString = (uint16_t*)((char*)(pStringToPrint)+sizeof(intptr_t) + sizeof(int32_t)); // Loop to display the string int32_t index = 0; while (index < length) { putwchar(*pString); pString++; index++; } } extern "C" void __not_yet_implemented(System::String * pMethodName, System::String * pMessage) { printf("ILCompiler failed generating code for this method; execution cannot continue.\n"); printf("This is likely because of a feature that is not yet implemented in the compiler.\n"); printf("Method: "); PrintStringObject(pMethodName); printf("\n\n"); printf("Reason: "); PrintStringObject(pMessage); printf("\n"); exit(-1); } extern "C" void __fail_fast() { // TODO: FailFast throw "__fail_fast"; } Object * __load_string_literal(const char * string) { // TODO: Cache/intern string literals // TODO: Unicode string literals size_t len = strlen(string); Object * pString = __allocate_string((int32_t)len); uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t)); for (size_t i = 0; i < len; i++) p[i] = string[i]; return pString; } extern "C" void RhGetCurrentThreadStackTrace() { throw "RhGetCurrentThreadStackTrace"; } extern "C" void RhCollect() { throw "RhCollect"; } extern "C" void RhpCallCatchFunclet() { throw "RhpCallCatchFunclet"; } extern "C" void RhpCallFilterFunclet() { throw "RhpCallFilterFunclet"; } extern "C" void RhpCallFinallyFunclet() { throw "RhpCallFinallyFunclet"; } extern "C" void RhpUniversalTransition() { throw "RhpUniversalTransition"; } extern "C" void RhpFailFastForPInvokeExceptionPreemp() { throw "RhpFailFastForPInvokeExceptionPreemp"; } extern "C" void RhpThrowEx(void * pEx) { throw "RhpThrowEx"; } extern "C" void RhpThrowHwEx() { throw "RhpThrowHwEx"; } extern "C" void RhpEtwExceptionThrown() { throw "RhpEtwExceptionThrown"; } extern "C" void RhReRegisterForFinalize() { throw "RhReRegisterForFinalize"; } extern "C" void * g_pDispatchMapTemporaryWorkaround; void * g_pDispatchMapTemporaryWorkaround; extern "C" void __StringTableStart(); extern "C" void __StringTableEnd(); extern "C" void* GetModuleSection(int id, int* length) { struct ModuleSectionSymbol { void* symbolId; size_t length; }; // TODO: emit this table from the compiler per module. // !!! // The order should be kept in sync with ModuleSectionIds in StartupCodeHelpers.cs in CoreLib. static ModuleSectionSymbol symbols[] = { #ifdef CPPCODEGEN { System::String::__getMethodTable(), sizeof(void*) }, { nullptr, 0 }, #else { __EEType_System_Private_CoreLib_System_String, sizeof(void*) }, { __StringTableStart, (uint8_t*)__StringTableEnd - (uint8_t*)__StringTableStart }, #endif }; *length = (int) symbols[id].length; return symbols[id].symbolId; } #ifndef CPPCODEGEN SimpleModuleHeader __module = { NULL, NULL /* &__gcStatics, &__gcStaticsDescs */ }; extern "C" void* __InterfaceDispatchMapTable; extern "C" void* __GCStaticRegionStart; extern "C" void* __GCStaticRegionEnd; int __statics_fixup() { for (void** currentBlock = &__GCStaticRegionStart; currentBlock < &__GCStaticRegionEnd; currentBlock++) { Object* gcBlock = RhNewObject((MethodTable*)*currentBlock); // TODO: OOM handling *currentBlock = RhpHandleAlloc(gcBlock, 2 /* Normal */); } return 0; } #if defined(_WIN32) extern "C" int __managed__Main(int argc, char* argv[]); // TODO: Use wchar_t int main(int argc, char* argv[]) // TODO: Use wmain and wchar_t #else extern "C" int __managed__Main(int argc, char* argv[]); int main(int argc, char* argv[]) #endif { if (__initialize_runtime() != 0) return -1; __register_module(&__module); g_pDispatchMapTemporaryWorkaround = (void*)&__InterfaceDispatchMapTable; ReversePInvokeFrame frame; __reverse_pinvoke(&frame); if (__statics_fixup() != 0) return -1; int retval; try { // Managed apps don't see the first args argument (full path of executable) so skip it assert(argc > 0); retval = __managed__Main(argc, argv); } catch (const char* &e) { printf("Call to an unimplemented runtime method; execution cannot continue.\n"); printf("Method: %s\n", e); retval = -1; } __reverse_pinvoke_return(&frame); __shutdown_runtime(); return retval; } #endif // !CPPCODEGEN <commit_msg>Fix for data declaration<commit_after>// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "common.h" #include "sal.h" #include "gcenv.structs.h" #include "gcenv.base.h" #include <stdlib.h> #pragma warning(disable:4297) extern "C" Object * RhNewObject(MethodTable * pMT); extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements); extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT); extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT); extern "C" void RhpStelemRef(void * pArray, int index, void * pObj); extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT); extern "C" __declspec(noreturn) void RhpThrowEx(void * pEx); #ifdef CPPCODEGEN extern "C" Object * __allocate_object(MethodTable * pMT) { return RhNewObject(pMT); } extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT) { return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch } extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_CheckCast(obj, pTargetMT); } extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT) { return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT); } extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj) { RhpStelemRef(pArray, idx, obj); } extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type) { return RhpLdelemaRef(pArray, idx, type); } extern "C" void __throw_exception(void * pEx) { RhpThrowEx(pEx); } void __range_check_fail() { throw "ThrowRangeOverflowException"; } #endif // CPPCODEGEN extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame); extern "C" void RhpReversePInvokeReturn(ReversePInvokeFrame* pRevFrame); extern "C" int32_t RhpEnableConservativeStackReporting(); extern "C" void RhpRegisterSimpleModule(SimpleModuleHeader* pModule); extern "C" void * RhpHandleAlloc(void * pObject, int handleType); #define DLL_PROCESS_ATTACH 1 extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved); #include "platform.h" int __initialize_runtime() { RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL); RhpEnableConservativeStackReporting(); return 0; } void __shutdown_runtime() { } void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame) { RhpReversePInvoke2(pRevFrame); } void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame) { RhpReversePInvokeReturn(pRevFrame); } void __register_module(SimpleModuleHeader* pModule) { RhpRegisterSimpleModule(pModule); } namespace System_Private_CoreLib { namespace System { class Object { public: MethodTable * get_EEType() { return *(MethodTable **)this; } }; class Array : public Object { public: int32_t GetArrayLength() { return *(int32_t *)((void **)this + 1); } void * GetArrayData() { return (void **)this + 2; } }; class String : public Object { public: static MethodTable * __getMethodTable(); }; class String__Array : public Object { public: static MethodTable * __getMethodTable(); }; class EETypePtr { public: intptr_t m_value; }; }; }; using namespace System_Private_CoreLib; extern "C" void* __EEType_System_Private_CoreLib_System_String; Object * __allocate_string(int32_t len) { #ifdef CPPCODEGEN return RhNewArray(System::String::__getMethodTable(), len); #else return RhNewArray((MethodTable*)__EEType_System_Private_CoreLib_System_String, len); #endif } void PrintStringObject(System::String *pStringToPrint) { // Get the number of characters in managed string (stored as UTF16) int32_t length = *((int32_t*)((char*)(pStringToPrint)+sizeof(intptr_t))); // Get the pointer to the start of the character array uint16_t *pString = (uint16_t*)((char*)(pStringToPrint)+sizeof(intptr_t) + sizeof(int32_t)); // Loop to display the string int32_t index = 0; while (index < length) { putwchar(*pString); pString++; index++; } } extern "C" void __not_yet_implemented(System::String * pMethodName, System::String * pMessage) { printf("ILCompiler failed generating code for this method; execution cannot continue.\n"); printf("This is likely because of a feature that is not yet implemented in the compiler.\n"); printf("Method: "); PrintStringObject(pMethodName); printf("\n\n"); printf("Reason: "); PrintStringObject(pMessage); printf("\n"); exit(-1); } extern "C" void __fail_fast() { // TODO: FailFast throw "__fail_fast"; } Object * __load_string_literal(const char * string) { // TODO: Cache/intern string literals // TODO: Unicode string literals size_t len = strlen(string); Object * pString = __allocate_string((int32_t)len); uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t)); for (size_t i = 0; i < len; i++) p[i] = string[i]; return pString; } extern "C" void RhGetCurrentThreadStackTrace() { throw "RhGetCurrentThreadStackTrace"; } extern "C" void RhCollect() { throw "RhCollect"; } extern "C" void RhpCallCatchFunclet() { throw "RhpCallCatchFunclet"; } extern "C" void RhpCallFilterFunclet() { throw "RhpCallFilterFunclet"; } extern "C" void RhpCallFinallyFunclet() { throw "RhpCallFinallyFunclet"; } extern "C" void RhpUniversalTransition() { throw "RhpUniversalTransition"; } extern "C" void RhpFailFastForPInvokeExceptionPreemp() { throw "RhpFailFastForPInvokeExceptionPreemp"; } extern "C" void RhpThrowEx(void * pEx) { throw "RhpThrowEx"; } extern "C" void RhpThrowHwEx() { throw "RhpThrowHwEx"; } extern "C" void RhpEtwExceptionThrown() { throw "RhpEtwExceptionThrown"; } extern "C" void RhReRegisterForFinalize() { throw "RhReRegisterForFinalize"; } extern "C" void * g_pDispatchMapTemporaryWorkaround; void * g_pDispatchMapTemporaryWorkaround; extern "C" void* __StringTableStart; extern "C" void* __StringTableEnd; extern "C" void* GetModuleSection(int id, int* length) { struct ModuleSectionSymbol { void* symbolId; size_t length; }; // TODO: emit this table from the compiler per module. // !!! // The order should be kept in sync with ModuleSectionIds in StartupCodeHelpers.cs in CoreLib. static ModuleSectionSymbol symbols[] = { #ifdef CPPCODEGEN { System::String::__getMethodTable(), sizeof(void*) }, { nullptr, 0 }, #else { &__EEType_System_Private_CoreLib_System_String, sizeof(void*) }, { &__StringTableStart, (uint8_t*)&__StringTableEnd - (uint8_t*)&__StringTableStart }, #endif }; *length = (int) symbols[id].length; return symbols[id].symbolId; } #ifndef CPPCODEGEN SimpleModuleHeader __module = { NULL, NULL /* &__gcStatics, &__gcStaticsDescs */ }; extern "C" void* __InterfaceDispatchMapTable; extern "C" void* __GCStaticRegionStart; extern "C" void* __GCStaticRegionEnd; int __statics_fixup() { for (void** currentBlock = &__GCStaticRegionStart; currentBlock < &__GCStaticRegionEnd; currentBlock++) { Object* gcBlock = RhNewObject((MethodTable*)*currentBlock); // TODO: OOM handling *currentBlock = RhpHandleAlloc(gcBlock, 2 /* Normal */); } return 0; } #if defined(_WIN32) extern "C" int __managed__Main(int argc, char* argv[]); // TODO: Use wchar_t int main(int argc, char* argv[]) // TODO: Use wmain and wchar_t #else extern "C" int __managed__Main(int argc, char* argv[]); int main(int argc, char* argv[]) #endif { if (__initialize_runtime() != 0) return -1; __register_module(&__module); g_pDispatchMapTemporaryWorkaround = (void*)&__InterfaceDispatchMapTable; ReversePInvokeFrame frame; __reverse_pinvoke(&frame); if (__statics_fixup() != 0) return -1; int retval; try { // Managed apps don't see the first args argument (full path of executable) so skip it assert(argc > 0); retval = __managed__Main(argc, argv); } catch (const char* &e) { printf("Call to an unimplemented runtime method; execution cannot continue.\n"); printf("Method: %s\n", e); retval = -1; } __reverse_pinvoke_return(&frame); __shutdown_runtime(); return retval; } #endif // !CPPCODEGEN <|endoftext|>
<commit_before>/** * Copyright 2013 Truphone */ #include "include/KeyCommand.h" #include <bb/cascades/AbstractTextControl> #include <bb/cascades/Application> #include <bb/cascades/Control> #include "Utils.h" #include "Connection.h" using bb::cascades::AbstractTextControl; using bb::cascades::Application; using bb::cascades::Control; namespace truphone { namespace test { namespace cascades { const QString KeyCommand::CMD_NAME = "key"; KeyCommand::KeyCommand(Connection * const socket, QObject * parent) : Command(parent), client(socket) { } KeyCommand::~KeyCommand() { } bool KeyCommand::executeCommand(QStringList * const arguments) { bool ret = false; int theKey = 0, isPressed = 0, isAlt = 0, isShift = 0, isCtrl = 0, processed = 0; QString target; for (int param = 0 ; param < 6 ; param++) { bool ok = false; switch (param) { case 0: theKey = QString(arguments->first()).toInt(&ok); break; case 1: isPressed = QString(arguments->first()).toInt(&ok); break; case 2: isAlt = QString(arguments->first()).toInt(&ok); break; case 3: isShift = QString(arguments->first()).toInt(&ok); break; case 4: isCtrl = QString(arguments->first()).toInt(&ok); break; case 5: target = arguments->first(); ok = not target.isNull() and not target.isEmpty(); break; default: break; } if (ok) { processed++; } arguments->removeFirst(); } Q_UNUSED(isAlt); Q_UNUSED(isShift); Q_UNUSED(isCtrl); if (processed not_eq 6) // 6 items are expected { this->client->write(tr("ERROR: wrong number of arguments to key command") + "\r\n"); } else { QObject * const targetObject = Utils::findObject(target); if (not targetObject) { this->client->write(tr("ERROR: Couldn't find the target of the keypress") + "\r\n"); } else { Control * const ctrl = qobject_cast<Control*>(targetObject); if (ctrl) { if (not ctrl->isFocused()) { ctrl->requestFocus(); } AbstractTextControl * const field = qobject_cast<AbstractTextControl*>(ctrl); if (field) { if (isPressed) { if (theKey >= ' ' and theKey <= 'z') { field->setProperty("text", QVariant(field->property("text").toString() + QChar(theKey))); } else { switch (theKey) { case '\b': field->setText(field->text().left( field->text().length()-1)); break; /* might need some extra special cases here later */ default: /* dropped */ break; } } } ret = true; } else { // for propogation (parents might not understand it, thats fine) ret = true; } } else { // for propogation (parents might not understand it, thats fine) ret = true; } } } return ret; } void KeyCommand::showHelp() { this->client->write(tr("> key <code> <pressed> <alt> <shift> <ctrl> <target>") + "\r\n"); this->client->write(tr("Simulate a key press") + "\r\n"); } } // namespace cascades } // namespace test } // namespace truphone <commit_msg>Fix for invalid arguments on the Key command.<commit_after>/** * Copyright 2013 Truphone */ #include "include/KeyCommand.h" #include <bb/cascades/AbstractTextControl> #include <bb/cascades/Application> #include <bb/cascades/Control> #include "Utils.h" #include "Connection.h" using bb::cascades::AbstractTextControl; using bb::cascades::Application; using bb::cascades::Control; namespace truphone { namespace test { namespace cascades { const QString KeyCommand::CMD_NAME = "key"; KeyCommand::KeyCommand(Connection * const socket, QObject * parent) : Command(parent), client(socket) { } KeyCommand::~KeyCommand() { } bool KeyCommand::executeCommand(QStringList * const arguments) { bool ret = false; int theKey = 0, isPressed = 0, isAlt = 0, isShift = 0, isCtrl = 0, processed = 0; QString target; for (int param = 0 ; param < 6 ; param++) { if (not arguments->isEmpty()) { bool ok = false; switch (param) { case 0: theKey = QString(arguments->first()).toInt(&ok); break; case 1: isPressed = QString(arguments->first()).toInt(&ok); break; case 2: isAlt = QString(arguments->first()).toInt(&ok); break; case 3: isShift = QString(arguments->first()).toInt(&ok); break; case 4: isCtrl = QString(arguments->first()).toInt(&ok); break; case 5: target = arguments->first(); ok = not target.isNull() and not target.isEmpty(); break; default: break; } if (ok) { processed++; } arguments->removeFirst(); } } Q_UNUSED(isAlt); Q_UNUSED(isShift); Q_UNUSED(isCtrl); if (processed not_eq 6) // 6 items are expected { this->client->write(tr("ERROR: wrong number of arguments to key command") + "\r\n"); } else { QObject * const targetObject = Utils::findObject(target); if (not targetObject) { this->client->write(tr("ERROR: Couldn't find the target of the keypress") + "\r\n"); } else { Control * const ctrl = qobject_cast<Control*>(targetObject); if (ctrl) { if (not ctrl->isFocused()) { ctrl->requestFocus(); } AbstractTextControl * const field = qobject_cast<AbstractTextControl*>(ctrl); if (field) { if (isPressed) { if (theKey >= ' ' and theKey <= 'z') { field->setProperty("text", QVariant(field->property("text").toString() + QChar(theKey))); } else { switch (theKey) { case '\b': field->setText(field->text().left( field->text().length()-1)); break; /* might need some extra special cases here later */ default: /* dropped */ break; } } } ret = true; } else { // for propogation (parents might not understand it, thats fine) ret = true; } } else { // for propogation (parents might not understand it, thats fine) ret = true; } } } return ret; } void KeyCommand::showHelp() { this->client->write(tr("> key <code> <pressed> <alt> <shift> <ctrl> <target>") + "\r\n"); this->client->write(tr("Simulate a key press") + "\r\n"); } } // namespace cascades } // namespace test } // namespace truphone <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querydescriptor.cxx,v $ * * $Revision: 1.31 $ * * last change: $Author: vg $ $Date: 2006-11-23 14:19:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBA_COREAPI_QUERYDESCRIPTOR_HXX_ #include "querydescriptor.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::util; using namespace ::comphelper; using namespace ::osl; using namespace ::cppu; //........................................................................ namespace dbaccess { //........................................................................ //========================================================================== //= OQueryDescriptor //========================================================================== DBG_NAME(OQueryDescriptor) //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor() :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const Reference< XPropertySet >& _rxCommandDefinition) :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); osl_incrementInterlockedCount(&m_refCount); OSL_ENSURE(_rxCommandDefinition.is(), "OQueryDescriptor_Base::OQueryDescriptor_Base : invalid source property set !"); try { ::comphelper::copyProperties(_rxCommandDefinition,this); } catch(Exception&) { OSL_ENSURE(sal_False, "OQueryDescriptor_Base::OQueryDescriptor_Base: caught an exception!"); } osl_decrementInterlockedCount(&m_refCount); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const OQueryDescriptor_Base& _rSource) :OQueryDescriptor_Base(_rSource,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } // ----------------------------------------------------------------------------- IMPLEMENT_TYPEPROVIDER2(OQueryDescriptor,OQueryDescriptor_Base,ODataSettings); IMPLEMENT_FORWARD_XINTERFACE3( OQueryDescriptor,OWeakObject,OQueryDescriptor_Base,ODataSettings) //-------------------------------------------------------------------------- void OQueryDescriptor::registerProperties() { // the properties which OCommandBase supplies (it has no own registration, as it's not derived from // a OPropertyStateContainer) registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND|PropertyAttribute::CONSTRAINED, &m_sElementName, ::getCppuType(&m_sElementName)); registerProperty(PROPERTY_COMMAND, PROPERTY_ID_COMMAND, PropertyAttribute::BOUND, &m_sCommand, ::getCppuType(&m_sCommand)); registerProperty(PROPERTY_USE_ESCAPE_PROCESSING, PROPERTY_ID_USE_ESCAPE_PROCESSING, PropertyAttribute::BOUND, &m_bEscapeProcessing, ::getBooleanCppuType()); registerProperty(PROPERTY_UPDATE_TABLENAME, PROPERTY_ID_UPDATE_TABLENAME, PropertyAttribute::BOUND, &m_sUpdateTableName, ::getCppuType(&m_sUpdateTableName)); registerProperty(PROPERTY_UPDATE_SCHEMANAME, PROPERTY_ID_UPDATE_SCHEMANAME, PropertyAttribute::BOUND, &m_sUpdateSchemaName, ::getCppuType(&m_sUpdateSchemaName)); registerProperty(PROPERTY_UPDATE_CATALOGNAME, PROPERTY_ID_UPDATE_CATALOGNAME, PropertyAttribute::BOUND, &m_sUpdateCatalogName, ::getCppuType(&m_sUpdateCatalogName)); registerProperty(PROPERTY_LAYOUTINFORMATION, PROPERTY_ID_LAYOUTINFORMATION, PropertyAttribute::BOUND, &m_aLayoutInformation, ::getCppuType(&m_aLayoutInformation)); } // ----------------------------------------------------------------------------- //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OQueryDescriptor::getPropertySetInfo( ) throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ) ; } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OQueryDescriptor::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OQueryDescriptor::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new ::cppu::OPropertyArrayHelper(aProps); } // ----------------------------------------------------------------------------- DBG_NAME(OQueryDescriptor_Base); //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(::osl::Mutex& _rMutex,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); } //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(const OQueryDescriptor_Base& _rSource,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rSource.m_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); m_sCommand = _rSource.m_sCommand; m_bEscapeProcessing = _rSource.m_bEscapeProcessing; m_sUpdateTableName = _rSource.m_sUpdateTableName; m_sUpdateSchemaName = _rSource.m_sUpdateSchemaName; m_sUpdateCatalogName = _rSource.m_sUpdateCatalogName; m_aLayoutInformation = _rSource.m_aLayoutInformation; } //-------------------------------------------------------------------------- OQueryDescriptor_Base::~OQueryDescriptor_Base() { m_pColumns->acquire(); m_pColumns->disposing(); delete m_pColumns; DBG_DTOR(OQueryDescriptor_Base,NULL); } // ----------------------------------------------------------------------------- sal_Int64 SAL_CALL OQueryDescriptor_Base::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) throw(RuntimeException) { if (_rIdentifier.getLength() != 16) return 0; if (0 == rtl_compareMemory(getImplementationId().getConstArray(), _rIdentifier.getConstArray(), 16 ) ) return reinterpret_cast<sal_Int64>(this); return 0; } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OQueryDescriptor_Base) //-------------------------------------------------------------------------- void OQueryDescriptor_Base::setColumnsOutOfDate( sal_Bool _bOutOfDate ) { m_bColumnsOutOfDate = _bOutOfDate; if ( !m_bColumnsOutOfDate ) m_pColumns->setInitialized(); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::implAppendColumn( const ::rtl::OUString& _rName, OColumn* _pColumn ) { m_pColumns->append( _rName, _pColumn ); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::clearColumns( ) { m_pColumns->clearColumns(); setColumnsOutOfDate(); } //-------------------------------------------------------------------------- Reference< XNameAccess > SAL_CALL OQueryDescriptor_Base::getColumns( ) throw (RuntimeException) { MutexGuard aGuard(m_rMutex); if ( isColumnsOutOfDate() ) { // clear the current columns clearColumns(); // do this before rebuildColumns. This prevents recursion, e.g. in the case where we // have queries with cyclic references: // foo := SELECT * FROM bar // bar := SELECT * FROM foo setColumnsOutOfDate( sal_False ); // rebuild them try { rebuildColumns(); } catch(...) { setColumnsOutOfDate( sal_True ); throw; } } return m_pColumns; } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OQueryDescriptor_Base::getImplementationName( ) throw(RuntimeException) { return ::rtl::OUString::createFromAscii("com.sun.star.sdb.OQueryDescriptor"); } //-------------------------------------------------------------------------- sal_Bool SAL_CALL OQueryDescriptor_Base::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OQueryDescriptor_Base::getSupportedServiceNames( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(2); aSupported.getArray()[0] = SERVICE_SDB_DATASETTINGS; aSupported.getArray()[1] = SERVICE_SDB_QUERYDESCRIPTOR; return aSupported; } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::disposeColumns() { m_pColumns->disposing(); } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnAppended( const Reference< XPropertySet >& /*_rxSourceDescriptor*/ ) { // not interested in } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnDropped(const ::rtl::OUString& /*_sName*/) { // not interested in } // ----------------------------------------------------------------------------- Reference< XPropertySet > OQueryDescriptor_Base::createColumnDescriptor() { OSL_ENSURE( false, "OQueryDescriptor_Base::createColumnDescriptor: called why?" ); return NULL; } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::rebuildColumns( ) { } // ----------------------------------------------------------------------------- // IRefreshableColumns void OQueryDescriptor_Base::refreshColumns() { MutexGuard aGuard( m_rMutex ); clearColumns(); rebuildColumns(); } //------------------------------------------------------------------------------ OColumn* OQueryDescriptor_Base::createColumn(const ::rtl::OUString& _rName) const { return new OTableColumn(_rName); } // ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS dba24b (1.31.96); FILE MERGED 2007/08/16 06:14:42 oj 1.31.96.1: #i56898# clean up of the class structure<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querydescriptor.cxx,v $ * * $Revision: 1.32 $ * * last change: $Author: hr $ $Date: 2007-11-01 15:02:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBA_COREAPI_QUERYDESCRIPTOR_HXX_ #include "querydescriptor.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::util; using namespace ::comphelper; using namespace ::osl; using namespace ::cppu; //........................................................................ namespace dbaccess { //........................................................................ //========================================================================== //= OQueryDescriptor //========================================================================== DBG_NAME(OQueryDescriptor) //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor() :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const Reference< XPropertySet >& _rxCommandDefinition) :OQueryDescriptor_Base(m_aMutex,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); osl_incrementInterlockedCount(&m_refCount); OSL_ENSURE(_rxCommandDefinition.is(), "OQueryDescriptor_Base::OQueryDescriptor_Base : invalid source property set !"); try { ::comphelper::copyProperties(_rxCommandDefinition,this); } catch(Exception&) { OSL_ENSURE(sal_False, "OQueryDescriptor_Base::OQueryDescriptor_Base: caught an exception!"); } osl_decrementInterlockedCount(&m_refCount); } //-------------------------------------------------------------------------- OQueryDescriptor::OQueryDescriptor(const OQueryDescriptor_Base& _rSource) :OQueryDescriptor_Base(_rSource,*this) ,ODataSettings(m_aBHelper,sal_True) { DBG_CTOR(OQueryDescriptor,NULL); registerProperties(); ODataSettings::registerPropertiesFor(this); } // ----------------------------------------------------------------------------- OQueryDescriptor::~OQueryDescriptor() { DBG_DTOR(OQueryDescriptor,NULL); } // ----------------------------------------------------------------------------- IMPLEMENT_TYPEPROVIDER2(OQueryDescriptor,OQueryDescriptor_Base,ODataSettings); IMPLEMENT_FORWARD_XINTERFACE3( OQueryDescriptor,OWeakObject,OQueryDescriptor_Base,ODataSettings) //-------------------------------------------------------------------------- void OQueryDescriptor::registerProperties() { // the properties which OCommandBase supplies (it has no own registration, as it's not derived from // a OPropertyStateContainer) registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND|PropertyAttribute::CONSTRAINED, &m_sElementName, ::getCppuType(&m_sElementName)); registerProperty(PROPERTY_COMMAND, PROPERTY_ID_COMMAND, PropertyAttribute::BOUND, &m_sCommand, ::getCppuType(&m_sCommand)); registerProperty(PROPERTY_USE_ESCAPE_PROCESSING, PROPERTY_ID_USE_ESCAPE_PROCESSING, PropertyAttribute::BOUND, &m_bEscapeProcessing, ::getBooleanCppuType()); registerProperty(PROPERTY_UPDATE_TABLENAME, PROPERTY_ID_UPDATE_TABLENAME, PropertyAttribute::BOUND, &m_sUpdateTableName, ::getCppuType(&m_sUpdateTableName)); registerProperty(PROPERTY_UPDATE_SCHEMANAME, PROPERTY_ID_UPDATE_SCHEMANAME, PropertyAttribute::BOUND, &m_sUpdateSchemaName, ::getCppuType(&m_sUpdateSchemaName)); registerProperty(PROPERTY_UPDATE_CATALOGNAME, PROPERTY_ID_UPDATE_CATALOGNAME, PropertyAttribute::BOUND, &m_sUpdateCatalogName, ::getCppuType(&m_sUpdateCatalogName)); registerProperty(PROPERTY_LAYOUTINFORMATION, PROPERTY_ID_LAYOUTINFORMATION, PropertyAttribute::BOUND, &m_aLayoutInformation, ::getCppuType(&m_aLayoutInformation)); } // ----------------------------------------------------------------------------- //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OQueryDescriptor::getPropertySetInfo( ) throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ) ; } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OQueryDescriptor::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OQueryDescriptor::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new ::cppu::OPropertyArrayHelper(aProps); } // ----------------------------------------------------------------------------- DBG_NAME(OQueryDescriptor_Base); //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(::osl::Mutex& _rMutex,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); } //-------------------------------------------------------------------------- OQueryDescriptor_Base::OQueryDescriptor_Base(const OQueryDescriptor_Base& _rSource,::cppu::OWeakObject& _rMySelf) :m_bColumnsOutOfDate(sal_True) ,m_rMutex(_rSource.m_rMutex) { DBG_CTOR(OQueryDescriptor_Base,NULL); m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this); m_sCommand = _rSource.m_sCommand; m_bEscapeProcessing = _rSource.m_bEscapeProcessing; m_sUpdateTableName = _rSource.m_sUpdateTableName; m_sUpdateSchemaName = _rSource.m_sUpdateSchemaName; m_sUpdateCatalogName = _rSource.m_sUpdateCatalogName; m_aLayoutInformation = _rSource.m_aLayoutInformation; } //-------------------------------------------------------------------------- OQueryDescriptor_Base::~OQueryDescriptor_Base() { m_pColumns->acquire(); m_pColumns->disposing(); delete m_pColumns; DBG_DTOR(OQueryDescriptor_Base,NULL); } // ----------------------------------------------------------------------------- sal_Int64 SAL_CALL OQueryDescriptor_Base::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) throw(RuntimeException) { if (_rIdentifier.getLength() != 16) return 0; if (0 == rtl_compareMemory(getImplementationId().getConstArray(), _rIdentifier.getConstArray(), 16 ) ) return reinterpret_cast<sal_Int64>(this); return 0; } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OQueryDescriptor_Base) //-------------------------------------------------------------------------- void OQueryDescriptor_Base::setColumnsOutOfDate( sal_Bool _bOutOfDate ) { m_bColumnsOutOfDate = _bOutOfDate; if ( !m_bColumnsOutOfDate ) m_pColumns->setInitialized(); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::implAppendColumn( const ::rtl::OUString& _rName, OColumn* _pColumn ) { m_pColumns->append( _rName, _pColumn ); } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::clearColumns( ) { m_pColumns->clearColumns(); setColumnsOutOfDate(); } //-------------------------------------------------------------------------- Reference< XNameAccess > SAL_CALL OQueryDescriptor_Base::getColumns( ) throw (RuntimeException) { MutexGuard aGuard(m_rMutex); if ( isColumnsOutOfDate() ) { // clear the current columns clearColumns(); // do this before rebuildColumns. This prevents recursion, e.g. in the case where we // have queries with cyclic references: // foo := SELECT * FROM bar // bar := SELECT * FROM foo setColumnsOutOfDate( sal_False ); // rebuild them try { rebuildColumns(); } catch(...) { setColumnsOutOfDate( sal_True ); throw; } } return m_pColumns; } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OQueryDescriptor_Base::getImplementationName( ) throw(RuntimeException) { return ::rtl::OUString::createFromAscii("com.sun.star.sdb.OQueryDescriptor"); } //-------------------------------------------------------------------------- sal_Bool SAL_CALL OQueryDescriptor_Base::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) { return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OQueryDescriptor_Base::getSupportedServiceNames( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aSupported(2); aSupported.getArray()[0] = SERVICE_SDB_DATASETTINGS; aSupported.getArray()[1] = SERVICE_SDB_QUERYDESCRIPTOR; return aSupported; } //-------------------------------------------------------------------------- void OQueryDescriptor_Base::disposeColumns() { m_pColumns->disposing(); } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnAppended( const Reference< XPropertySet >& /*_rxSourceDescriptor*/ ) { // not interested in } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::columnDropped(const ::rtl::OUString& /*_sName*/) { // not interested in } // ----------------------------------------------------------------------------- Reference< XPropertySet > OQueryDescriptor_Base::createColumnDescriptor() { OSL_ENSURE( false, "OQueryDescriptor_Base::createColumnDescriptor: called why?" ); return NULL; } // ----------------------------------------------------------------------------- void OQueryDescriptor_Base::rebuildColumns( ) { } // ----------------------------------------------------------------------------- // IRefreshableColumns void OQueryDescriptor_Base::refreshColumns() { MutexGuard aGuard( m_rMutex ); clearColumns(); rebuildColumns(); } //------------------------------------------------------------------------------ OColumn* OQueryDescriptor_Base::createColumn(const ::rtl::OUString& _rName) const { return new OTableColumn(_rName); } // ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Telmo Menezes. * telmo@telmomenezes.com */ #include "drmap.h" #include "utils.h" #include "emd_hat_signatures_interface.hpp" #include <stdlib.h> #include <strings.h> #include <stdio.h> namespace syn { DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor, double min_val_ver, double max_val_ver) { this->bin_number = bin_number; this->min_val_hor = min_val_hor; this->max_val_hor = max_val_hor; this->min_val_ver = min_val_ver; this->max_val_ver = max_val_ver; data = (double*)malloc(bin_number * bin_number * sizeof(double)); clear(); } DRMap::~DRMap() { free(data); } void DRMap::clear() { bzero(data, bin_number * bin_number * sizeof(double)); } void DRMap::set_value(unsigned int x, unsigned int y, double val) { data[(y * bin_number) + x] = val; } void DRMap::inc_value(unsigned int x, unsigned int y) { data[(y * bin_number) + x] += 1; } double DRMap::get_value(unsigned int x, unsigned int y) { return data[(y * bin_number) + x]; } void DRMap::log_scale() { for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if(data[(y * bin_number) + x] > 0) { data[(y * bin_number) + x] = log(data[(y * bin_number) + x]); } } } } void DRMap::normalize() { // find max value double max = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if(data[(y * bin_number) + x] > max) { max = data[(y * bin_number) + x]; } } } // normalize by max for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { data[(y * bin_number) + x] = data[(y * bin_number) + x] / max; } } } void DRMap::binary() { for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if(data[(y * bin_number) + x] > 0) { data[(y * bin_number) + x] = 1; } } } } double DRMap::total() { double total = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { total += data[(y * bin_number) + x]; } } return total; } double DRMap::simple_dist(DRMap* map) { double dist = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]); } } return dist; } double ground_dist(feature_tt* feature1, feature_tt* feature2) { double deltaX = feature1->x - feature2->x; double deltaY = feature1->y - feature2->y; double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY)); //double dist = (deltaX * deltaX) + (deltaY * deltaY); return dist; } signature_tt* get_emd_signature(DRMap* map) { unsigned int n = 0; unsigned int bin_number = map->get_bin_number(); for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if (map->get_value(x, y) > 0) { n++; } } } feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n); double* weights = (double*)malloc(sizeof(double) * n); unsigned int i = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { double val = map->get_value(x, y); if (val > 0) { features[i].x = x; features[i].y = y; weights[i] = val; i++; } } } signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt)); signature->n = n; signature->Features = features; signature->Weights = weights; return signature; } double DRMap::emd_dist(DRMap* map) { printf("totals-> %f; %f\n", total, map->total()); double infinity = 9999999999.9; if (total() == 0) { return infinity; } if (map->total() == 0) { return infinity; } signature_tt* sig1 = get_emd_signature(this); signature_tt* sig2 = get_emd_signature(map); double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1); free(sig1->Features); free(sig1->Weights); free(sig1); free(sig2->Features); free(sig2->Weights); free(sig2); return dist; } void DRMap::print() { for (unsigned int y = 0; y < bin_number; y++) { for (unsigned int x = 0; x < bin_number; x++) { printf("%f\t", get_value(x, y)); } printf("\n"); } } } <commit_msg>degugging emd_dist<commit_after>/* * Copyright (C) 2010 Telmo Menezes. * telmo@telmomenezes.com */ #include "drmap.h" #include "utils.h" #include "emd_hat_signatures_interface.hpp" #include <stdlib.h> #include <strings.h> #include <stdio.h> namespace syn { DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor, double min_val_ver, double max_val_ver) { this->bin_number = bin_number; this->min_val_hor = min_val_hor; this->max_val_hor = max_val_hor; this->min_val_ver = min_val_ver; this->max_val_ver = max_val_ver; data = (double*)malloc(bin_number * bin_number * sizeof(double)); clear(); } DRMap::~DRMap() { free(data); } void DRMap::clear() { bzero(data, bin_number * bin_number * sizeof(double)); } void DRMap::set_value(unsigned int x, unsigned int y, double val) { data[(y * bin_number) + x] = val; } void DRMap::inc_value(unsigned int x, unsigned int y) { data[(y * bin_number) + x] += 1; } double DRMap::get_value(unsigned int x, unsigned int y) { return data[(y * bin_number) + x]; } void DRMap::log_scale() { for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if(data[(y * bin_number) + x] > 0) { data[(y * bin_number) + x] = log(data[(y * bin_number) + x]); } } } } void DRMap::normalize() { // find max value double max = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if(data[(y * bin_number) + x] > max) { max = data[(y * bin_number) + x]; } } } // normalize by max for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { data[(y * bin_number) + x] = data[(y * bin_number) + x] / max; } } } void DRMap::binary() { for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if(data[(y * bin_number) + x] > 0) { data[(y * bin_number) + x] = 1; } } } } double DRMap::total() { double total = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { total += data[(y * bin_number) + x]; } } return total; } double DRMap::simple_dist(DRMap* map) { double dist = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]); } } return dist; } double ground_dist(feature_tt* feature1, feature_tt* feature2) { double deltaX = feature1->x - feature2->x; double deltaY = feature1->y - feature2->y; double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY)); //double dist = (deltaX * deltaX) + (deltaY * deltaY); return dist; } signature_tt* get_emd_signature(DRMap* map) { unsigned int n = 0; unsigned int bin_number = map->get_bin_number(); for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { if (map->get_value(x, y) > 0) { n++; } } } feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n); double* weights = (double*)malloc(sizeof(double) * n); unsigned int i = 0; for (unsigned int x = 0; x < bin_number; x++) { for (unsigned int y = 0; y < bin_number; y++) { double val = map->get_value(x, y); if (val > 0) { features[i].x = x; features[i].y = y; weights[i] = val; i++; } } } signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt)); signature->n = n; signature->Features = features; signature->Weights = weights; return signature; } double DRMap::emd_dist(DRMap* map) { printf("totals-> %f; %f\n", total(), map->total()); double infinity = 9999999999.9; if (total() == 0) { return infinity; } if (map->total() == 0) { return infinity; } signature_tt* sig1 = get_emd_signature(this); signature_tt* sig2 = get_emd_signature(map); double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1); free(sig1->Features); free(sig1->Weights); free(sig1); free(sig2->Features); free(sig2->Weights); free(sig2); return dist; } void DRMap::print() { for (unsigned int y = 0; y < bin_number; y++) { for (unsigned int x = 0; x < bin_number; x++) { printf("%f\t", get_value(x, y)); } printf("\n"); } } } <|endoftext|>
<commit_before>/* Q Light Controller Plus e131node.cpp Copyright (c) Massimo Callegari 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.txt 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 "e131controller.h" #include <QDebug> E131Controller::E131Controller(QString ipaddr, QString macAddress, Type type, quint32 line, QObject *parent) : QObject(parent) { m_ipAddr = QHostAddress(ipaddr); m_MACAddress = macAddress; m_line = line; qDebug() << "[E131Controller] type: " << type; m_packetizer = new E131Packetizer(); m_packetSent = 0; m_packetReceived = 0; m_type = type; m_inputRefCount = 0; m_outputRefCount = 0; m_UdpSocket = new QUdpSocket(this); // reset initial DMX values if we're an input if (type == Input) { m_dmxValues.fill(0, 512); if (m_UdpSocket->bind(QHostAddress::AnyIPv4, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false) { qDebug() << Q_FUNC_INFO << "Socket input bind failed !!"; return; } m_inputRefCount = 1; } else { if (m_UdpSocket->bind(m_ipAddr, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false) { qDebug() << Q_FUNC_INFO << "Socket output bind failed !!"; return; } m_outputRefCount = 1; } connect(m_UdpSocket, SIGNAL(readyRead()), this, SLOT(processPendingPackets())); } E131Controller::~E131Controller() { qDebug() << Q_FUNC_INFO; disconnect(m_UdpSocket, SIGNAL(readyRead()), this, SLOT(processPendingPackets())); m_UdpSocket->close(); } void E131Controller::setType(Type type) { m_type = type; } E131Controller::Type E131Controller::type() { return m_type; } void E131Controller::enableUniverse(quint32 universe) { m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1)); qDebug() << "[E131Controller] Enable universe:" << universe << ", multicast address:" << m_multicastAddr[universe].toString(); if (m_type == Input) m_UdpSocket->joinMulticastGroup(m_multicastAddr[universe]); } quint64 E131Controller::getPacketSentNumber() { return m_packetSent; } quint64 E131Controller::getPacketReceivedNumber() { return m_packetReceived; } void E131Controller::changeReferenceCount(E131Controller::Type type, int amount) { if (type == Input) { m_inputRefCount += amount; m_dmxValues.resize(m_inputRefCount * 512); } else m_outputRefCount += amount; } int E131Controller::referenceCount(E131Controller::Type type) { if (type == Input) return m_inputRefCount; else return m_outputRefCount; } QString E131Controller::getNetworkIP() { return m_ipAddr.toString(); } void E131Controller::sendDmx(const quint32 universe, const QByteArray &data) { QByteArray dmxPacket; m_packetizer->setupE131Dmx(dmxPacket, universe, data); if (m_multicastAddr.contains(universe) == false) { m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1)); qDebug() << "[E131Controller] Universe:" << universe << ", multicast address:" << m_multicastAddr[universe].toString() << "(MAC:" << m_MACAddress << ")"; } qint64 sent = m_UdpSocket->writeDatagram(dmxPacket.data(), dmxPacket.size(), m_multicastAddr[universe], E131_DEFAULT_PORT); if (sent < 0) { qDebug() << "sendDmx failed"; qDebug() << "Errno: " << m_UdpSocket->error(); qDebug() << "Errmgs: " << m_UdpSocket->errorString(); } else m_packetSent++; } void E131Controller::processPendingPackets() { while (m_UdpSocket->hasPendingDatagrams()) { QByteArray datagram; QHostAddress senderAddress; datagram.resize(m_UdpSocket->pendingDatagramSize()); m_UdpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress); if (senderAddress != m_ipAddr) { qDebug() << "Received packet with size: " << datagram.size() << ", host: " << senderAddress.toString(); if (m_packetizer->checkPacket(datagram) == true) { QByteArray dmxData; quint32 universe; if (this->type() == Input) { m_packetReceived++; if (m_packetizer->fillDMXdata(datagram, dmxData, universe) == true) { if (universe >= (quint32)m_inputRefCount) break; quint32 uniAddr = universe << 9; for (quint32 i = 0; i < (quint32)dmxData.length(); i++) { if (m_dmxValues.at(uniAddr + i) != dmxData.at(i)) { m_dmxValues[uniAddr + i] = dmxData[i]; emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i)); } } } } } } } } <commit_msg>Fixed Qt4 build<commit_after>/* Q Light Controller Plus e131node.cpp Copyright (c) Massimo Callegari 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.txt 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 "e131controller.h" #include <QDebug> E131Controller::E131Controller(QString ipaddr, QString macAddress, Type type, quint32 line, QObject *parent) : QObject(parent) { m_ipAddr = QHostAddress(ipaddr); m_MACAddress = macAddress; m_line = line; qDebug() << "[E131Controller] type: " << type; m_packetizer = new E131Packetizer(); m_packetSent = 0; m_packetReceived = 0; m_type = type; m_inputRefCount = 0; m_outputRefCount = 0; m_UdpSocket = new QUdpSocket(this); // reset initial DMX values if we're an input if (type == Input) { m_dmxValues.fill(0, 512); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) if (m_UdpSocket->bind(QHostAddress::AnyIPv4, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false) #else if (m_UdpSocket->bind(QHostAddress::Any, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false) #endif { qDebug() << Q_FUNC_INFO << "Socket input bind failed !!"; return; } m_inputRefCount = 1; } else { if (m_UdpSocket->bind(m_ipAddr, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false) { qDebug() << Q_FUNC_INFO << "Socket output bind failed !!"; return; } m_outputRefCount = 1; } connect(m_UdpSocket, SIGNAL(readyRead()), this, SLOT(processPendingPackets())); } E131Controller::~E131Controller() { qDebug() << Q_FUNC_INFO; disconnect(m_UdpSocket, SIGNAL(readyRead()), this, SLOT(processPendingPackets())); m_UdpSocket->close(); } void E131Controller::setType(Type type) { m_type = type; } E131Controller::Type E131Controller::type() { return m_type; } void E131Controller::enableUniverse(quint32 universe) { m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1)); qDebug() << "[E131Controller] Enable universe:" << universe << ", multicast address:" << m_multicastAddr[universe].toString(); if (m_type == Input) m_UdpSocket->joinMulticastGroup(m_multicastAddr[universe]); } quint64 E131Controller::getPacketSentNumber() { return m_packetSent; } quint64 E131Controller::getPacketReceivedNumber() { return m_packetReceived; } void E131Controller::changeReferenceCount(E131Controller::Type type, int amount) { if (type == Input) { m_inputRefCount += amount; m_dmxValues.resize(m_inputRefCount * 512); } else m_outputRefCount += amount; } int E131Controller::referenceCount(E131Controller::Type type) { if (type == Input) return m_inputRefCount; else return m_outputRefCount; } QString E131Controller::getNetworkIP() { return m_ipAddr.toString(); } void E131Controller::sendDmx(const quint32 universe, const QByteArray &data) { QByteArray dmxPacket; m_packetizer->setupE131Dmx(dmxPacket, universe, data); if (m_multicastAddr.contains(universe) == false) { m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1)); qDebug() << "[E131Controller] Universe:" << universe << ", multicast address:" << m_multicastAddr[universe].toString() << "(MAC:" << m_MACAddress << ")"; } qint64 sent = m_UdpSocket->writeDatagram(dmxPacket.data(), dmxPacket.size(), m_multicastAddr[universe], E131_DEFAULT_PORT); if (sent < 0) { qDebug() << "sendDmx failed"; qDebug() << "Errno: " << m_UdpSocket->error(); qDebug() << "Errmgs: " << m_UdpSocket->errorString(); } else m_packetSent++; } void E131Controller::processPendingPackets() { while (m_UdpSocket->hasPendingDatagrams()) { QByteArray datagram; QHostAddress senderAddress; datagram.resize(m_UdpSocket->pendingDatagramSize()); m_UdpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress); if (senderAddress != m_ipAddr) { qDebug() << "Received packet with size: " << datagram.size() << ", host: " << senderAddress.toString(); if (m_packetizer->checkPacket(datagram) == true) { QByteArray dmxData; quint32 universe; if (this->type() == Input) { m_packetReceived++; if (m_packetizer->fillDMXdata(datagram, dmxData, universe) == true) { if (universe >= (quint32)m_inputRefCount) break; quint32 uniAddr = universe << 9; for (quint32 i = 0; i < (quint32)dmxData.length(); i++) { if (m_dmxValues.at(uniAddr + i) != dmxData.at(i)) { m_dmxValues[uniAddr + i] = dmxData[i]; emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i)); } } } } } } } } <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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 <vlGraphics/DrawPixels.hpp> #include <vlGraphics/Actor.hpp> #include <vlGraphics/Camera.hpp> #include <vlGraphics/GLBufferObject.hpp> #include <vlCore/Log.hpp> #include <map> using namespace vl; //----------------------------------------------------------------------------- // DrawPixels::Pixels //----------------------------------------------------------------------------- DrawPixels::Pixels::Pixels() { VL_DEBUG_SET_OBJECT_NAME() mAlign = AlignBottom | AlignLeft; } //----------------------------------------------------------------------------- DrawPixels::Pixels::Pixels(ImagePBO* img, int scrx, int scry, int startx, int starty, int width, int height, int alignment) { VL_DEBUG_SET_OBJECT_NAME() mAlign = alignment; if (width < 0) width = img->width() - startx; if (height < 0) height = img->height() - starty; mImage = img; mPosition = ivec2(scrx, scry); mStart = ivec2(startx, starty); mSize = ivec2(width, height); } //----------------------------------------------------------------------------- DrawPixels::Pixels::Pixels(const Pixels& other): Object(other) { VL_DEBUG_SET_OBJECT_NAME() *this = other; } //----------------------------------------------------------------------------- DrawPixels::Pixels& DrawPixels::Pixels::operator=(const Pixels& other) { mImage = other.mImage; mPosition = other.mPosition; mStart = other.mStart; mSize = other.mSize; mAlign = other.mAlign; return *this; } //----------------------------------------------------------------------------- DrawPixels::Pixels::~Pixels() { } //----------------------------------------------------------------------------- void DrawPixels::Pixels::deletePixelBufferObject() { image()->pixelBufferObject()->deleteGLBufferObject(); } //----------------------------------------------------------------------------- bool DrawPixels::Pixels::generatePixelBufferObject(EGLBufferUsage usage, bool discard_local_storage) { VL_CHECK(image()) if (!image()) return false; image()->pixelBufferObject()->setBufferData( image()->imageBuffer()->bytesUsed(), image()->imageBuffer()->ptr(), usage ); if (discard_local_storage) image()->imageBuffer()->clear(); return true; } //----------------------------------------------------------------------------- bool DrawPixels::Pixels::hasPixelBufferObject() const { return image()->pixelBufferObject()->handle() != 0; } //----------------------------------------------------------------------------- // DrawPixels //----------------------------------------------------------------------------- DrawPixels::DrawPixels() { mUsePixelBufferObject = false; mDraws.setAutomaticDelete(false); } //----------------------------------------------------------------------------- void DrawPixels::render_Implementation(const Actor* actor, const Shader*, const Camera* camera, OpenGLContext*) const { VL_CHECK_OGL() int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() }; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); VL_CHECK_OGL(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho( -0.5, viewport[2]-0.5, -0.5, viewport[3]-0.5, -1, +1 ); VL_CHECK_OGL(); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); VL_CHECK_OGL(); for(int i=0; i<(int)mDraws.size(); ++i) { const Pixels* cmd = draws()->at(i); if (cmd->image() == 0) continue; const GLBufferObject* glbuf = cmd->image()->pixelBufferObject(); VL_CHECK( cmd->image() ) VL_CHECK( glbuf ) VL_CHECK( glbuf->handle() || cmd->image()->pixels() ) VL_CHECK( cmd->image()->isValid() ) VL_CHECK( cmd->mStart.x() >= 0 ) VL_CHECK( cmd->mStart.y() >= 0 ) //VL_CHECK( cmd->mStart.x()+cmd->mSize.x() -1 < cmd->image()->width() ) //VL_CHECK( cmd->mStart.y()+cmd->mSize.y() -1 < cmd->image()->height() ) int pos_x = cmd->mPosition.x(); int pos_y = cmd->mPosition.y(); // alignment if (cmd->align() & AlignRight) pos_x -= cmd->mSize.x() -1; if (cmd->align() & AlignHCenter) pos_x -= cmd->mSize.x() / 2; if (cmd->align() & AlignTop) pos_y -= cmd->mSize.y() -1; if (cmd->align() & AlignVCenter) pos_y -= cmd->mSize.y() / 2; // transform following if ( camera && actor && actor->transform() ) { vec4 v(0,0,0,1); v = actor->transform()->worldMatrix() * v; camera->project(v,v); // from screen space to viewport space v.x() -= viewport[0]; v.y() -= viewport[1]; pos_x += int(v.x() + 0.5); pos_y += int(v.y() + 0.5); } // culling if ( pos_x + cmd->mSize.x() -1 < 0 ) continue; if ( pos_y + cmd->mSize.y() -1 < 0 ) continue; if (pos_x > viewport[2] - 1) continue; if (pos_y > viewport[3] - 1) continue; // clipping int clip_left = pos_x < 0 ? -pos_x : 0; int clip_bottom = pos_y < 0 ? -pos_y : 0; int clip_right = (pos_x+cmd->mSize.x()-1)-( viewport[2]-1 ); int clip_top = (pos_y+cmd->mSize.y()-1)-( viewport[3]-1 ); if (clip_right < 0) clip_right = 0; if (clip_top < 0) clip_top = 0; glRasterPos2f( /*0.5f +*/ (float)pos_x + clip_left, /*0.5f +*/ (float)pos_y + clip_bottom ); // clear the current color, texture, normal glColor4f(1.0f,1.0f,1.0f,1.0f); glNormal3f(0,0,1.0f); glTexCoord3f(0,0,0); VL_CHECK_OGL() glPixelStorei( GL_UNPACK_ALIGNMENT, cmd->image()->byteAlignment() ); glPixelStorei( GL_UNPACK_ROW_LENGTH, cmd->image()->width() ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, cmd->mStart.x() + clip_left ); glPixelStorei( GL_UNPACK_SKIP_ROWS, cmd->mStart.y() + clip_bottom ); VL_CHECK_OGL() if ( glbuf->handle() ) { VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, glbuf->handle() ); VL_CHECK_OGL() glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), 0 ); VL_CHECK_OGL(); } else { VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 ); glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), cmd->image()->pixels() ); VL_CHECK_OGL(); } } VL_CHECK_OGL(); VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 ); VL_CHECK_OGL() // restores the default values glPopClientAttrib(); VL_CHECK_OGL(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); VL_CHECK_OGL() glMatrixMode(GL_PROJECTION); glPopMatrix(); VL_CHECK_OGL() } //----------------------------------------------------------------------------- //! deallocate PBOs void DrawPixels::deletePixelBufferObjects() { VL_CHECK_OGL() for(int i=0; i<(int)mDraws.size(); ++i) { mDraws[i]->image()->pixelBufferObject()->deleteGLBufferObject(); } VL_CHECK_OGL() } //----------------------------------------------------------------------------- void DrawPixels::releaseImages() { for(int i=0; i<(int)mDraws.size(); ++i) mDraws[i]->mImage = NULL; } //----------------------------------------------------------------------------- //! generates PBOs only for Pixels objects without a PBO handle bool DrawPixels::generatePixelBufferObjects(EGLBufferUsage usage, bool discard_local_storage) { if ( !( Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object ) ) return false; // generates PBOs if they have an attached Image // avoids to PBO duplicates for the same images std::map< ref<Image>, unsigned int> pbomap; for(int i=0; i<(int)mDraws.size(); ++i) { if ( mDraws[i]->hasPixelBufferObject() ) continue; if ( mDraws[i]->mImage.get() == NULL ) continue; mDraws[i]->generatePixelBufferObject(usage, discard_local_storage); } return true; } //----------------------------------------------------------------------------- void DrawPixels::setUsePixelBufferObject(bool use_pbo) { if ( (Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object) ) mUsePixelBufferObject = use_pbo; else mUsePixelBufferObject = false; } //----------------------------------------------------------------------------- <commit_msg>Use floats for glOrtho<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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 <vlGraphics/DrawPixels.hpp> #include <vlGraphics/Actor.hpp> #include <vlGraphics/Camera.hpp> #include <vlGraphics/GLBufferObject.hpp> #include <vlCore/Log.hpp> #include <map> using namespace vl; //----------------------------------------------------------------------------- // DrawPixels::Pixels //----------------------------------------------------------------------------- DrawPixels::Pixels::Pixels() { VL_DEBUG_SET_OBJECT_NAME() mAlign = AlignBottom | AlignLeft; } //----------------------------------------------------------------------------- DrawPixels::Pixels::Pixels(ImagePBO* img, int scrx, int scry, int startx, int starty, int width, int height, int alignment) { VL_DEBUG_SET_OBJECT_NAME() mAlign = alignment; if (width < 0) width = img->width() - startx; if (height < 0) height = img->height() - starty; mImage = img; mPosition = ivec2(scrx, scry); mStart = ivec2(startx, starty); mSize = ivec2(width, height); } //----------------------------------------------------------------------------- DrawPixels::Pixels::Pixels(const Pixels& other): Object(other) { VL_DEBUG_SET_OBJECT_NAME() *this = other; } //----------------------------------------------------------------------------- DrawPixels::Pixels& DrawPixels::Pixels::operator=(const Pixels& other) { mImage = other.mImage; mPosition = other.mPosition; mStart = other.mStart; mSize = other.mSize; mAlign = other.mAlign; return *this; } //----------------------------------------------------------------------------- DrawPixels::Pixels::~Pixels() { } //----------------------------------------------------------------------------- void DrawPixels::Pixels::deletePixelBufferObject() { image()->pixelBufferObject()->deleteGLBufferObject(); } //----------------------------------------------------------------------------- bool DrawPixels::Pixels::generatePixelBufferObject(EGLBufferUsage usage, bool discard_local_storage) { VL_CHECK(image()) if (!image()) return false; image()->pixelBufferObject()->setBufferData( (GLsizeiptr)image()->imageBuffer()->bytesUsed(), image()->imageBuffer()->ptr(), usage ); if (discard_local_storage) image()->imageBuffer()->clear(); return true; } //----------------------------------------------------------------------------- bool DrawPixels::Pixels::hasPixelBufferObject() const { return image()->pixelBufferObject()->handle() != 0; } //----------------------------------------------------------------------------- // DrawPixels //----------------------------------------------------------------------------- DrawPixels::DrawPixels() { mUsePixelBufferObject = false; mDraws.setAutomaticDelete(false); } //----------------------------------------------------------------------------- void DrawPixels::render_Implementation(const Actor* actor, const Shader*, const Camera* camera, OpenGLContext*) const { VL_CHECK_OGL() int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() }; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); VL_CHECK_OGL(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho( -0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f, -1.0f, +1.0f ); VL_CHECK_OGL(); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); VL_CHECK_OGL(); for(int i=0; i<(int)mDraws.size(); ++i) { const Pixels* cmd = draws()->at(i); if (cmd->image() == 0) continue; const GLBufferObject* glbuf = cmd->image()->pixelBufferObject(); VL_CHECK( cmd->image() ) VL_CHECK( glbuf ) VL_CHECK( glbuf->handle() || cmd->image()->pixels() ) VL_CHECK( cmd->image()->isValid() ) VL_CHECK( cmd->mStart.x() >= 0 ) VL_CHECK( cmd->mStart.y() >= 0 ) //VL_CHECK( cmd->mStart.x()+cmd->mSize.x() -1 < cmd->image()->width() ) //VL_CHECK( cmd->mStart.y()+cmd->mSize.y() -1 < cmd->image()->height() ) int pos_x = cmd->mPosition.x(); int pos_y = cmd->mPosition.y(); // alignment if (cmd->align() & AlignRight) pos_x -= cmd->mSize.x() -1; if (cmd->align() & AlignHCenter) pos_x -= cmd->mSize.x() / 2; if (cmd->align() & AlignTop) pos_y -= cmd->mSize.y() -1; if (cmd->align() & AlignVCenter) pos_y -= cmd->mSize.y() / 2; // transform following if ( camera && actor && actor->transform() ) { vec4 v(0,0,0,1); v = actor->transform()->worldMatrix() * v; camera->project(v,v); // from screen space to viewport space v.x() -= viewport[0]; v.y() -= viewport[1]; pos_x += int(v.x() + 0.5); pos_y += int(v.y() + 0.5); } // culling if ( pos_x + cmd->mSize.x() -1 < 0 ) continue; if ( pos_y + cmd->mSize.y() -1 < 0 ) continue; if (pos_x > viewport[2] - 1) continue; if (pos_y > viewport[3] - 1) continue; // clipping int clip_left = pos_x < 0 ? -pos_x : 0; int clip_bottom = pos_y < 0 ? -pos_y : 0; int clip_right = (pos_x+cmd->mSize.x()-1)-( viewport[2]-1 ); int clip_top = (pos_y+cmd->mSize.y()-1)-( viewport[3]-1 ); if (clip_right < 0) clip_right = 0; if (clip_top < 0) clip_top = 0; glRasterPos2f( /*0.5f +*/ (float)pos_x + clip_left, /*0.5f +*/ (float)pos_y + clip_bottom ); // clear the current color, texture, normal glColor4f(1.0f,1.0f,1.0f,1.0f); glNormal3f(0,0,1.0f); glTexCoord3f(0,0,0); VL_CHECK_OGL() glPixelStorei( GL_UNPACK_ALIGNMENT, cmd->image()->byteAlignment() ); glPixelStorei( GL_UNPACK_ROW_LENGTH, cmd->image()->width() ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, cmd->mStart.x() + clip_left ); glPixelStorei( GL_UNPACK_SKIP_ROWS, cmd->mStart.y() + clip_bottom ); VL_CHECK_OGL() if ( glbuf->handle() ) { VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, glbuf->handle() ); VL_CHECK_OGL() glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), 0 ); VL_CHECK_OGL(); } else { VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 ); glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), cmd->image()->pixels() ); VL_CHECK_OGL(); } } VL_CHECK_OGL(); VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 ); VL_CHECK_OGL() // restores the default values glPopClientAttrib(); VL_CHECK_OGL(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); VL_CHECK_OGL() glMatrixMode(GL_PROJECTION); glPopMatrix(); VL_CHECK_OGL() } //----------------------------------------------------------------------------- //! deallocate PBOs void DrawPixels::deletePixelBufferObjects() { VL_CHECK_OGL() for(int i=0; i<(int)mDraws.size(); ++i) { mDraws[i]->image()->pixelBufferObject()->deleteGLBufferObject(); } VL_CHECK_OGL() } //----------------------------------------------------------------------------- void DrawPixels::releaseImages() { for(int i=0; i<(int)mDraws.size(); ++i) mDraws[i]->mImage = NULL; } //----------------------------------------------------------------------------- //! generates PBOs only for Pixels objects without a PBO handle bool DrawPixels::generatePixelBufferObjects(EGLBufferUsage usage, bool discard_local_storage) { if ( !( Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object ) ) return false; // generates PBOs if they have an attached Image // avoids to PBO duplicates for the same images std::map< ref<Image>, unsigned int> pbomap; for(int i=0; i<(int)mDraws.size(); ++i) { if ( mDraws[i]->hasPixelBufferObject() ) continue; if ( mDraws[i]->mImage.get() == NULL ) continue; mDraws[i]->generatePixelBufferObject(usage, discard_local_storage); } return true; } //----------------------------------------------------------------------------- void DrawPixels::setUsePixelBufferObject(bool use_pbo) { if ( (Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object) ) mUsePixelBufferObject = use_pbo; else mUsePixelBufferObject = false; } //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "Players/CECP_Mediator.h" #include <string> #include <future> #include "Game/Board.h" #include "Game/Clock.h" #include "Game/Game_Result.h" #include "Moves/Move.h" #include "Players/Player.h" #include "Exceptions/Illegal_Move.h" #include "Exceptions/Game_Ended.h" #include "Utility/String.h" CECP_Mediator::CECP_Mediator(const Player& local_player) { std::string expected = "protover 2"; if(receive_command() == expected) { send_command("feature " "usermove=1 " "sigint=0 " "sigterm=0 " "reuse=0 " "myname=\"" + local_player.name() + "\" " "name=1 " "ping=1 " "setboard=1 " "colors=0 " "done=1"); } else { log("ERROR: Expected \"" + expected + "\""); throw std::runtime_error("Error in communicating with CECP program."); } } void CECP_Mediator::setup_turn(Board& board, Clock& clock) { while(true) { auto command = receive_cecp_command(board, clock, false); if(command == "go") { set_indent_level(board.whose_turn() == WHITE ? 2 : 3); log("telling local AI to move at leisure and accepting move"); in_force_mode = false; board.choose_move_at_leisure(); return; } else if (String::starts_with(command, "setboard ")) { auto fen = String::split(command, " ", 1).back(); try { // Handle stateless GUIs that send the next board position // instead of a move. board.submit_move(board.create_move(fen)); log("Derived move: " + board.game_record().back()->coordinate_move()); } catch(const Illegal_Move&) { log("Rearranging board to: " + fen); board = Board(fen); } } else if(String::starts_with(command, "usermove ")) { auto move = String::split(command).back(); try { log("Applying move: " + move); auto result = board.submit_move(board.create_move(move)); if(result.game_has_ended()) { report_end_of_game(result); } if( ! in_force_mode) { set_indent_level(board.whose_turn() == WHITE ? 2 : 3); log("Local AI now chooses a move"); board.choose_move_at_leisure(); return; } } catch(const Illegal_Move& e) { send_command("Illegal move (" + std::string(e.what()) + ") " + move); } } else if(String::starts_with(command, "time ") || String::starts_with(command, "otim ")) { auto time = std::stod(String::split(command, " ")[1])/100; // time specified in centiseconds auto ai_color = board.whose_turn(); auto clock_color = String::starts_with(command, "time ") ? ai_color : opposite(ai_color); clock.set_time(clock_color, time); log("setting " + color_text(clock_color) + "'s time to " + std::to_string(time) + " seconds."); } } } void CECP_Mediator::listen(Board& board, Clock& clock) { last_listening_command = std::async(std::launch::async, &CECP_Mediator::listener, this, std::ref(board), std::ref(clock)); } Game_Result CECP_Mediator::handle_move(Board& board, const Move& move) { if(in_force_mode) { log("Ignoring move: " + move.coordinate_move()); return {}; } else { send_command("move " + move.coordinate_move()); auto result = board.submit_move(move); if(result.game_has_ended()) { report_end_of_game(result); } return result; } } bool CECP_Mediator::pondering_allowed() const { return thinking_on_opponent_time; } std::string CECP_Mediator::receive_cecp_command(Board& board, Clock& clock, bool while_listening) { while(true) { std::string command; if(while_listening) { command = receive_command(); } else { command = last_listening_command.valid() ? last_listening_command.get() : receive_command(); } if(String::starts_with(command, "ping ")) { command[1] = 'o'; // change "ping" to "pong" send_command(command); } else if(String::starts_with(command, "result ")) { auto result = String::split(command).at(1); auto reason = String::split(String::split(command, "{", 1)[1], "}", 1)[0]; report_end_of_game(result, reason); } else if(command == "force") { board.pick_move_now(); in_force_mode = true; } else if(String::starts_with(command, "level ")) { log("got time specs: " + command); auto split = String::split(command); log("moves to reset clock = " + split[1]); auto reset_moves = String::string_to_size_t(split[1]); auto time_split = String::split(split[2], ":"); auto game_time = 0; if(time_split.size() == 1) { log("game time = " + time_split[0] + " minutes"); game_time = 60*std::stoi(time_split[0]); } else { log("game time = " + time_split[0] + " minutes and " + time_split[1] + " seconds"); game_time = 60*std::stoi(time_split[0]) + std::stoi(time_split[1]); } log("increment = " + split[3]); auto increment = std::stod(split[3]); clock = Clock(game_time, reset_moves, increment, WHITE, false); } else if(String::starts_with(command, "st ")) { log("got time specs: " + command); auto split = String::split(command); auto time_per_move = std::stoi(split[1]); auto reset_moves = 1; auto increment = 0; auto game_time = time_per_move; clock = Clock(game_time, reset_moves, increment, WHITE, false); } else if(command == "post") { if(board.thinking_mode() == CECP) { board.set_thinking_mode(NO_THINKING); log("Disabling thinking output for CECP"); } else { board.set_thinking_mode(CECP); log("turning on thinking output for CECP"); } } else if(command == "nopost") { board.set_thinking_mode(NO_THINKING); log("turning off thinking output for CECP"); } else if(command == "easy") { log("Turning off pondering"); thinking_on_opponent_time = false; } else if(command == "hard") { log("Turning on pondering"); thinking_on_opponent_time = true; } else if(command == "new") { log("Setting board to standard start position and resetting clock"); board = Board{}; clock = Clock(clock.initial_time(), clock.moves_per_time_period(), clock.increment(WHITE), WHITE, false); } else if(String::starts_with(command, "name ")) { set_other_player_name(String::split(command, " ", 1).back()); } else { return command; } } } std::string CECP_Mediator::listener(Board& board, Clock& clock) { while(true) { auto command = receive_cecp_command(board, clock, true); if(command == "?") { log("Forcing local AI to pick move and accepting it"); board.pick_move_now(); } else { return command; } } } void CECP_Mediator::report_end_of_game(const std::string& result, const std::string& reason) const { send_command(result + " {" + reason + "}"); throw Game_Ended(); } void CECP_Mediator::report_end_of_game(const Game_Result& result) const { report_end_of_game(result.game_ending_annotation(), result.ending_reason()); } <commit_msg>Log all accepted commands<commit_after>#include "Players/CECP_Mediator.h" #include <string> #include <future> #include "Game/Board.h" #include "Game/Clock.h" #include "Game/Game_Result.h" #include "Moves/Move.h" #include "Players/Player.h" #include "Exceptions/Illegal_Move.h" #include "Exceptions/Game_Ended.h" #include "Utility/String.h" CECP_Mediator::CECP_Mediator(const Player& local_player) { std::string expected = "protover 2"; if(receive_command() == expected) { send_command("feature " "usermove=1 " "sigint=0 " "sigterm=0 " "reuse=0 " "myname=\"" + local_player.name() + "\" " "name=1 " "ping=1 " "setboard=1 " "colors=0 " "done=1"); } else { log("ERROR: Expected \"" + expected + "\""); throw std::runtime_error("Error in communicating with CECP program."); } } void CECP_Mediator::setup_turn(Board& board, Clock& clock) { while(true) { auto command = receive_cecp_command(board, clock, false); if(command == "go") { set_indent_level(board.whose_turn() == WHITE ? 2 : 3); log("telling local AI to move at leisure and accepting move"); in_force_mode = false; board.choose_move_at_leisure(); return; } else if (String::starts_with(command, "setboard ")) { auto fen = String::split(command, " ", 1).back(); try { // Handle stateless GUIs that send the next board position // instead of a move. board.submit_move(board.create_move(fen)); log("Derived move: " + board.game_record().back()->coordinate_move()); } catch(const Illegal_Move&) { log("Rearranging board to: " + fen); board = Board(fen); } } else if(String::starts_with(command, "usermove ")) { auto move = String::split(command).back(); try { log("Applying move: " + move); auto result = board.submit_move(board.create_move(move)); if(result.game_has_ended()) { report_end_of_game(result); } if( ! in_force_mode) { set_indent_level(board.whose_turn() == WHITE ? 2 : 3); log("Local AI now chooses a move"); board.choose_move_at_leisure(); return; } } catch(const Illegal_Move& e) { send_command("Illegal move (" + std::string(e.what()) + ") " + move); } } else if(String::starts_with(command, "time ") || String::starts_with(command, "otim ")) { auto time = std::stod(String::split(command, " ")[1])/100; // time specified in centiseconds auto ai_color = board.whose_turn(); auto clock_color = String::starts_with(command, "time ") ? ai_color : opposite(ai_color); clock.set_time(clock_color, time); log("setting " + color_text(clock_color) + "'s time to " + std::to_string(time) + " seconds."); } } } void CECP_Mediator::listen(Board& board, Clock& clock) { last_listening_command = std::async(std::launch::async, &CECP_Mediator::listener, this, std::ref(board), std::ref(clock)); } Game_Result CECP_Mediator::handle_move(Board& board, const Move& move) { if(in_force_mode) { log("Ignoring move: " + move.coordinate_move()); return {}; } else { send_command("move " + move.coordinate_move()); auto result = board.submit_move(move); if(result.game_has_ended()) { report_end_of_game(result); } return result; } } bool CECP_Mediator::pondering_allowed() const { return thinking_on_opponent_time; } std::string CECP_Mediator::receive_cecp_command(Board& board, Clock& clock, bool while_listening) { while(true) { std::string command; if(while_listening) { command = receive_command(); } else { command = last_listening_command.valid() ? last_listening_command.get() : receive_command(); } if(String::starts_with(command, "ping ")) { command[1] = 'o'; // change "ping" to "pong" send_command(command); } else if(String::starts_with(command, "result ")) { auto result = String::split(command).at(1); auto reason = String::split(String::split(command, "{", 1)[1], "}", 1)[0]; report_end_of_game(result, reason); } else if(command == "force") { log("Entering force mode"); board.pick_move_now(); in_force_mode = true; } else if(String::starts_with(command, "level ")) { log("got time specs: " + command); auto split = String::split(command); log("moves to reset clock = " + split[1]); auto reset_moves = String::string_to_size_t(split[1]); auto time_split = String::split(split[2], ":"); auto game_time = 0; if(time_split.size() == 1) { log("game time = " + time_split[0] + " minutes"); game_time = 60*std::stoi(time_split[0]); } else { log("game time = " + time_split[0] + " minutes and " + time_split[1] + " seconds"); game_time = 60*std::stoi(time_split[0]) + std::stoi(time_split[1]); } log("increment = " + split[3]); auto increment = std::stod(split[3]); clock = Clock(game_time, reset_moves, increment, WHITE, false); } else if(String::starts_with(command, "st ")) { log("got time specs: " + command); auto split = String::split(command); auto time_per_move = std::stoi(split[1]); auto reset_moves = 1; auto increment = 0; auto game_time = time_per_move; clock = Clock(game_time, reset_moves, increment, WHITE, false); } else if(command == "post") { if(board.thinking_mode() == CECP) { board.set_thinking_mode(NO_THINKING); log("Disabling thinking output for CECP"); } else { board.set_thinking_mode(CECP); log("turning on thinking output for CECP"); } } else if(command == "nopost") { board.set_thinking_mode(NO_THINKING); log("turning off thinking output for CECP"); } else if(command == "easy") { log("Turning off pondering"); thinking_on_opponent_time = false; } else if(command == "hard") { log("Turning on pondering"); thinking_on_opponent_time = true; } else if(command == "new") { log("Setting board to standard start position and resetting clock"); board = Board{}; clock = Clock(clock.initial_time(), clock.moves_per_time_period(), clock.increment(WHITE), WHITE, false); } else if(String::starts_with(command, "name ")) { log("Getting other player's name"); set_other_player_name(String::split(command, " ", 1).back()); } else { return command; } } } std::string CECP_Mediator::listener(Board& board, Clock& clock) { while(true) { auto command = receive_cecp_command(board, clock, true); if(command == "?") { log("Forcing local AI to pick move and accepting it"); board.pick_move_now(); } else { return command; } } } void CECP_Mediator::report_end_of_game(const std::string& result, const std::string& reason) const { send_command(result + " {" + reason + "}"); throw Game_Ended(); } void CECP_Mediator::report_end_of_game(const Game_Result& result) const { report_end_of_game(result.game_ending_annotation(), result.ending_reason()); } <|endoftext|>
<commit_before>#include <efirc.h> // TODO was das wieder? IMPLEMENT_APP(Efirc) using namespace std; // Empfangene normale Nachrichten werden ausgegeben void irc_pmsg(const irc_msg_data *msg_data, void *cp) { string text = msg_data->params_a[1]; string recipient = msg_data->params_a[0]; string user = msg_data->nick; // CTCP vorerst ignorieren if (text[0] != '\001') { if(recipient == irc->CurrentNick) { frame->add_message("[" + user + "] " + text); } else { frame->add_message("<" + user + "> " + text); } } } // Am Ende der Nachricht des Tages automatisch den in // der Konfigurationsdatei genannten Kanal betreten void irc_endofmotd(const irc_msg_data *msg_data, void *cp) { IRCSocket *ircsocket = (IRCSocket *) cp; ircsocket->send_join(config->parsecfgvalue("irc_channel").c_str()); } // Thema des Raums anzeigen lassen void irc_topic(const irc_msg_data *msg_data, void *cp) { string topic = msg_data->params_a[2]; frame->set_topic(topic); } void irc_requestedtopic(const irc_msg_data *msg_data, void *cp) { string topic = msg_data->params_a[1]; frame->set_topic(topic); } // Benutzerliste einlesen void irc_userlist(const irc_msg_data *msg_data, void *cp) { string benutzerliste; benutzerliste = msg_data->params_a[3]; frame->add_user(benutzerliste); /* frame->add_message("(i) Folgende Benutzer sind zur Zeit im Raum: \n" + benutzerliste); */ } // Benutzerliste aktualisieren / Benutzer hat den Raum // betreten void irc_join(const irc_msg_data *msg_data, void *cp) { string benutzer; benutzer = msg_data->nick; frame->add_message("(i) " + benutzer + " hat den Raum betreten"); if (benutzer == irc->CurrentNick) { irc->CurrentChannel = msg_data->params_a[0]; frame->SetTitle(wxT(frame->parsecfgvalue("text_title") + " - [ " + irc->CurrentChannel + " ]")); } else // wenn selber, reicht irc_userlist() aus, da // neuer Channel und eventuell Operator frame->add_user(benutzer); } // Benutzerliste aktualisieren / Benutzer hat den Raum // verlassen void irc_leave(const irc_msg_data *msg_data, void *cp) { string benutzer; benutzer = msg_data->nick; frame->delete_user(benutzer); frame->add_message("(i) " + benutzer + " hat den Raum verlassen"); } // Benutzerliste aktualisieren / Benutzer hat den Raum und // das Netzwerk verlassen void irc_quit(const irc_msg_data *msg_data, void *cp) { string benutzer, nachricht; benutzer = msg_data->nick; nachricht = msg_data->params_a[0]; frame->delete_user(benutzer); frame->add_message("(i) " + benutzer + " ist gegangen: " + nachricht); } // Benutzerliste aktualisieren / Benutzer hat seinen // Nickname geaendert void irc_changenick(const irc_msg_data *msg_data, void *cp) { string alternick, neuernick; alternick = msg_data->nick; neuernick = msg_data->params_a[0]; frame->change_nick(alternick + " -> " + neuernick); if (alternick == irc->CurrentNick) irc->CurrentNick = neuernick; } void irc_pong(const irc_msg_data *msg_data, void *cp) { irc->send_pong(msg_data->params_a[0]); } void irc_kick(const irc_msg_data *msg_data, void *cp) { string benutzer,sender; sender = msg_data->nick; benutzer = msg_data->params_a[1]; if(benutzer == irc->CurrentNick) { frame->add_message("(i) Sie wurden von " + sender + "aus dem Raum geworfen"); frame->clear_userlist(); frame->set_topic(""); frame->SetTitle(wxT(frame->parsecfgvalue("text_title"))); } else { frame->delete_user(benutzer); frame->add_message("(i) " + benutzer + " wurde von " + sender + " aus dem Raum geworfen"); } } void irc_nickinuse(const irc_msg_data *msg_data, void *cp) { frame->add_message("(i) Nickname wird bereits verwendet"); // Nickname erneuern // aktuellen Nickname uebergeben config->reset_nickname(irc->CurrentNick); // neuen Nicknamen auslesen irc->CurrentNick = config->parsecfgvalue("irc_nickname"); frame->add_message("(i) Sie sind jetzt bekannt als " + config->parsecfgvalue("irc_nickname")); irc->send_nick(config->parsecfgvalue("irc_nickname").c_str()); } void irc_error(const irc_msg_data *msg_data, void *cp) { string text = msg_data->params_a[2]; frame->add_message("(!) " + text); } // Thread fuer recv_raw-Schleife void recv_thread(void *cp) { IRCSocket *ircsocket = (IRCSocket *)cp; ircsocket->recv_raw(); } // Abarbeitung der Befehlsschlange void call_thread(void *cp) { IRCSocket *ircsocket = (IRCSocket *)cp; ircsocket->call_cmd(); } void connect_thread(void *cp) { irc->connect(); // Wer sagt mir, dass der Nick verfuegbar ist??? irc->CurrentNick = config->parsecfgvalue("irc_nickname"); irc->CurrentChannel = config->parsecfgvalue("irc_channel"); // Ereignisverknpfung // TODO wirklich Ereignisse implementieren irc->add_link("PRIVMSG", &irc_pmsg); irc->add_link("376", &irc_endofmotd); irc->add_link("332", &irc_topic); irc->add_link("TOPIC", &irc_requestedtopic); irc->add_link("353", &irc_userlist); irc->add_link("JOIN", &irc_join); irc->add_link("PART", &irc_leave); irc->add_link("QUIT", &irc_quit); irc->add_link("NICK", &irc_changenick); irc->add_link("PING", &irc_pong); irc->add_link("KICK", &irc_kick); irc->add_link("433", &irc_nickinuse); //Fehler Antworten irc->add_link("401", &irc_error); irc->add_link("402", &irc_error); irc->add_link("403", &irc_error); irc->add_link("404", &irc_error); irc->add_link("405", &irc_error); irc->add_link("406", &irc_error); irc->add_link("407", &irc_error); irc->add_link("409", &irc_error); irc->add_link("411", &irc_error); irc->add_link("412", &irc_error); irc->add_link("413", &irc_error); irc->add_link("414", &irc_error); irc->add_link("421", &irc_error); irc->add_link("422", &irc_error); irc->add_link("423", &irc_error); irc->add_link("424", &irc_error); irc->add_link("431", &irc_error); irc->add_link("432", &irc_error); irc->add_link("433", &irc_error); irc->add_link("436", &irc_error); irc->add_link("441", &irc_error); irc->add_link("442", &irc_error); irc->add_link("443", &irc_error); irc->add_link("444", &irc_error); irc->add_link("445", &irc_error); irc->add_link("446", &irc_error); irc->add_link("451", &irc_error); irc->add_link("461", &irc_error); irc->add_link("462", &irc_error); irc->add_link("463", &irc_error); irc->add_link("464", &irc_error); irc->add_link("465", &irc_error); irc->add_link("467", &irc_error); irc->add_link("471", &irc_error); irc->add_link("472", &irc_error); irc->add_link("473", &irc_error); irc->add_link("474", &irc_error); irc->add_link("475", &irc_error); irc->add_link("481", &irc_error); irc->add_link("482", &irc_error); irc->add_link("483", &irc_error); irc->add_link("491", &irc_error); irc->add_link("501", &irc_error); irc->add_link("502", &irc_error); _beginthread(recv_thread, 0, irc); _beginthread(call_thread, 0, irc); } bool Efirc::OnInit() { frame = new UserInterface(NULL); frame->Show(); config = new ConfigInterface(); WSADATA wsaData; // TODO nach irc (class) if (WSAStartup(MAKEWORD(1, 1), &wsaData)) frame->add_message("(i) Failed to initialise winsock!"); irc = new IRCInterface(config->parsecfgvalue("irc_port"), config->parsecfgvalue("irc_server"), config->parsecfgvalue("irc_nickname"), config->parsecfgvalue("irc_username"), config->parsecfgvalue("irc_realname"), "pass"); _beginthread(connect_thread, 0, NULL); frame->irc = irc; return true; } int Efirc::OnExit() { WSACleanup(); return 0; } <commit_msg><commit_after>#include <efirc.h> // TODO was das wieder? IMPLEMENT_APP(Efirc) using namespace std; // Empfangene normale Nachrichten werden ausgegeben void irc_pmsg(const irc_msg_data *msg_data, void *cp) { string text = msg_data->params_a[1]; string recipient = msg_data->params_a[0]; string user = msg_data->nick; // CTCP vorerst ignorieren if (text[0] != '\001') { if(recipient == irc->CurrentNick) { frame->add_message("[" + user + "] " + text); } else { frame->add_message("<" + user + "> " + text); } } } // Am Ende der Nachricht des Tages automatisch den in // der Konfigurationsdatei genannten Kanal betreten void irc_endofmotd(const irc_msg_data *msg_data, void *cp) { IRCSocket *ircsocket = (IRCSocket *) cp; ircsocket->send_join(config->parsecfgvalue("irc_channel").c_str()); } // Thema des Raums anzeigen lassen void irc_topic(const irc_msg_data *msg_data, void *cp) { string topic = msg_data->params_a[2]; frame->set_topic(topic); } void irc_requestedtopic(const irc_msg_data *msg_data, void *cp) { string topic = msg_data->params_a[1]; frame->set_topic(topic); } // Benutzerliste einlesen void irc_userlist(const irc_msg_data *msg_data, void *cp) { string benutzerliste; benutzerliste = msg_data->params_a[3]; frame->add_user(benutzerliste); /* frame->add_message("(i) Folgende Benutzer sind zur Zeit im Raum: \n" + benutzerliste); */ } // Benutzerliste aktualisieren / Benutzer hat den Raum // betreten void irc_join(const irc_msg_data *msg_data, void *cp) { string benutzer; benutzer = msg_data->nick; frame->add_message("(i) " + benutzer + " hat den Raum betreten"); if (benutzer == irc->CurrentNick) { irc->CurrentChannel = msg_data->params_a[0]; frame->SetTitle(wxT(frame->parsecfgvalue("text_title") + " - [ " + irc->CurrentChannel + " ]")); } else // wenn selber, reicht irc_userlist() aus, da // neuer Channel und eventuell Operator frame->add_user(benutzer); } // Benutzerliste aktualisieren / Benutzer hat den Raum // verlassen void irc_leave(const irc_msg_data *msg_data, void *cp) { string benutzer; benutzer = msg_data->nick; frame->delete_user(benutzer); frame->add_message("(i) " + benutzer + " hat den Raum verlassen"); } // Benutzerliste aktualisieren / Benutzer hat den Raum und // das Netzwerk verlassen void irc_quit(const irc_msg_data *msg_data, void *cp) { string benutzer, nachricht; benutzer = msg_data->nick; nachricht = msg_data->params_a[0]; frame->delete_user(benutzer); frame->add_message("(i) " + benutzer + " ist gegangen: " + nachricht); } // Benutzerliste aktualisieren / Benutzer hat seinen // Nickname geaendert void irc_changenick(const irc_msg_data *msg_data, void *cp) { string alternick, neuernick; alternick = msg_data->nick; neuernick = msg_data->params_a[0]; frame->change_nick(alternick + " -> " + neuernick); if (alternick == irc->CurrentNick) irc->CurrentNick = neuernick; } void irc_pong(const irc_msg_data *msg_data, void *cp) { irc->send_pong(msg_data->params_a[0]); } void irc_kick(const irc_msg_data *msg_data, void *cp) { string benutzer,sender; sender = msg_data->nick; benutzer = msg_data->params_a[1]; if(benutzer == irc->CurrentNick) { frame->add_message("(i) Sie wurden von " + sender + "aus dem Raum geworfen"); frame->clear_userlist(); frame->set_topic(""); frame->SetTitle(wxT(frame->parsecfgvalue("text_title"))); } else { frame->delete_user(benutzer); frame->add_message("(i) " + benutzer + " wurde von " + sender + " aus dem Raum geworfen"); } } void irc_nickinuse(const irc_msg_data *msg_data, void *cp) { frame->add_message("(i) Nickname wird bereits verwendet"); // Nickname erneuern // aktuellen Nickname uebergeben config->reset_nickname(irc->CurrentNick); // neuen Nicknamen auslesen irc->CurrentNick = config->parsecfgvalue("irc_nickname"); frame->add_message("(i) Sie sind jetzt bekannt als " + config->parsecfgvalue("irc_nickname")); irc->send_nick(config->parsecfgvalue("irc_nickname").c_str()); } void irc_error(const irc_msg_data *msg_data, void *cp) { string text = msg_data->params_a[2]; frame->add_message("(!) " + text); } // Thread fuer recv_raw-Schleife void recv_thread(void *cp) { IRCSocket *ircsocket = (IRCSocket *)cp; ircsocket->recv_raw(); } // Abarbeitung der Befehlsschlange void call_thread(void *cp) { IRCSocket *ircsocket = (IRCSocket *)cp; ircsocket->call_cmd(); } void connect_thread(void *cp) { irc->connect(); // Wer sagt mir, dass der Nick verfuegbar ist??? irc->CurrentNick = config->parsecfgvalue("irc_nickname"); irc->CurrentChannel = config->parsecfgvalue("irc_channel"); // Ereignisverknpfung // TODO wirklich Ereignisse implementieren irc->add_link("PRIVMSG", &irc_pmsg); irc->add_link("376", &irc_endofmotd); irc->add_link("332", &irc_topic); irc->add_link("TOPIC", &irc_requestedtopic); irc->add_link("353", &irc_userlist); irc->add_link("JOIN", &irc_join); irc->add_link("PART", &irc_leave); irc->add_link("QUIT", &irc_quit); irc->add_link("NICK", &irc_changenick); irc->add_link("PING", &irc_pong); irc->add_link("KICK", &irc_kick); //Fehler Antworten irc->add_link("401", &irc_error); irc->add_link("402", &irc_error); irc->add_link("403", &irc_error); irc->add_link("404", &irc_error); irc->add_link("405", &irc_error); irc->add_link("406", &irc_error); irc->add_link("407", &irc_error); irc->add_link("409", &irc_error); irc->add_link("411", &irc_error); irc->add_link("412", &irc_error); irc->add_link("413", &irc_error); irc->add_link("414", &irc_error); irc->add_link("421", &irc_error); irc->add_link("422", &irc_error); irc->add_link("423", &irc_error); irc->add_link("424", &irc_error); irc->add_link("431", &irc_error); irc->add_link("432", &irc_error); irc->add_link("433", &irc_nickinuse); irc->add_link("436", &irc_error); irc->add_link("441", &irc_error); irc->add_link("442", &irc_error); irc->add_link("443", &irc_error); irc->add_link("444", &irc_error); irc->add_link("445", &irc_error); irc->add_link("446", &irc_error); irc->add_link("451", &irc_error); irc->add_link("461", &irc_error); irc->add_link("462", &irc_error); irc->add_link("463", &irc_error); irc->add_link("464", &irc_error); irc->add_link("465", &irc_error); irc->add_link("467", &irc_error); irc->add_link("471", &irc_error); irc->add_link("472", &irc_error); irc->add_link("473", &irc_error); irc->add_link("474", &irc_error); irc->add_link("475", &irc_error); irc->add_link("481", &irc_error); irc->add_link("482", &irc_error); irc->add_link("483", &irc_error); irc->add_link("491", &irc_error); irc->add_link("501", &irc_error); irc->add_link("502", &irc_error); _beginthread(recv_thread, 0, irc); _beginthread(call_thread, 0, irc); } bool Efirc::OnInit() { frame = new UserInterface(NULL); frame->Show(); config = new ConfigInterface(); WSADATA wsaData; // TODO nach irc (class) if (WSAStartup(MAKEWORD(1, 1), &wsaData)) frame->add_message("(i) Failed to initialise winsock!"); irc = new IRCInterface(config->parsecfgvalue("irc_port"), config->parsecfgvalue("irc_server"), config->parsecfgvalue("irc_nickname"), config->parsecfgvalue("irc_username"), config->parsecfgvalue("irc_realname"), "pass"); _beginthread(connect_thread, 0, NULL); frame->irc = irc; return true; } int Efirc::OnExit() { WSACleanup(); return 0; } <|endoftext|>
<commit_before>#include "engine.h" #include <cstdint> #include <string> #include <vector> // gray all percent uint_fast32_t Engine::GrayAllPercent(const uint_fast32_t pixCount, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0; i < pixCount; i++) { if (pixDiff > GrayDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / pixCount; } // gray mask percent uint_fast32_t Engine::GrayMaskPercent(const uint_fast32_t pixCount, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0; i < pixCount; i++) { if (bitsetVec[i] == 0 || pixDiff > GrayDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / bitsetCount; } // gray regions percent std::vector<uint_fast32_t> Engine::GrayRegionsPercent(const uint_fast32_t pixCount, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<uint_fast32_t> percentResultVec(regionsLen, 0); for (uint_fast32_t i = 0, r = 0; i < pixCount; i++) { uint_fast32_t diff = GrayDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[i] == 0 || regionsVec[r].pixDiff > diff) continue; percentResultVec[r]++; } } for (uint_fast32_t r = 0; r < regionsLen; r++) { percentResultVec[r] = percentResultVec[r] * 100 / regionsVec[r].bitsetCount; } return percentResultVec; } // rgb all percent uint_fast32_t Engine::RgbAllPercent(const uint_fast32_t pixCount, const uint_fast32_t pixDepth, const uint_fast32_t bufLen, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0; i < bufLen; i += pixDepth) { if (pixDiff > RgbDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / pixCount; } // rgb mask percent uint_fast32_t Engine::RgbMaskPercent(const uint_fast32_t pixDepth, const uint_fast32_t bufLen, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0, p = 0; i < bufLen; i += pixDepth, p++) { if (bitsetVec[p] == 0 || pixDiff > RgbDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / bitsetCount; } // rgb regions percent std::vector<uint_fast32_t> Engine::RgbRegionsPercent(const uint_fast32_t pixDepth, const uint_fast32_t bufLen, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<uint_fast32_t> percentResultVec(regionsLen, 0); for (uint_fast32_t i = 0, p = 0, r = 0; i < bufLen; i += pixDepth, p++) { uint_fast32_t diff = RgbDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[p] == 0 || regionsVec[r].pixDiff > diff) continue; percentResultVec[r]++; } } for (uint_fast32_t r = 0; r < regionsLen; r++) { percentResultVec[r] = percentResultVec[r] * 100 / regionsVec[r].bitsetCount; } return percentResultVec; } // gray all bounds Engine::BoundsResult Engine::GrayAllBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixCount, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0; y < height; y++) { for (x = 0; x < width; x++, i++) { if (pixDiff > GrayDiff(buf0, buf1, i)) continue; if (x > maxX) maxX = x; if (y > maxY) maxY = y; if (x < minX) minX = x; if (y < minY) minY = y; //minX = MinUint(minX, x); //maxX = MaxUint(maxX, x); //minY = MinUint(minY, y); //maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / pixCount, minX, maxX, minY, maxY}; } // gray mask bounds Engine::BoundsResult Engine::GrayMaskBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0; y < height; y++) { for (x = 0; x < width; x++, i++) { if (bitsetVec[i] == 0 || pixDiff > GrayDiff(buf0, buf1, i)) continue; if (x > maxX) maxX = x; if (y > maxY) maxY = y; if (x < minX) minX = x; if (y < minY) minY = y; //minX = MinUint(minX, x); //maxX = MaxUint(maxX, x); //minY = MinUint(minY, y); //maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / bitsetCount, minX, maxX, minY, maxY}; } // gray regions bounds std::vector<Engine::BoundsResult> Engine::GrayRegionsBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<Engine::BoundsResult> boundsResultVec(regionsLen, Engine::BoundsResult {0, width - 1 , 0, height - 1, 0}); for (uint_fast32_t y = 0, x = 0, i = 0, r = 0; y < height; y++) { for (x = 0; x < width; x++, i++) { uint_fast32_t diff = GrayDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[i] == 0 || regionsVec[r].pixDiff > diff) continue; boundsResultVec[r].minX = MinUint(boundsResultVec[r].minX, x); boundsResultVec[r].maxX = MaxUint(boundsResultVec[r].maxX, x); boundsResultVec[r].minY = MinUint(boundsResultVec[r].minY, y); boundsResultVec[r].maxY = MaxUint(boundsResultVec[r].maxY, y); boundsResultVec[r].percent++; } } } for (uint_fast32_t r = 0; r < regionsLen; r++) { boundsResultVec[r].percent = boundsResultVec[r].percent * 100 / regionsVec[r].bitsetCount; } return boundsResultVec; } // rgb all bounds Engine::BoundsResult Engine::RgbAllBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixCount, const uint_fast32_t pixDepth, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0; y < height; y++) { for (x = 0; x < width; x++, i += pixDepth) { if (pixDiff > RgbDiff(buf0, buf1, i)) continue; minX = MinUint(minX, x); maxX = MaxUint(maxX, x); minY = MinUint(minY, y); maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / pixCount, minX, maxX, minY, maxY}; } // rgb mask bounds Engine::BoundsResult Engine::RgbMaskBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixDepth, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0, p = 0; y < height; y++) { for (x = 0; x < width; x++, i += pixDepth, p++) { if (bitsetVec[p] == 0 || pixDiff > RgbDiff(buf0, buf1, i)) continue; minX = MinUint(minX, x); maxX = MaxUint(maxX, x); minY = MinUint(minY, y); maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / bitsetCount, minX, maxX, minY, maxY}; } // rgb regions bounds std::vector<Engine::BoundsResult> Engine::RgbRegionsBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixDepth, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<Engine::BoundsResult> boundsResultVec(regionsLen, Engine::BoundsResult {0, width - 1 , 0, height - 1, 0}); for (uint_fast32_t y = 0, x = 0, i = 0, p = 0, r = 0; y < height; y++) { for (x = 0; x < width; x++, i += pixDepth, p++) { uint_fast32_t diff = RgbDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[p] == 0 || regionsVec[r].pixDiff > diff) continue; boundsResultVec[r].minX = MinUint(boundsResultVec[r].minX, x); boundsResultVec[r].maxX = MaxUint(boundsResultVec[r].maxX, x); boundsResultVec[r].minY = MinUint(boundsResultVec[r].minY, y); boundsResultVec[r].maxY = MaxUint(boundsResultVec[r].maxY, y); boundsResultVec[r].percent++; } } } for (uint_fast32_t r = 0; r < regionsLen; r++) { boundsResultVec[r].percent = boundsResultVec[r].percent * 100 / regionsVec[r].bitsetCount; } return boundsResultVec; } // if (x > maxX) maxX = x; // if (y > maxY) maxY = y; // if (x < minX) minX = x; // if (y < minY) minY = y;<commit_msg>test bounds<commit_after>#include "engine.h" #include <cstdint> #include <string> #include <vector> // gray all percent uint_fast32_t Engine::GrayAllPercent(const uint_fast32_t pixCount, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0; i < pixCount; i++) { if (pixDiff > GrayDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / pixCount; } // gray mask percent uint_fast32_t Engine::GrayMaskPercent(const uint_fast32_t pixCount, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0; i < pixCount; i++) { if (bitsetVec[i] == 0 || pixDiff > GrayDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / bitsetCount; } // gray regions percent std::vector<uint_fast32_t> Engine::GrayRegionsPercent(const uint_fast32_t pixCount, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<uint_fast32_t> percentResultVec(regionsLen, 0); for (uint_fast32_t i = 0, r = 0; i < pixCount; i++) { uint_fast32_t diff = GrayDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[i] == 0 || regionsVec[r].pixDiff > diff) continue; percentResultVec[r]++; } } for (uint_fast32_t r = 0; r < regionsLen; r++) { percentResultVec[r] = percentResultVec[r] * 100 / regionsVec[r].bitsetCount; } return percentResultVec; } // rgb all percent uint_fast32_t Engine::RgbAllPercent(const uint_fast32_t pixCount, const uint_fast32_t pixDepth, const uint_fast32_t bufLen, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0; i < bufLen; i += pixDepth) { if (pixDiff > RgbDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / pixCount; } // rgb mask percent uint_fast32_t Engine::RgbMaskPercent(const uint_fast32_t pixDepth, const uint_fast32_t bufLen, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t diffs = 0; for (uint_fast32_t i = 0, p = 0; i < bufLen; i += pixDepth, p++) { if (bitsetVec[p] == 0 || pixDiff > RgbDiff(buf0, buf1, i)) continue; diffs++; } return 100 * diffs / bitsetCount; } // rgb regions percent std::vector<uint_fast32_t> Engine::RgbRegionsPercent(const uint_fast32_t pixDepth, const uint_fast32_t bufLen, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<uint_fast32_t> percentResultVec(regionsLen, 0); for (uint_fast32_t i = 0, p = 0, r = 0; i < bufLen; i += pixDepth, p++) { uint_fast32_t diff = RgbDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[p] == 0 || regionsVec[r].pixDiff > diff) continue; percentResultVec[r]++; } } for (uint_fast32_t r = 0; r < regionsLen; r++) { percentResultVec[r] = percentResultVec[r] * 100 / regionsVec[r].bitsetCount; } return percentResultVec; } // gray all bounds Engine::BoundsResult Engine::GrayAllBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixCount, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0; y < height; y++) { for (x = 0; x < width; x++, i++) { if (pixDiff > GrayDiff(buf0, buf1, i)) continue; if (x < minX) { minX = x; } else if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } else if (y > maxY) { maxY = y; } //minX = MinUint(minX, x); //maxX = MaxUint(maxX, x); //minY = MinUint(minY, y); //maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / pixCount, minX, maxX, minY, maxY}; } // gray mask bounds Engine::BoundsResult Engine::GrayMaskBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0; y < height; y++) { for (x = 0; x < width; x++, i++) { if (bitsetVec[i] == 0 || pixDiff > GrayDiff(buf0, buf1, i)) continue; minX = MinUint(minX, x); maxX = MaxUint(maxX, x); minY = MinUint(minY, y); maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / bitsetCount, minX, maxX, minY, maxY}; } // gray regions bounds std::vector<Engine::BoundsResult> Engine::GrayRegionsBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<Engine::BoundsResult> boundsResultVec(regionsLen, Engine::BoundsResult {0, width - 1 , 0, height - 1, 0}); for (uint_fast32_t y = 0, x = 0, i = 0, r = 0; y < height; y++) { for (x = 0; x < width; x++, i++) { uint_fast32_t diff = GrayDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[i] == 0 || regionsVec[r].pixDiff > diff) continue; boundsResultVec[r].minX = MinUint(boundsResultVec[r].minX, x); boundsResultVec[r].maxX = MaxUint(boundsResultVec[r].maxX, x); boundsResultVec[r].minY = MinUint(boundsResultVec[r].minY, y); boundsResultVec[r].maxY = MaxUint(boundsResultVec[r].maxY, y); boundsResultVec[r].percent++; } } } for (uint_fast32_t r = 0; r < regionsLen; r++) { boundsResultVec[r].percent = boundsResultVec[r].percent * 100 / regionsVec[r].bitsetCount; } return boundsResultVec; } // rgb all bounds Engine::BoundsResult Engine::RgbAllBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixCount, const uint_fast32_t pixDepth, const uint_fast32_t pixDiff, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0; y < height; y++) { for (x = 0; x < width; x++, i += pixDepth) { if (pixDiff > RgbDiff(buf0, buf1, i)) continue; minX = MinUint(minX, x); maxX = MaxUint(maxX, x); minY = MinUint(minY, y); maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / pixCount, minX, maxX, minY, maxY}; } // rgb mask bounds Engine::BoundsResult Engine::RgbMaskBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixDepth, const uint_fast32_t pixDiff, const uint_fast32_t bitsetCount, const std::vector<bool> &bitsetVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { uint_fast32_t minX = width - 1, maxX = 0, minY = height - 1, maxY = 0, diffs = 0; for (uint_fast32_t y = 0, x = 0, i = 0, p = 0; y < height; y++) { for (x = 0; x < width; x++, i += pixDepth, p++) { if (bitsetVec[p] == 0 || pixDiff > RgbDiff(buf0, buf1, i)) continue; minX = MinUint(minX, x); maxX = MaxUint(maxX, x); minY = MinUint(minY, y); maxY = MaxUint(maxY, y); diffs++; } } return Engine::BoundsResult {100 * diffs / bitsetCount, minX, maxX, minY, maxY}; } // rgb regions bounds std::vector<Engine::BoundsResult> Engine::RgbRegionsBounds(const uint_fast32_t width, const uint_fast32_t height, const uint_fast32_t pixDepth, const uint_fast32_t minDiff, const uint_fast32_t regionsLen, const std::vector<Engine::Region> &regionsVec, const uint_fast8_t *buf0, const uint_fast8_t *buf1) { std::vector<Engine::BoundsResult> boundsResultVec(regionsLen, Engine::BoundsResult {0, width - 1 , 0, height - 1, 0}); for (uint_fast32_t y = 0, x = 0, i = 0, p = 0, r = 0; y < height; y++) { for (x = 0; x < width; x++, i += pixDepth, p++) { uint_fast32_t diff = RgbDiff(buf0, buf1, i); if (minDiff > diff) continue; for (r = 0; r < regionsLen; r++) { if (regionsVec[r].bitset[p] == 0 || regionsVec[r].pixDiff > diff) continue; boundsResultVec[r].minX = MinUint(boundsResultVec[r].minX, x); boundsResultVec[r].maxX = MaxUint(boundsResultVec[r].maxX, x); boundsResultVec[r].minY = MinUint(boundsResultVec[r].minY, y); boundsResultVec[r].maxY = MaxUint(boundsResultVec[r].maxY, y); boundsResultVec[r].percent++; } } } for (uint_fast32_t r = 0; r < regionsLen; r++) { boundsResultVec[r].percent = boundsResultVec[r].percent * 100 / regionsVec[r].bitsetCount; } return boundsResultVec; } // if (x > maxX) maxX = x; // if (y > maxY) maxY = y; // if (x < minX) minX = x; // if (y < minY) minY = y;<|endoftext|>
<commit_before>//============================================================================ // Name : Shader.cpp // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Shader //============================================================================ #include "Shaders.h" #include <stdlib.h> #ifdef ANDROID #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #else #include "GL/glew.h" #endif #include "../../Core/Buffers/FrameBuffer.h" namespace p3d { Shader::Shader() { } Shader::Shader(uint32 type) { this->type = type; } Shader::~Shader() {} const uint32 &Shader::GetType() const { return type; } void Shader::loadShaderFile(const char* filename) { std::ifstream t(filename); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); shaderString = str.c_str(); } void Shader::loadShaderText(const std::string &text) { shaderString = text; } void Shader::compileShader(uint32* ProgramObject) { std::string shaderType; switch (type) { case ShaderType::VertexShader: shader = glCreateShader(GL_VERTEX_SHADER); shaderType = "Vertex Shader"; break; case ShaderType::FragmentShader: shader = glCreateShader(GL_FRAGMENT_SHADER); shaderType = "Fragment Shader"; break; case ShaderType::GeometryShader: //shader = glCreateShader(GL_GEOMETRY_SHADER); shaderType = "Geometry Shader"; break; } uint32 len = shaderString.length(); // batatas because is a good example :P const char *batatas = shaderString.c_str(); glShaderSource(shader,1,(const GLchar**) &batatas,(const GLint *)&len); glCompileShader(shader); GLint result, length = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if (result==GL_FALSE) { std::string log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); std::stringstream ss;//create a stringstream ss << length; echo(ss.str()); if (length>0) { log.resize(length); glGetShaderInfoLog(shader, length, &result, &log[0]); echo(std::string(shaderType.c_str() + std::string(" COMPILATION ERROR: ") + log.c_str())); } } else { std::string log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); std::stringstream ss;//create a stringstream ss << length; echo(ss.str()); if (length>1) { log.resize(length); glGetShaderInfoLog(shader, length, &result, &log[0]); echo(std::string(shaderType.c_str() + std::string(" COMPILED WITH WARNINGS: ") + log.c_str())); } if (*ProgramObject==0) *ProgramObject = (uint32)glCreateProgram(); // Attach shader glAttachShader(*ProgramObject, shader); // Link Program glLinkProgram(*ProgramObject); // Get Linkage error glGetProgramiv(*ProgramObject, GL_LINK_STATUS, &result); if (result==GL_FALSE) { glGetProgramiv(*ProgramObject, GL_INFO_LOG_LENGTH, &length); log.resize(length); std::stringstream ss;//create a stringstream ss << length; echo(ss.str()); glGetProgramInfoLog(*ProgramObject, length, &result, &log[0]); echo(std::string(shaderType.c_str() + std::string(" LINK ERROR: ") + log.c_str())); } } } void Shader::DeleteShader(uint32 ProgramObject) { if (glIsProgram(ProgramObject)) { if (glIsShader(shader)) { glDetachShader(ProgramObject, shader); glDeleteShader(shader); // std::cout << "Shader Destroyed: " << shader << std::endl; } // else std::cout << "Shader Not Found: " << shader << std::endl; } // else std::cout << "Shader Program Object Not Found: " << ProgramObject << std::endl; } void Shader::DeleteProgram(uint32* ProgramObject) { if (glIsProgram(*ProgramObject)) { glDeleteProgram(*ProgramObject); // std::cout << "Shader Program Destroyed: " << *ProgramObject << std::endl; *ProgramObject = 0; } // else std::cout << "Shader Program Object Not Found: " << *ProgramObject << std::endl; } // Get positions int32 Shader::GetUniformLocation(const uint32 &program, const std::string &name) { return glGetUniformLocation(program, name.c_str()); } int32 Shader::GetAttributeLocation(const uint32 &program, const std::string &name) { return glGetAttribLocation(program, name.c_str()); } void Shader::SendUniform(const Uniform::Uniform &uniform, const int32 &Handle) { if (Handle>-1 && uniform.ElementCount>0) switch(uniform.Type) { case Uniform::DataType::Int: { glUniform1iv(Handle,uniform.ElementCount,(int*)&uniform.Value[0]); break; } case Uniform::DataType::Float: { glUniform1fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Vec2: { glUniform2fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Vec3: { glUniform3fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Vec4: { glUniform4fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Matrix: { glUniformMatrix4fv(Handle,uniform.ElementCount,false,(f32*)&uniform.Value[0]); break; } } } void Shader::SendUniform(const Uniform::Uniform &uniform, void* data, const int32 &Handle, const uint32 &elementCount) { if (Handle>-1 && elementCount>0) { switch(uniform.Type) { case Uniform::DataType::Int: { glUniform1iv(Handle,elementCount,(int*)data); break; } case Uniform::DataType::Float: { glUniform1fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Vec2: { glUniform2fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Vec3: { glUniform3fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Vec4: { glUniform4fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Matrix: { glUniformMatrix4fv(Handle,elementCount,false,(f32*)data); break; } } } } } <commit_msg>Fix to last commit<commit_after>//============================================================================ // Name : Shader.cpp // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Shader //============================================================================ #include "Shaders.h" #include <stdlib.h> #ifdef ANDROID #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #else #include "GL/glew.h" #endif #include "../../Core/Buffers/FrameBuffer.h" namespace p3d { Shader::Shader() { } Shader::Shader(uint32 type) { this->type = type; } Shader::~Shader() {} const uint32 &Shader::GetType() const { return type; } void Shader::loadShaderFile(const char* filename) { std::ifstream t(filename); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); shaderString = str.c_str(); } void Shader::loadShaderText(const std::string &text) { shaderString = text; } void Shader::compileShader(uint32* ProgramObject) { std::string shaderType; switch (type) { case ShaderType::VertexShader: shader = glCreateShader(GL_VERTEX_SHADER); shaderType = "Vertex Shader"; break; case ShaderType::FragmentShader: shader = glCreateShader(GL_FRAGMENT_SHADER); shaderType = "Fragment Shader"; break; case ShaderType::GeometryShader: //shader = glCreateShader(GL_GEOMETRY_SHADER); shaderType = "Geometry Shader"; break; } uint32 len = shaderString.length(); // batatas because is a good example :P const char *batatas = shaderString.c_str(); glShaderSource(shader,1,(const GLchar**) &batatas,(const GLint *)&len); glCompileShader(shader); GLint result, length = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if (result==GL_FALSE) { std::string log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); if (length>0) { log.resize(length); glGetShaderInfoLog(shader, length, &result, &log[0]); echo(std::string(shaderType.c_str() + std::string(" COMPILATION ERROR: ") + log.c_str())); } } else { std::string log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); if (length>0) { log.resize(length); glGetShaderInfoLog(shader, length, &result, &log[0]); echo(std::string(shaderType.c_str() + std::string(" COMPILED WITH WARNINGS: ") + log.c_str())); } if (*ProgramObject==0) *ProgramObject = (uint32)glCreateProgram(); // Attach shader glAttachShader(*ProgramObject, shader); // Link Program glLinkProgram(*ProgramObject); // Get Linkage error glGetProgramiv(*ProgramObject, GL_LINK_STATUS, &result); if (result==GL_FALSE) { glGetProgramiv(*ProgramObject, GL_INFO_LOG_LENGTH, &length); log.resize(length); glGetProgramInfoLog(*ProgramObject, length, &result, &log[0]); echo(std::string(shaderType.c_str() + std::string(" LINK ERROR: ") + log.c_str())); } } } void Shader::DeleteShader(uint32 ProgramObject) { if (glIsProgram(ProgramObject)) { if (glIsShader(shader)) { glDetachShader(ProgramObject, shader); glDeleteShader(shader); // std::cout << "Shader Destroyed: " << shader << std::endl; } // else std::cout << "Shader Not Found: " << shader << std::endl; } // else std::cout << "Shader Program Object Not Found: " << ProgramObject << std::endl; } void Shader::DeleteProgram(uint32* ProgramObject) { if (glIsProgram(*ProgramObject)) { glDeleteProgram(*ProgramObject); // std::cout << "Shader Program Destroyed: " << *ProgramObject << std::endl; *ProgramObject = 0; } // else std::cout << "Shader Program Object Not Found: " << *ProgramObject << std::endl; } // Get positions int32 Shader::GetUniformLocation(const uint32 &program, const std::string &name) { return glGetUniformLocation(program, name.c_str()); } int32 Shader::GetAttributeLocation(const uint32 &program, const std::string &name) { return glGetAttribLocation(program, name.c_str()); } void Shader::SendUniform(const Uniform::Uniform &uniform, const int32 &Handle) { if (Handle>-1 && uniform.ElementCount>0) switch(uniform.Type) { case Uniform::DataType::Int: { glUniform1iv(Handle,uniform.ElementCount,(int*)&uniform.Value[0]); break; } case Uniform::DataType::Float: { glUniform1fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Vec2: { glUniform2fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Vec3: { glUniform3fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Vec4: { glUniform4fv(Handle,uniform.ElementCount,(f32*)&uniform.Value[0]); break; } case Uniform::DataType::Matrix: { glUniformMatrix4fv(Handle,uniform.ElementCount,false,(f32*)&uniform.Value[0]); break; } } } void Shader::SendUniform(const Uniform::Uniform &uniform, void* data, const int32 &Handle, const uint32 &elementCount) { if (Handle>-1 && elementCount>0) { switch(uniform.Type) { case Uniform::DataType::Int: { glUniform1iv(Handle,elementCount,(int*)data); break; } case Uniform::DataType::Float: { glUniform1fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Vec2: { glUniform2fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Vec3: { glUniform3fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Vec4: { glUniform4fv(Handle,elementCount,(f32*)data); break; } case Uniform::DataType::Matrix: { glUniformMatrix4fv(Handle,elementCount,false,(f32*)data); break; } } } } } <|endoftext|>
<commit_before>#include <babylon/samples/samples_index.h> #include <babylon/babylon_stl_util.h> #include <babylon/core/string.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/samples/animations/_animations_samples_index.h> #include <babylon/samples/cameras/_cameras_samples_index.h> #include <babylon/samples/collisionsandintersections/_collisions_and_intersections_samples_index.h> #include <babylon/samples/extensions/_extensions_samples_index.h> #include <babylon/samples/lights/_lights_samples_index.h> #include <babylon/samples/loaders/_loaders_samples_index.h> #include <babylon/samples/materials/_materials_samples_index.h> #include <babylon/samples/materialslibrary/_materials_library_samples_index.h> #include <babylon/samples/meshes/_meshes_samples_index.h> #include <babylon/samples/optimizations/_optimizations_samples_index.h> #include <babylon/samples/particles/_particles_samples_index.h> #include <babylon/samples/proceduraltextureslibrary/_procedural_textures_library_samples_index.h> #include <babylon/samples/shadows/_shadows_samples_index.h> #include <babylon/samples/specialfx/_special_fx_samples_index.h> #include <babylon/samples/textures/_textures_samples_index.h> #include <nlohmann/json.hpp> #include <iostream> #include <fstream> namespace BABYLON { namespace Samples { SamplesIndex::SamplesIndex() { _samplesFailures = { {"BlurModeForMirrorsScene", SampleFailureReason::empty3d}, {"ColoredRibbonScene", SampleFailureReason::outOfBoundAccess}, {"CircleCurvesFromBeziersScene", SampleFailureReason::empty3d}, {"EdgesRenderScene", SampleFailureReason::outOfBoundAccess}, {"HighlightLayerScene", SampleFailureReason::incomplete3d}, {"InnerMeshPointsScene", SampleFailureReason::outOfBoundAccess}, {"LinesMeshSpiralScene", SampleFailureReason::empty3d}, {"LorenzAttractorScene", SampleFailureReason::empty3d}, {"MorphTargetsScene", SampleFailureReason::broken}, {"MultiSampleRenderTargetsScene", SampleFailureReason::empty3d}, {"PBRMaterialCheckerORMScene", SampleFailureReason::broken}, {"PBRMaterialScene", SampleFailureReason::broken}, {"PBRMetallicRoughnessGoldMaterialScene", SampleFailureReason::broken}, {"PBRMetallicRoughnessMaterialScene", SampleFailureReason::outOfBoundAccess}, {"PBRMetallicRoughnessTextureMaterialScene", SampleFailureReason::broken}, {"ShaderMaterialWarpSpeedScene", SampleFailureReason::empty3d}, }; // Initialize the samples index _samplesIndex = { // Animations samples {_AnimationsSamplesIndex::CategoryName(), _AnimationsSamplesIndex()}, // Cameras samples {_CamerasSamplesIndex::CategoryName(), _CamerasSamplesIndex()}, // Collisions and Intersections samples {_CollisionsAndIntersectionsSamplesIndex::CategoryName(), _CollisionsAndIntersectionsSamplesIndex()}, // Extensions samples {_ExtensionsSamplesIndex::CategoryName(), _ExtensionsSamplesIndex()}, // Lights samples {_LightsSamplesIndex::CategoryName(), _LightsSamplesIndex()}, // Loaders - babylon format {_LoadersBabylonSamplesIndex::CategoryName(), _LoadersBabylonSamplesIndex()}, #ifdef WITH_LOADERS // Loaders - glTF format {_LoadersGLTFSamplesIndex::CategoryName(), _LoadersGLTFSamplesIndex()}, #endif // Materials samples {_MaterialsSamplesIndex::CategoryName(), _MaterialsSamplesIndex()}, // // Materials Library samples {_MaterialsLibrarySamplesIndex::CategoryName(), _MaterialsLibrarySamplesIndex()}, // Meshes samples {_MeshesSamplesIndex::CategoryName(), _MeshesSamplesIndex()}, // Optimizations samples {_OptimizationsSamplesIndex::CategoryName(), _OptimizationsSamplesIndex()}, // Particles samples {_ParticlesSamplesIndex::CategoryName(), _ParticlesSamplesIndex()}, // Procedural Textures Library samples {_ProceduralTexturesLibrarySamplesIndex::CategoryName(), _ProceduralTexturesLibrarySamplesIndex()}, // Shadows samples {_ShadowsSamplesIndex::CategoryName(), _ShadowsSamplesIndex()}, // Special FX samples {_SpecialFXSamplesIndex::CategoryName(), _SpecialFXSamplesIndex()}, // Textures samples {_TexturesSamplesIndex::CategoryName(), _TexturesSamplesIndex()}, }; } SamplesIndex::~SamplesIndex() { } bool SamplesIndex::isSampleEnabled(const std::string& sampleName) const { for (const auto& item : _samplesIndex) { if (stl_util::contains(item.second.samples(), sampleName)) { return std::get<0>(item.second.samples().at(sampleName)); } } return false; } std::optional<BABYLON::Samples::SampleFailureReason> SamplesIndex::doesSampleFail(const std::string& sampleName) const { if (_samplesFailures.find(sampleName) == _samplesFailures.end()) return std::nullopt; else return _samplesFailures.at(sampleName); } bool SamplesIndex::sampleExists(const std::string& sampleName) const { for (const auto& item : _samplesIndex) { if (stl_util::contains(item.second.samples(), sampleName)) { return true; } } return false; } nlohmann::json ReadSampleInfoFile() { std::ifstream is("samples_info.json"); if (! is.good()) is = std::ifstream("../samples_info.json"); if (! is.good()) is = std::ifstream("../../samples_info.json"); if (is.good()) { nlohmann::json j; is >> j; return j; } else return nlohmann::json(); } SampleInfo SamplesIndex::getSampleInfo(const std::string& sampleName) const { static nlohmann::json _samplesInfo = ReadSampleInfoFile(); static std::map<std::string, SampleInfo> cache; if (cache.find(sampleName) != cache.end()) return cache.at(sampleName); SampleInfo result; for (const auto & element : _samplesInfo) { if (element["sample_name"] == sampleName) { result.Brief = element["brief"]; result.HeaderFile = element["header_file"]; result.SourceFile = element["source_file"]; for (const auto & link : element["links"]) { result.Links.push_back(link); } } } cache[sampleName] = result; return result; } std::vector<std::string> SamplesIndex::getSampleNames() const { // Extract the enabled sample names from the map std::vector<std::string> sampleNames; for (const auto& samplesCategory : _samplesIndex) { for (const auto& element : samplesCategory.second.samples()) { // Check if enabled if (std::get<0>(element.second)) { sampleNames.emplace_back(element.first); } } } // Sort the vector with sample names in ascending order std::sort(sampleNames.begin(), sampleNames.end()); return sampleNames; } std::vector<std::string> SamplesIndex::getCategoryNames() const { // Extract the category names auto categoryNames = stl_util::extract_keys(_samplesIndex); // Sort the vector with category names in ascending order std::sort(categoryNames.begin(), categoryNames.end()); return categoryNames; } bool SamplesIndex::categoryExists(const std::string& categoryNameToSearch) const { bool _categoryExists = false; // Extract the category names auto categoryNames = stl_util::extract_keys(_samplesIndex); // Search for sample for (const auto& categoryName : categoryNames) { if (categoryName == categoryNameToSearch) { _categoryExists = true; break; } } return _categoryExists; } std::vector<std::string> SamplesIndex::getSampleNamesInCategory(const std::string& categoryName) const { // Extract the enabled sample names for the given category from the map std::vector<std::string> sampleNames; if (stl_util::contains(_samplesIndex, categoryName)) { const auto& samplesCategory = _samplesIndex.at(categoryName); for (const auto& element : samplesCategory.samples()) { // Check if enabled if (std::get<0>(element.second)) { sampleNames.emplace_back(element.first); } } } // Sort the vector with sample names in ascending order std::sort(sampleNames.begin(), sampleNames.end()); return sampleNames; } IRenderableScenePtr SamplesIndex::createRenderableScene(const std::string& sampleName, ICanvas* iCanvas) const { for (const auto& item : _samplesIndex) { if (stl_util::contains(item.second.samples(), sampleName)) { return std::get<1>(item.second.samples().at(sampleName))(iCanvas); } } return nullptr; } void SamplesIndex::listSamples() { auto categories = getCategoryNames(); for (const auto & category : categories) { std::cout << "********************************************" << "\n"; std::cout << "Category: " << category << "\n"; std::cout << "********************************************" << "\n"; auto samples = getSampleNamesInCategory(category); for (const auto & sample : samples) { std::string ko = (!isSampleEnabled(sample)) ? " (KO)" : ""; std::cout << sample << ko << "\n"; } } } std::string SampleFailureReason_Str(SampleFailureReason s) { switch (s) { case SampleFailureReason::blankDisplay: return "Blank display"; break; case SampleFailureReason::outOfBoundAccess : return "Out of bounds access"; break; case SampleFailureReason::processHung: return "Process hung"; break; case SampleFailureReason::invalidComparator: return "Invalid comparator"; break; case SampleFailureReason::vectorIteratorInvalid: return "vector iterators in range are from different containers"; break; case SampleFailureReason::empty3d: return "3D rendering is empty"; break; case SampleFailureReason::readAccessViolation: return "Read Access Violation"; break; case SampleFailureReason::incomplete3d: return "Incomplete 3d (black textures and co)"; break; case SampleFailureReason::broken: return "Broken (bad rendering and/or bad behavior)"; break; default: throw "Unhandled enum!"; } } } // end of namespace Samples } // end of namespace BABYLON <commit_msg>the samples index file is now using lower case<commit_after>#include <babylon/samples/samples_index.h> #include <babylon/babylon_stl_util.h> #include <babylon/core/string.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/samples/animations/_animations_samples_index.h> #include <babylon/samples/cameras/_cameras_samples_index.h> #include <babylon/samples/collisionsandintersections/_collisions_and_intersections_samples_index.h> #include <babylon/samples/extensions/_extensions_samples_index.h> #include <babylon/samples/lights/_lights_samples_index.h> #include <babylon/samples/loaders/_loaders_samples_index.h> #include <babylon/samples/materials/_materials_samples_index.h> #include <babylon/samples/materialslibrary/_materials_library_samples_index.h> #include <babylon/samples/meshes/_meshes_samples_index.h> #include <babylon/samples/optimizations/_optimizations_samples_index.h> #include <babylon/samples/particles/_particles_samples_index.h> #include <babylon/samples/proceduraltextureslibrary/_procedural_textures_library_samples_index.h> #include <babylon/samples/shadows/_shadows_samples_index.h> #include <babylon/samples/specialfx/_special_fx_samples_index.h> #include <babylon/samples/textures/_textures_samples_index.h> #include <nlohmann/json.hpp> #include <iostream> #include <fstream> namespace BABYLON { namespace Samples { SamplesIndex::SamplesIndex() { _samplesFailures = { {"BlurModeForMirrorsScene", SampleFailureReason::empty3d}, {"ColoredRibbonScene", SampleFailureReason::outOfBoundAccess}, {"CircleCurvesFromBeziersScene", SampleFailureReason::empty3d}, {"EdgesRenderScene", SampleFailureReason::outOfBoundAccess}, {"HighlightLayerScene", SampleFailureReason::incomplete3d}, {"InnerMeshPointsScene", SampleFailureReason::outOfBoundAccess}, {"LinesMeshSpiralScene", SampleFailureReason::empty3d}, {"LorenzAttractorScene", SampleFailureReason::empty3d}, {"MorphTargetsScene", SampleFailureReason::broken}, {"MultiSampleRenderTargetsScene", SampleFailureReason::empty3d}, {"PBRMaterialCheckerORMScene", SampleFailureReason::broken}, {"PBRMaterialScene", SampleFailureReason::broken}, {"PBRMetallicRoughnessGoldMaterialScene", SampleFailureReason::broken}, {"PBRMetallicRoughnessMaterialScene", SampleFailureReason::outOfBoundAccess}, {"PBRMetallicRoughnessTextureMaterialScene", SampleFailureReason::broken}, {"ShaderMaterialWarpSpeedScene", SampleFailureReason::empty3d}, }; // Initialize the samples index _samplesIndex = { // Animations samples {_AnimationsSamplesIndex::CategoryName(), _AnimationsSamplesIndex()}, // Cameras samples {_CamerasSamplesIndex::CategoryName(), _CamerasSamplesIndex()}, // Collisions and Intersections samples {_CollisionsAndIntersectionsSamplesIndex::CategoryName(), _CollisionsAndIntersectionsSamplesIndex()}, // Extensions samples {_ExtensionsSamplesIndex::CategoryName(), _ExtensionsSamplesIndex()}, // Lights samples {_LightsSamplesIndex::CategoryName(), _LightsSamplesIndex()}, // Loaders - babylon format {_LoadersBabylonSamplesIndex::CategoryName(), _LoadersBabylonSamplesIndex()}, #ifdef WITH_LOADERS // Loaders - glTF format {_LoadersGLTFSamplesIndex::CategoryName(), _LoadersGLTFSamplesIndex()}, #endif // Materials samples {_MaterialsSamplesIndex::CategoryName(), _MaterialsSamplesIndex()}, // // Materials Library samples {_MaterialsLibrarySamplesIndex::CategoryName(), _MaterialsLibrarySamplesIndex()}, // Meshes samples {_MeshesSamplesIndex::CategoryName(), _MeshesSamplesIndex()}, // Optimizations samples {_OptimizationsSamplesIndex::CategoryName(), _OptimizationsSamplesIndex()}, // Particles samples {_ParticlesSamplesIndex::CategoryName(), _ParticlesSamplesIndex()}, // Procedural Textures Library samples {_ProceduralTexturesLibrarySamplesIndex::CategoryName(), _ProceduralTexturesLibrarySamplesIndex()}, // Shadows samples {_ShadowsSamplesIndex::CategoryName(), _ShadowsSamplesIndex()}, // Special FX samples {_SpecialFXSamplesIndex::CategoryName(), _SpecialFXSamplesIndex()}, // Textures samples {_TexturesSamplesIndex::CategoryName(), _TexturesSamplesIndex()}, }; } SamplesIndex::~SamplesIndex() { } bool SamplesIndex::isSampleEnabled(const std::string& sampleName) const { for (const auto& item : _samplesIndex) { if (stl_util::contains(item.second.samples(), sampleName)) { return std::get<0>(item.second.samples().at(sampleName)); } } return false; } std::optional<BABYLON::Samples::SampleFailureReason> SamplesIndex::doesSampleFail(const std::string& sampleName) const { if (_samplesFailures.find(sampleName) == _samplesFailures.end()) return std::nullopt; else return _samplesFailures.at(sampleName); } bool SamplesIndex::sampleExists(const std::string& sampleName) const { for (const auto& item : _samplesIndex) { if (stl_util::contains(item.second.samples(), sampleName)) { return true; } } return false; } nlohmann::json ReadSampleInfoFile() { std::ifstream is("samples_info.json"); if (! is.good()) is = std::ifstream("../samples_info.json"); if (! is.good()) is = std::ifstream("../../samples_info.json"); if (is.good()) { nlohmann::json j; is >> j; return j; } else return nlohmann::json(); } SampleInfo SamplesIndex::getSampleInfo(const std::string& sampleNameMixedCase) const { static nlohmann::json _samplesInfo = ReadSampleInfoFile(); static std::map<std::string, SampleInfo> cache; std::string sampleNameLowerCase; for (auto c : sampleNameMixedCase) sampleNameLowerCase += static_cast<char>(std::tolower(c)); if (cache.find(sampleNameLowerCase) != cache.end()) return cache.at(sampleNameLowerCase); SampleInfo result; for (const auto & element : _samplesInfo) { if (element["sample_name"] == sampleNameLowerCase) { result.Brief = element["brief"]; result.HeaderFile = element["header_file"]; result.SourceFile = element["source_file"]; for (const auto & link : element["links"]) { result.Links.push_back(link); } } } cache[sampleNameLowerCase] = result; return result; } std::vector<std::string> SamplesIndex::getSampleNames() const { // Extract the enabled sample names from the map std::vector<std::string> sampleNames; for (const auto& samplesCategory : _samplesIndex) { for (const auto& element : samplesCategory.second.samples()) { // Check if enabled if (std::get<0>(element.second)) { sampleNames.emplace_back(element.first); } } } // Sort the vector with sample names in ascending order std::sort(sampleNames.begin(), sampleNames.end()); return sampleNames; } std::vector<std::string> SamplesIndex::getCategoryNames() const { // Extract the category names auto categoryNames = stl_util::extract_keys(_samplesIndex); // Sort the vector with category names in ascending order std::sort(categoryNames.begin(), categoryNames.end()); return categoryNames; } bool SamplesIndex::categoryExists(const std::string& categoryNameToSearch) const { bool _categoryExists = false; // Extract the category names auto categoryNames = stl_util::extract_keys(_samplesIndex); // Search for sample for (const auto& categoryName : categoryNames) { if (categoryName == categoryNameToSearch) { _categoryExists = true; break; } } return _categoryExists; } std::vector<std::string> SamplesIndex::getSampleNamesInCategory(const std::string& categoryName) const { // Extract the enabled sample names for the given category from the map std::vector<std::string> sampleNames; if (stl_util::contains(_samplesIndex, categoryName)) { const auto& samplesCategory = _samplesIndex.at(categoryName); for (const auto& element : samplesCategory.samples()) { // Check if enabled if (std::get<0>(element.second)) { sampleNames.emplace_back(element.first); } } } // Sort the vector with sample names in ascending order std::sort(sampleNames.begin(), sampleNames.end()); return sampleNames; } IRenderableScenePtr SamplesIndex::createRenderableScene(const std::string& sampleName, ICanvas* iCanvas) const { for (const auto& item : _samplesIndex) { if (stl_util::contains(item.second.samples(), sampleName)) { return std::get<1>(item.second.samples().at(sampleName))(iCanvas); } } return nullptr; } void SamplesIndex::listSamples() { auto categories = getCategoryNames(); for (const auto & category : categories) { std::cout << "********************************************" << "\n"; std::cout << "Category: " << category << "\n"; std::cout << "********************************************" << "\n"; auto samples = getSampleNamesInCategory(category); for (const auto & sample : samples) { std::string ko = (!isSampleEnabled(sample)) ? " (KO)" : ""; std::cout << sample << ko << "\n"; } } } std::string SampleFailureReason_Str(SampleFailureReason s) { switch (s) { case SampleFailureReason::blankDisplay: return "Blank display"; break; case SampleFailureReason::outOfBoundAccess : return "Out of bounds access"; break; case SampleFailureReason::processHung: return "Process hung"; break; case SampleFailureReason::invalidComparator: return "Invalid comparator"; break; case SampleFailureReason::vectorIteratorInvalid: return "vector iterators in range are from different containers"; break; case SampleFailureReason::empty3d: return "3D rendering is empty"; break; case SampleFailureReason::readAccessViolation: return "Read Access Violation"; break; case SampleFailureReason::incomplete3d: return "Incomplete 3d (black textures and co)"; break; case SampleFailureReason::broken: return "Broken (bad rendering and/or bad behavior)"; break; default: throw "Unhandled enum!"; } } } // end of namespace Samples } // end of namespace BABYLON <|endoftext|>
<commit_before>/** * @file neighborreduce.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2021-11-05 * * @copyright Copyright (c) 2021 * */ #pragma once #include <gunrock/cuda/context.hxx> #include <gunrock/error.hxx> #include <gunrock/util/type_limits.hxx> #include <gunrock/framework/operators/configs.hxx> #include <moderngpu/kernel_segreduce.hxx> namespace gunrock { namespace operators { namespace neighborreduce { /** * @brief Neighbor reduce is an operator that performs reduction on the segments * of neighbors (or data associated with the neighbors), where each segment is * defined by the source vertex. Another simple way to understand this operator * is to perform advance and then reduction on the resultant traversal. * * @par Overview * Neighbor reduce operator, built on top of segmented reduction. This is * a very limited approach to neighbor reduce, and only gives you the edge per * advance. It's only implemented on the entire graph (frontiers not yet * supported). * * @tparam input_t advance input type (advance_io_type_t::graph supported) * @tparam graph_t graph type. * @tparam enactor_t enactor type. * @tparam output_t output type. * @tparam operator_t user-defined lambda function. * @tparam arithmetic_t binary function, arithmetic operator such as sum, max, * min, etc. * @param G graph to perform advance-reduce on. * @param E enactor structure (not used as of right now). * @param output output buffer. * @param op user-defined lambda function. * @param arithmetic_op arithmetic operator (binary). * @param init_value initial value for the reduction. * @param context cuda context (@see cuda::multi_context_t). */ template <advance_io_type_t input_t = advance_io_type_t::graph, typename graph_t, typename enactor_t, typename output_t, typename operator_t, typename arithmetic_t> void execute(graph_t& G, enactor_t* E, output_t* output, operator_t op, arithmetic_t arithmetic_op, output_t init_value, cuda::multi_context_t& context) { if (context.size() == 1) { auto context0 = context.get_context(0); using find_csr_t = typename graph_t::graph_csr_view_t; if (!(G.template contains_representation<find_csr_t>())) { error::throw_if_exception(cudaErrorUnknown, "CSR sparse-matrix representation " "required for neighborreduce operator."); } // TODO: Throw an exception if input_t is not advance_io_type_t::graph. mgpu::transform_segreduce(op, G.get_number_of_edges(), G.get_row_offsets(), G.get_number_of_vertices(), output, arithmetic_op, init_value, *(context0->mgpu())); } } } // namespace neighborreduce } // namespace operators } // namespace gunrock<commit_msg>Another implementation of neighborreduce. Uses lbs_segreduce instead of transform_segreduce. Can be used to optimize the vertex lookup and also support neighborreduce on frontiers instead of just on graphs.<commit_after>/** * @file neighborreduce.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2021-11-05 * * @copyright Copyright (c) 2021 * */ #pragma once #include <gunrock/cuda/context.hxx> #include <gunrock/error.hxx> #include <gunrock/util/type_limits.hxx> #include <gunrock/framework/operators/configs.hxx> #include <moderngpu/kernel_segreduce.hxx> // #define LBS_SEGREDUCE 1 namespace gunrock { namespace operators { namespace neighborreduce { /** * @brief Neighbor reduce is an operator that performs reduction on the segments * of neighbors (or data associated with the neighbors), where each segment is * defined by the source vertex. Another simple way to understand this operator * is to perform advance and then reduction on the resultant traversal. * * @par Overview * Neighbor reduce operator, built on top of segmented reduction. This is * a very limited approach to neighbor reduce, and only gives you the edge per * advance. It's only implemented on the entire graph (frontiers not yet * supported). * * @tparam input_t advance input type (advance_io_type_t::graph supported) * @tparam graph_t graph type. * @tparam enactor_t enactor type. * @tparam output_t output type. * @tparam operator_t user-defined lambda function. * @tparam arithmetic_t binary function, arithmetic operator such as sum, max, * min, etc. * @param G graph to perform advance-reduce on. * @param E enactor structure (not used as of right now). * @param output output buffer. * @param op user-defined lambda function. * @param arithmetic_op arithmetic operator (binary). * @param init_value initial value for the reduction. * @param context cuda context (@see cuda::multi_context_t). */ template <advance_io_type_t input_t = advance_io_type_t::graph, typename graph_t, typename enactor_t, typename output_t, typename operator_t, typename arithmetic_t> void execute(graph_t& G, enactor_t* E, output_t* output, operator_t op, arithmetic_t arithmetic_op, output_t init_value, cuda::multi_context_t& context) { if (context.size() == 1) { auto context0 = context.get_context(0); using type_t = typename graph_t::vertex_type; using find_csr_t = typename graph_t::graph_csr_view_t; if (!(G.template contains_representation<find_csr_t>())) { error::throw_if_exception(cudaErrorUnknown, "CSR sparse-matrix representation " "required for neighborreduce operator."); } #ifndef LBS_SEGREDUCE // TODO: Throw an exception if input_t is not advance_io_type_t::graph. mgpu::transform_segreduce(op, G.get_number_of_edges(), G.get_row_offsets(), G.get_number_of_vertices(), output, arithmetic_op, init_value, *(context0->mgpu())); #else auto f = [=] __device__(std::size_t index, std::size_t seg, std::size_t rank) { auto v = type_t(seg); auto start_edge = G.get_starting_edge(v); auto e = start_edge + rank; return op(e); }; // TODO: Throw an exception if input_t is not advance_io_type_t::graph. mgpu::lbs_segreduce(f, G.get_number_of_edges(), G.get_row_offsets(), G.get_number_of_vertices(), output, arithmetic_op, init_value, *(context0->mgpu())); #endif } } } // namespace neighborreduce } // namespace operators } // namespace gunrock<|endoftext|>
<commit_before>//**************************************************************************** // Copyright © 2015 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2015-06-03 // // This file is distributed under the Simplified BSD License. // License text is included with the source distribution. //**************************************************************************** #pragma once #include <cstdint> #include <utility> namespace Ystring { namespace EncodedString { template <typename Decoder, typename UnaryPred> bool advanceIf(Decoder& str, UnaryPred pred) { auto pos = str.getLogicalBegin(); char32_t ch; if (!str.next(ch) || !pred(ch)) { str.setLogicalBegin(pos); return false; } return true; } template <typename Decoder, typename UnaryPred> bool advanceIfNot(Decoder& str, UnaryPred pred) { auto pos = str.getLogicalBegin(); char32_t ch; if (!str.next(ch) || pred(ch)) { str.setLogicalBegin(pos); return false; } return true; } template <typename Decoder1, typename Decoder2, typename BinaryPred> bool advanceIfEqual(Decoder1& a, Decoder2& b, BinaryPred compare) { auto aPos = a.getLogicalBegin(); auto bPos = b.getLogicalBegin(); char32_t aCh, bCh; bool aNext = a.next(aCh); bool bNext = b.next(bCh); if (!aNext && !bNext) return false; if (!aNext || !bNext || !compare(aCh, bCh)) { a.setLogicalBegin(aPos); b.setLogicalBegin(bPos); return false; } return true; } template <typename Decoder, typename UnaryPred> bool advanceUntil(Decoder& str, UnaryPred pred) { while (advanceIfNot(str, pred)) {} return str.begin() != str.end(); } template <typename Decoder, typename UnaryPred> bool advanceWhile(Decoder& str, UnaryPred pred) { while (advanceIf(str, pred)) {} return str.begin() == str.end(); } template <typename Decoder1, typename Decoder2, typename BinaryPred> bool advanceWhileEqual(Decoder1& str, Decoder2& cmp, BinaryPred compare) { while (advanceIfEqual(str, cmp, compare)) {} return cmp.begin() == cmp.end(); } template <typename Decoder1, typename Decoder2> bool advanceWhileEqual(Decoder1& str, Decoder2& cmp) { return advanceWhileEqual(str, cmp, [](char32_t a, char32_t b){return a == b;}); } template <typename Decoder1, typename Decoder2, typename BinaryPred> Decoder1 search(Decoder1& str, Decoder2& cmp, BinaryPred compare) { while (true) { auto copyOfStr = str; auto copyOfCmp = cmp; if (advanceWhileEqual(copyOfStr, copyOfCmp, compare)) { str.setLogicalEnd(copyOfStr.getLogicalBegin()); std::swap(str, copyOfStr); return copyOfStr; } if (!str.skip()) break; } return str; } template <typename Decoder1, typename Decoder2> Decoder1 search(Decoder1& str, Decoder2& cmp) { return search(str, cmp, [](char32_t a, char32_t b){return a == b;}); } }} <commit_msg>MSVC 2019 requires this namespace prefix for some reason.<commit_after>//**************************************************************************** // Copyright © 2015 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2015-06-03 // // This file is distributed under the Simplified BSD License. // License text is included with the source distribution. //**************************************************************************** #pragma once #include <cstdint> #include <utility> namespace Ystring { namespace EncodedString { template <typename Decoder, typename UnaryPred> bool advanceIf(Decoder& str, UnaryPred pred) { auto pos = str.getLogicalBegin(); char32_t ch; if (!str.next(ch) || !pred(ch)) { str.setLogicalBegin(pos); return false; } return true; } template <typename Decoder, typename UnaryPred> bool advanceIfNot(Decoder& str, UnaryPred pred) { auto pos = str.getLogicalBegin(); char32_t ch; if (!str.next(ch) || pred(ch)) { str.setLogicalBegin(pos); return false; } return true; } template <typename Decoder1, typename Decoder2, typename BinaryPred> bool advanceIfEqual(Decoder1& a, Decoder2& b, BinaryPred compare) { auto aPos = a.getLogicalBegin(); auto bPos = b.getLogicalBegin(); char32_t aCh, bCh; bool aNext = a.next(aCh); bool bNext = b.next(bCh); if (!aNext && !bNext) return false; if (!aNext || !bNext || !compare(aCh, bCh)) { a.setLogicalBegin(aPos); b.setLogicalBegin(bPos); return false; } return true; } template <typename Decoder, typename UnaryPred> bool advanceUntil(Decoder& str, UnaryPred pred) { while (advanceIfNot(str, pred)) {} return str.begin() != str.end(); } template <typename Decoder, typename UnaryPred> bool advanceWhile(Decoder& str, UnaryPred pred) { while (advanceIf(str, pred)) {} return str.begin() == str.end(); } template <typename Decoder1, typename Decoder2, typename BinaryPred> bool advanceWhileEqual(Decoder1& str, Decoder2& cmp, BinaryPred compare) { while (advanceIfEqual(str, cmp, compare)) {} return cmp.begin() == cmp.end(); } template <typename Decoder1, typename Decoder2> bool advanceWhileEqual(Decoder1& str, Decoder2& cmp) { return advanceWhileEqual(str, cmp, [](char32_t a, char32_t b){return a == b;}); } template <typename Decoder1, typename Decoder2, typename BinaryPred> Decoder1 search(Decoder1& str, Decoder2& cmp, BinaryPred compare) { while (true) { auto copyOfStr = str; auto copyOfCmp = cmp; if (advanceWhileEqual(copyOfStr, copyOfCmp, compare)) { str.setLogicalEnd(copyOfStr.getLogicalBegin()); std::swap(str, copyOfStr); return copyOfStr; } if (!str.skip()) break; } return str; } template <typename Decoder1, typename Decoder2> Decoder1 search(Decoder1& str, Decoder2& cmp) { return Ystring::EncodedString::search(str, cmp, [](char32_t a, char32_t b){return a == b;}); } }} <|endoftext|>
<commit_before>// @(#)root/eve:$Id$ // Author: Matevz Tadel 2007 /************************************************************************* * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TEveArrowGL.h" #include "TEveArrow.h" #include "TGLRnrCtx.h" #include "TGLIncludes.h" #include "TGLUtil.h" #include "TGLQuadric.h" // #include "TAttLine.h" //______________________________________________________________________________ // OpenGL renderer class for TEveArrow. // ClassImp(TEveArrowGL); //______________________________________________________________________________ TEveArrowGL::TEveArrowGL() : TGLObject(), fM(0) { // Constructor. } /******************************************************************************/ //______________________________________________________________________________ Bool_t TEveArrowGL::SetModel(TObject* obj, const Option_t* /*opt*/) { // Set model object. if (SetModelCheckClass(obj, TEveArrow::Class())) { fM = dynamic_cast<TEveArrow*>(obj); return kTRUE; } return kFALSE; } //______________________________________________________________________________ void TEveArrowGL::SetBBox() { // Set bounding box. // !! This ok if master sub-classed from TAttBBox SetAxisAlignedBBox(((TEveArrow*)fExternalObj)->AssertBBox()); } /******************************************************************************/ //______________________________________________________________________________ void TEveArrowGL::DirectDraw(TGLRnrCtx & rnrCtx) const { // Render with OpenGL. // printf("TEveArrowGL::DirectDraw LOD \n"); static TGLQuadric quad; UInt_t drawQuality = 10; // Draw 3D line (tube) with optional head shape // glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT); glDisable(GL_CULL_FACE); glPushMatrix(); TGLVertex3 uo(fM->fOrigin.fX, fM->fOrigin.fY, fM->fOrigin.fZ); TGLVector3 uv(fM->fVector.fX, fM->fVector.fY, fM->fVector.fZ); TGLMatrix local(uo, uv); glMultMatrixd(local.CArr()); Float_t size = fM->fVector.Mag(); // Line (tube) component Float_t tr = size*fM->fTubeR; Float_t hh = size*fM->fConeL; gluCylinder(quad.Get(), tr, tr, size - hh, drawQuality, 1); // disks gluQuadricOrientation(quad.Get(), (GLenum)GLU_INSIDE); gluDisk(quad.Get(), 0.0, tr, drawQuality, 1); glTranslated(0.0, 0.0, size -hh ); gluDisk(quad.Get(), 0.0, tr, drawQuality, 1); // Arrow cone gluQuadricOrientation(quad.Get(), (GLenum)GLU_OUTSIDE); gluCylinder(quad.Get(), size*fM->fConeR, 0., hh , drawQuality, 1); gluDisk(quad.Get(), 0.0, size*fM->fConeR, drawQuality, 1); glPopMatrix(); // glPopAttrib(); } <commit_msg>From Alja. Fix compilation warnings.<commit_after>// @(#)root/eve:$Id$ // Author: Matevz Tadel 2007 /************************************************************************* * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TEveArrowGL.h" #include "TEveArrow.h" #include "TGLRnrCtx.h" #include "TGLIncludes.h" #include "TGLUtil.h" #include "TGLQuadric.h" //______________________________________________________________________________ // OpenGL renderer class for TEveArrow. // ClassImp(TEveArrowGL); //______________________________________________________________________________ TEveArrowGL::TEveArrowGL() : TGLObject(), fM(0) { // Constructor. } /******************************************************************************/ //______________________________________________________________________________ Bool_t TEveArrowGL::SetModel(TObject* obj, const Option_t* /*opt*/) { // Set model object. if (SetModelCheckClass(obj, TEveArrow::Class())) { fM = dynamic_cast<TEveArrow*>(obj); return kTRUE; } return kFALSE; } //______________________________________________________________________________ void TEveArrowGL::SetBBox() { // Set bounding box. // !! This ok if master sub-classed from TAttBBox SetAxisAlignedBBox(((TEveArrow*)fExternalObj)->AssertBBox()); } /******************************************************************************/ //______________________________________________________________________________ void TEveArrowGL::DirectDraw(TGLRnrCtx& /*rnrCtx*/) const { // Render with OpenGL. // printf("TEveArrowGL::DirectDraw LOD \n"); static TGLQuadric quad; UInt_t drawQuality = 10; // Draw 3D line (tube) with optional head shape glPushMatrix(); TGLVertex3 uo(fM->fOrigin.fX, fM->fOrigin.fY, fM->fOrigin.fZ); TGLVector3 uv(fM->fVector.fX, fM->fVector.fY, fM->fVector.fZ); TGLMatrix local(uo, uv); glMultMatrixd(local.CArr()); Float_t size = fM->fVector.Mag(); // Line (tube) component Float_t tr = size*fM->fTubeR; Float_t hh = size*fM->fConeL; gluCylinder(quad.Get(), tr, tr, size - hh, drawQuality, 1); // disks gluQuadricOrientation(quad.Get(), (GLenum)GLU_INSIDE); gluDisk(quad.Get(), 0.0, tr, drawQuality, 1); glTranslated(0.0, 0.0, size -hh ); gluDisk(quad.Get(), 0.0, tr, drawQuality, 1); // Arrow cone gluQuadricOrientation(quad.Get(), (GLenum)GLU_OUTSIDE); gluCylinder(quad.Get(), size*fM->fConeR, 0., hh , drawQuality, 1); gluDisk(quad.Get(), 0.0, size*fM->fConeR, drawQuality, 1); glPopMatrix(); } <|endoftext|>
<commit_before>#include "input.h" #include "engine.h" P<WindowManager> InputHandler::windowManager; bool InputHandler::touch_screen = false; sf::Transform InputHandler::mouse_transform; PVector<InputEventHandler> InputHandler::input_event_handlers; PVector<JoystickEventHandler> InputHandler::joystick_event_handlers; bool InputHandler::keyboard_button_down[sf::Keyboard::KeyCount]; bool InputHandler::keyboard_button_pressed[sf::Keyboard::KeyCount]; bool InputHandler::keyboard_button_released[sf::Keyboard::KeyCount]; sf::Event::KeyEvent InputHandler::last_key_press; sf::Vector2f InputHandler::mouse_position; float InputHandler::mouse_wheel_delta; bool InputHandler::mouse_button_down[sf::Mouse::ButtonCount]; bool InputHandler::mouse_button_pressed[sf::Mouse::ButtonCount]; bool InputHandler::mouse_button_released[sf::Mouse::ButtonCount]; float InputHandler::joystick_axis_pos[sf::Joystick::Count][sf::Joystick::AxisCount]; float InputHandler::joystick_axis_changed[sf::Joystick::Count][sf::Joystick::AxisCount]; bool InputHandler::joystick_button_down[sf::Joystick::Count][sf::Joystick::ButtonCount]; bool InputHandler::joystick_button_changed[sf::Joystick::Count][sf::Joystick::ButtonCount]; InputEventHandler::InputEventHandler() { InputHandler::input_event_handlers.push_back(this); } InputEventHandler::~InputEventHandler() { } JoystickEventHandler::JoystickEventHandler() { InputHandler::joystick_event_handlers.push_back(this); } JoystickEventHandler::~JoystickEventHandler() { } void InputHandler::initialize() { memset(mouse_button_down, 0, sizeof(mouse_button_down)); memset(keyboard_button_down, 0, sizeof(keyboard_button_down)); memset(joystick_axis_pos, 0, sizeof(joystick_axis_pos)); #ifdef __ANDROID__ touch_screen = true; #endif last_key_press.code = sf::Keyboard::Unknown; } void InputHandler::preEventsUpdate() { if (!windowManager) windowManager = engine->getObject("windowManager"); for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++) { if (keyboard_button_pressed[n]) keyboard_button_pressed[n] = false; else keyboard_button_released[n] = false; } for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++) { if (mouse_button_pressed[n]) mouse_button_pressed[n] = false; else mouse_button_released[n] = false; } for(unsigned int i=0; i<sf::Joystick::Count; i++) { for(unsigned int n=0; n<sf::Joystick::AxisCount; n++) { joystick_axis_changed[i][n] = false; } for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++) { joystick_button_changed[i][n] = false; } } mouse_wheel_delta = 0; } void InputHandler::handleEvent(sf::Event& event) { if (event.type == sf::Event::KeyPressed) { if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount) { keyboard_button_down[event.key.code] = true; keyboard_button_pressed[event.key.code] = true; } last_key_press = event.key; } else if (event.type == sf::Event::KeyReleased) { if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount) { keyboard_button_down[event.key.code] = false; keyboard_button_released[event.key.code] = true; } } else if (event.type == sf::Event::TextEntered && event.text.unicode > 31 && event.text.unicode < 128) { if (last_key_press.code != sf::Keyboard::Unknown) { fireKeyEvent(last_key_press, event.text.unicode); last_key_press.code = sf::Keyboard::Unknown; } } else if (event.type == sf::Event::MouseWheelMoved) mouse_wheel_delta += event.mouseWheel.delta; if (event.type == sf::Event::MouseButtonPressed) { mouse_button_down[event.mouseButton.button] = true; mouse_button_pressed[event.mouseButton.button] = true; } else if (event.type == sf::Event::MouseButtonReleased) { mouse_button_down[event.mouseButton.button] = false; mouse_button_released[event.mouseButton.button] = true; } else if (event.type == sf::Event::JoystickMoved) { float axis_pos; if (event.joystickMove.position > joystick_axis_snap_to_0_range) { axis_pos = (event.joystickMove.position - joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1); } else if (event.joystickMove.position < -joystick_axis_snap_to_0_range) { axis_pos = (event.joystickMove.position + joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1); } else { axis_pos = 0.0; } if (joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] != axis_pos){ joystick_axis_changed[event.joystickMove.joystickId][event.joystickMove.axis] = true; } joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] = axis_pos; } else if (event.type == sf::Event::JoystickButtonPressed) { joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = true; joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true; } else if (event.type == sf::Event::JoystickButtonReleased) { joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = false; joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true; } } void InputHandler::postEventsUpdate() { if (last_key_press.code != sf::Keyboard::Unknown) { InputHandler::fireKeyEvent(last_key_press, -1); last_key_press.code = sf::Keyboard::Unknown; } #ifdef __ANDROID__ if (sf::Touch::isDown(0)) { mouse_position = realWindowPosToVirtual(sf::Touch::getPosition(0)); if (!mouse_button_down[sf::Mouse::Left]) mouse_button_pressed[sf::Mouse::Left] = true; mouse_button_down[sf::Mouse::Left] = true; }else{ if (mouse_button_down[sf::Mouse::Left]) mouse_button_released[sf::Mouse::Left] = true; mouse_button_down[sf::Mouse::Left] = false; } #else mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window)); #endif mouse_position = mouse_transform.transformPoint(mouse_position); if (touch_screen) { bool any_button_down = false; for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++) if (mouse_button_down[n] || mouse_button_released[n]) any_button_down = true; if (!any_button_down) { mouse_position = sf::Vector2f(-1, -1); } } for(unsigned int i=0; i<sf::Joystick::Count; i++) { for(unsigned int n=0; n<sf::Joystick::AxisCount; n++) { if(joystick_axis_changed[i][n]) { foreach(JoystickEventHandler, e, joystick_event_handlers) { e->handleJoystickAxis(i, (sf::Joystick::Axis) n, joystick_axis_pos[i][n]); } } } for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++) { if(joystick_button_changed[i][n]) { foreach(JoystickEventHandler, e, joystick_event_handlers) { e->handleJoystickButton(i, n, joystick_button_down[n]); } } } } } void InputHandler::setMousePos(sf::Vector2f position) { if (!windowManager) windowManager = engine->getObject("windowManager"); sf::Mouse::setPosition(virtualWindowPosToReal(position), windowManager->window); mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window)); } void InputHandler::fireKeyEvent(sf::Event::KeyEvent key, int unicode) { foreach(InputEventHandler, e, input_event_handlers) { e->handleKeyPress(key, unicode); } } sf::Vector2f InputHandler::realWindowPosToVirtual(sf::Vector2i position) { sf::FloatRect viewport = windowManager->window.getView().getViewport(); sf::Vector2f pos = sf::Vector2f(position); pos.x -= viewport.left * float(windowManager->window.getSize().x); pos.y -= viewport.top * float(windowManager->window.getSize().y); pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width; pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height; return pos; } sf::Vector2i InputHandler::virtualWindowPosToReal(sf::Vector2f position) { sf::FloatRect viewport = windowManager->window.getView().getViewport(); position.x /= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width; position.y /= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height; position.x += viewport.left * float(windowManager->window.getSize().x); position.y += viewport.top * float(windowManager->window.getSize().y); return sf::Vector2i(position); } <commit_msg>fix joystick button event bug - send correct state<commit_after>#include "input.h" #include "engine.h" P<WindowManager> InputHandler::windowManager; bool InputHandler::touch_screen = false; sf::Transform InputHandler::mouse_transform; PVector<InputEventHandler> InputHandler::input_event_handlers; PVector<JoystickEventHandler> InputHandler::joystick_event_handlers; bool InputHandler::keyboard_button_down[sf::Keyboard::KeyCount]; bool InputHandler::keyboard_button_pressed[sf::Keyboard::KeyCount]; bool InputHandler::keyboard_button_released[sf::Keyboard::KeyCount]; sf::Event::KeyEvent InputHandler::last_key_press; sf::Vector2f InputHandler::mouse_position; float InputHandler::mouse_wheel_delta; bool InputHandler::mouse_button_down[sf::Mouse::ButtonCount]; bool InputHandler::mouse_button_pressed[sf::Mouse::ButtonCount]; bool InputHandler::mouse_button_released[sf::Mouse::ButtonCount]; float InputHandler::joystick_axis_pos[sf::Joystick::Count][sf::Joystick::AxisCount]; float InputHandler::joystick_axis_changed[sf::Joystick::Count][sf::Joystick::AxisCount]; bool InputHandler::joystick_button_down[sf::Joystick::Count][sf::Joystick::ButtonCount]; bool InputHandler::joystick_button_changed[sf::Joystick::Count][sf::Joystick::ButtonCount]; InputEventHandler::InputEventHandler() { InputHandler::input_event_handlers.push_back(this); } InputEventHandler::~InputEventHandler() { } JoystickEventHandler::JoystickEventHandler() { InputHandler::joystick_event_handlers.push_back(this); } JoystickEventHandler::~JoystickEventHandler() { } void InputHandler::initialize() { memset(mouse_button_down, 0, sizeof(mouse_button_down)); memset(keyboard_button_down, 0, sizeof(keyboard_button_down)); memset(joystick_axis_pos, 0, sizeof(joystick_axis_pos)); #ifdef __ANDROID__ touch_screen = true; #endif last_key_press.code = sf::Keyboard::Unknown; } void InputHandler::preEventsUpdate() { if (!windowManager) windowManager = engine->getObject("windowManager"); for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++) { if (keyboard_button_pressed[n]) keyboard_button_pressed[n] = false; else keyboard_button_released[n] = false; } for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++) { if (mouse_button_pressed[n]) mouse_button_pressed[n] = false; else mouse_button_released[n] = false; } for(unsigned int i=0; i<sf::Joystick::Count; i++) { for(unsigned int n=0; n<sf::Joystick::AxisCount; n++) { joystick_axis_changed[i][n] = false; } for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++) { joystick_button_changed[i][n] = false; } } mouse_wheel_delta = 0; } void InputHandler::handleEvent(sf::Event& event) { if (event.type == sf::Event::KeyPressed) { if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount) { keyboard_button_down[event.key.code] = true; keyboard_button_pressed[event.key.code] = true; } last_key_press = event.key; } else if (event.type == sf::Event::KeyReleased) { if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount) { keyboard_button_down[event.key.code] = false; keyboard_button_released[event.key.code] = true; } } else if (event.type == sf::Event::TextEntered && event.text.unicode > 31 && event.text.unicode < 128) { if (last_key_press.code != sf::Keyboard::Unknown) { fireKeyEvent(last_key_press, event.text.unicode); last_key_press.code = sf::Keyboard::Unknown; } } else if (event.type == sf::Event::MouseWheelMoved) mouse_wheel_delta += event.mouseWheel.delta; if (event.type == sf::Event::MouseButtonPressed) { mouse_button_down[event.mouseButton.button] = true; mouse_button_pressed[event.mouseButton.button] = true; } else if (event.type == sf::Event::MouseButtonReleased) { mouse_button_down[event.mouseButton.button] = false; mouse_button_released[event.mouseButton.button] = true; } else if (event.type == sf::Event::JoystickMoved) { float axis_pos; if (event.joystickMove.position > joystick_axis_snap_to_0_range) { axis_pos = (event.joystickMove.position - joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1); } else if (event.joystickMove.position < -joystick_axis_snap_to_0_range) { axis_pos = (event.joystickMove.position + joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1); } else { axis_pos = 0.0; } if (joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] != axis_pos){ joystick_axis_changed[event.joystickMove.joystickId][event.joystickMove.axis] = true; } joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] = axis_pos; } else if (event.type == sf::Event::JoystickButtonPressed) { joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = true; joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true; } else if (event.type == sf::Event::JoystickButtonReleased) { joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = false; joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true; } } void InputHandler::postEventsUpdate() { if (last_key_press.code != sf::Keyboard::Unknown) { InputHandler::fireKeyEvent(last_key_press, -1); last_key_press.code = sf::Keyboard::Unknown; } #ifdef __ANDROID__ if (sf::Touch::isDown(0)) { mouse_position = realWindowPosToVirtual(sf::Touch::getPosition(0)); if (!mouse_button_down[sf::Mouse::Left]) mouse_button_pressed[sf::Mouse::Left] = true; mouse_button_down[sf::Mouse::Left] = true; }else{ if (mouse_button_down[sf::Mouse::Left]) mouse_button_released[sf::Mouse::Left] = true; mouse_button_down[sf::Mouse::Left] = false; } #else mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window)); #endif mouse_position = mouse_transform.transformPoint(mouse_position); if (touch_screen) { bool any_button_down = false; for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++) if (mouse_button_down[n] || mouse_button_released[n]) any_button_down = true; if (!any_button_down) { mouse_position = sf::Vector2f(-1, -1); } } for(unsigned int i=0; i<sf::Joystick::Count; i++) { for(unsigned int n=0; n<sf::Joystick::AxisCount; n++) { if(joystick_axis_changed[i][n]) { foreach(JoystickEventHandler, e, joystick_event_handlers) { e->handleJoystickAxis(i, (sf::Joystick::Axis) n, joystick_axis_pos[i][n]); } } } for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++) { if(joystick_button_changed[i][n]) { foreach(JoystickEventHandler, e, joystick_event_handlers) { e->handleJoystickButton(i, n, joystick_button_down[i][n]); } } } } } void InputHandler::setMousePos(sf::Vector2f position) { if (!windowManager) windowManager = engine->getObject("windowManager"); sf::Mouse::setPosition(virtualWindowPosToReal(position), windowManager->window); mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window)); } void InputHandler::fireKeyEvent(sf::Event::KeyEvent key, int unicode) { foreach(InputEventHandler, e, input_event_handlers) { e->handleKeyPress(key, unicode); } } sf::Vector2f InputHandler::realWindowPosToVirtual(sf::Vector2i position) { sf::FloatRect viewport = windowManager->window.getView().getViewport(); sf::Vector2f pos = sf::Vector2f(position); pos.x -= viewport.left * float(windowManager->window.getSize().x); pos.y -= viewport.top * float(windowManager->window.getSize().y); pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width; pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height; return pos; } sf::Vector2i InputHandler::virtualWindowPosToReal(sf::Vector2f position) { sf::FloatRect viewport = windowManager->window.getView().getViewport(); position.x /= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width; position.y /= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height; position.x += viewport.left * float(windowManager->window.getSize().x); position.y += viewport.top * float(windowManager->window.getSize().y); return sf::Vector2i(position); } <|endoftext|>
<commit_before>#include <cstdio> #include <vector> #include <stack> #include <algorithm> using namespace std; enum class Frog { None, Brown, Green }; enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight }; struct FrogsState { size_t Count; vector<Frog> Lilies; int BlankPos; Step Movement; FrogsState(): Count(0), BlankPos(-1), Movement(Step::None) {} FrogsState(size_t count): Count(count), Lilies(2 * Count + 1), BlankPos(Count), Movement(Step::None) { for (auto i = 0; i < Count; i++) { Lilies[i] = Frog::Brown; Lilies[2 * Count - i] = Frog::Green; } Lilies[BlankPos] = Frog::None; } bool operator==(const FrogsState& other) const { return Count == other.Count && Lilies == other.Lilies && BlankPos == other.BlankPos; } bool IsStuckJumpLeft() const { return BlankPos >= Lilies.size() - 1 || Lilies[BlankPos + 1] != Frog::Green; } bool IsStuckLeapLeft() const { return BlankPos >= Lilies.size() - 2 || Lilies[BlankPos + 2] != Frog::Green; } bool IsStuckJumpRight() const { return BlankPos < 1 || Lilies[BlankPos - 1] != Frog::Brown; } bool IsStuckLeapRight() const { return BlankPos < 2 || Lilies[BlankPos - 2] != Frog::Brown; } bool WasTargetReached() const { for (auto i = 0; i < Count; i++) if (Lilies[i] != Frog::Green || Lilies[2 * Count - i] != Frog::Brown) return false; return Lilies[Count] == Frog::None; }; void Print() const { for (auto frog: Lilies) switch (frog) { case Frog::Brown: printf(">"); break; case Frog::Green: printf("<"); break; case Frog::None: printf(" "); break; } printf("\n"); } pair<bool, FrogsState> Move(Step movement) const { auto canMove = false; auto moved = *this; moved.Movement = movement; switch (movement) { case Step::JumpLeft: if (!IsStuckJumpLeft()) { moved.Lilies[moved.BlankPos] = Frog::Green; moved.BlankPos++; canMove = true; } break; case Step::LeapLeft: if (!IsStuckLeapLeft()) { moved.Lilies[moved.BlankPos] = Frog::Green; moved.BlankPos += 2; canMove = true; } break; case Step::JumpRight: if (!IsStuckJumpRight()) { moved.Lilies[moved.BlankPos] = Frog::Brown; moved.BlankPos--; canMove = true; } break; case Step::LeapRight: if (!IsStuckLeapRight()) { moved.Lilies[moved.BlankPos] = Frog::Brown; moved.BlankPos -= 2; canMove = true; } break; default: break; } if (canMove) moved.Lilies[moved.BlankPos] = Frog::None; return make_pair(canMove, moved); } bool UndoStep(Step prevMovement) { auto canUndoStep = false; switch (Movement) { case Step::JumpLeft: Lilies[BlankPos] = Frog::Green; BlankPos--; canUndoStep = true; break; case Step::LeapLeft: Lilies[BlankPos] = Frog::Green; BlankPos -= 2; canUndoStep = true; break; case Step::JumpRight: Lilies[BlankPos] = Frog::Brown; BlankPos++; canUndoStep = true; break; case Step::LeapRight: Lilies[BlankPos] = Frog::Brown; BlankPos += 2; canUndoStep = true; break; default: break; } if (canUndoStep) { Lilies[BlankPos] = Frog::None; Movement = prevMovement; } return canUndoStep; }; }; int main() { unsigned int count; scanf_s("%u", &count); vector<FrogsState> visited; stack<FrogsState> trace; stack<Step> movements; trace.push(FrogsState(count)); while (!trace.empty() && !trace.top().WasTargetReached()) { auto state = trace.top(); trace.pop(); auto move = [&](Step movement) { auto newStateOptional = state.Move(movement); if (newStateOptional.first) trace.push(newStateOptional.second); }; while (!movements.empty() && state.IsStuckJumpLeft() && state.IsStuckLeapLeft() && state.IsStuckJumpRight() && state.IsStuckLeapRight()) { state.UndoStep(movements.top()); movements.pop(); } if (visited.crend() == find(visited.crbegin(), visited.crend(), state)) { visited.push_back(state); movements.push(state.Movement); move(Step::JumpLeft); move(Step::LeapLeft); move(Step::JumpRight); move(Step::LeapRight); state.Print(); } } if (!trace.empty()) trace.top().Print(); return 0; } <commit_msg>fix: forgot the Movement member in the equality operator for FrogsState<commit_after>#include <cstdio> #include <vector> #include <stack> #include <algorithm> using namespace std; enum class Frog { None, Brown, Green }; enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight }; struct FrogsState { size_t Count; vector<Frog> Lilies; int BlankPos; Step Movement; FrogsState(): Count(0), BlankPos(-1), Movement(Step::None) {} FrogsState(size_t count): Count(count), Lilies(2 * Count + 1), BlankPos(Count), Movement(Step::None) { for (auto i = 0; i < Count; i++) { Lilies[i] = Frog::Brown; Lilies[2 * Count - i] = Frog::Green; } Lilies[BlankPos] = Frog::None; } bool operator==(const FrogsState& other) const { return Count == other.Count && Lilies == other.Lilies && BlankPos == other.BlankPos && Movement == other.Movement; } bool IsStuckJumpLeft() const { return BlankPos >= Lilies.size() - 1 || Lilies[BlankPos + 1] != Frog::Green; } bool IsStuckLeapLeft() const { return BlankPos >= Lilies.size() - 2 || Lilies[BlankPos + 2] != Frog::Green; } bool IsStuckJumpRight() const { return BlankPos < 1 || Lilies[BlankPos - 1] != Frog::Brown; } bool IsStuckLeapRight() const { return BlankPos < 2 || Lilies[BlankPos - 2] != Frog::Brown; } bool WasTargetReached() const { for (auto i = 0; i < Count; i++) if (Lilies[i] != Frog::Green || Lilies[2 * Count - i] != Frog::Brown) return false; return Lilies[Count] == Frog::None; }; void Print() const { for (auto frog: Lilies) switch (frog) { case Frog::Brown: printf(">"); break; case Frog::Green: printf("<"); break; case Frog::None: printf(" "); break; } printf("\n"); } pair<bool, FrogsState> Move(Step movement) const { auto canMove = false; auto moved = *this; moved.Movement = movement; switch (movement) { case Step::JumpLeft: if (!IsStuckJumpLeft()) { moved.Lilies[moved.BlankPos] = Frog::Green; moved.BlankPos++; canMove = true; } break; case Step::LeapLeft: if (!IsStuckLeapLeft()) { moved.Lilies[moved.BlankPos] = Frog::Green; moved.BlankPos += 2; canMove = true; } break; case Step::JumpRight: if (!IsStuckJumpRight()) { moved.Lilies[moved.BlankPos] = Frog::Brown; moved.BlankPos--; canMove = true; } break; case Step::LeapRight: if (!IsStuckLeapRight()) { moved.Lilies[moved.BlankPos] = Frog::Brown; moved.BlankPos -= 2; canMove = true; } break; default: break; } if (canMove) moved.Lilies[moved.BlankPos] = Frog::None; return make_pair(canMove, moved); } bool UndoStep(Step prevMovement) { auto canUndoStep = false; switch (Movement) { case Step::JumpLeft: Lilies[BlankPos] = Frog::Green; BlankPos--; canUndoStep = true; break; case Step::LeapLeft: Lilies[BlankPos] = Frog::Green; BlankPos -= 2; canUndoStep = true; break; case Step::JumpRight: Lilies[BlankPos] = Frog::Brown; BlankPos++; canUndoStep = true; break; case Step::LeapRight: Lilies[BlankPos] = Frog::Brown; BlankPos += 2; canUndoStep = true; break; default: break; } if (canUndoStep) { Lilies[BlankPos] = Frog::None; Movement = prevMovement; } return canUndoStep; }; }; int main() { unsigned int count; scanf_s("%u", &count); vector<FrogsState> visited; stack<FrogsState> trace; stack<Step> movements; trace.push(FrogsState(count)); while (!trace.empty() && !trace.top().WasTargetReached()) { auto state = trace.top(); trace.pop(); auto move = [&](Step movement) { auto newStateOptional = state.Move(movement); if (newStateOptional.first) trace.push(newStateOptional.second); }; while (!movements.empty() && state.IsStuckJumpLeft() && state.IsStuckLeapLeft() && state.IsStuckJumpRight() && state.IsStuckLeapRight()) { state.UndoStep(movements.top()); movements.pop(); } if (visited.crend() == find(visited.crbegin(), visited.crend(), state)) { visited.push_back(state); movements.push(state.Movement); move(Step::JumpLeft); move(Step::LeapLeft); move(Step::JumpRight); move(Step::LeapRight); state.Print(); } } if (!trace.empty()) trace.top().Print(); return 0; } <|endoftext|>
<commit_before>/* * PluginFramework.cpp * * Created on: 21.06.2017 * Author: alwi0251 */ #include "pluginFramework/impl/PluginFrameworkImpl.hpp" #ifdef NDEBUG #define DEBUG_MESSAGE(a) /**/ #else #define DEBUG_MESSAGE(a) a #endif #define MAX_CHAR 260 typedef std::shared_ptr<MDE4CPPPlugin> (__stdcall *StartFunction)(); #include <iostream> #include <dirent.h> #ifdef __linux__ #elif defined(_WIN32) #include <windows.h> #endif #include "pluginFramework/MDE4CPPPlugin.hpp" PluginFrameworkImpl::PluginFrameworkImpl() { initialize(); } PluginFrameworkImpl::~PluginFrameworkImpl() { m_mapPluginName.clear(); m_mapPluginUri.clear(); } PluginFramework* PluginFrameworkImpl::create() { return new PluginFrameworkImpl(); } std::vector<std::string> PluginFrameworkImpl::findAllAvailableLibraries() { char folderBuffer[MAX_CHAR]; char nameBuffer[MAX_CHAR]; m_debugMode = false; #ifdef __linux__ m_endingDebug = "d.so"; m_endingRelease = ".so"; m_endingString = "d"; std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!" return libraries; #elif defined(_WIN32) GetCurrentDirectory(MAX_CHAR, folderBuffer); GetModuleFileName(NULL, nameBuffer, MAX_CHAR); m_endingDebug = "d.dll"; m_endingRelease = ".dll"; m_endingString = "d.exe"; #else std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!" return libraries; #endif std::string fileName(nameBuffer); std::string folderName(folderBuffer); std::vector<std::string> libraries; if (fileName.length() >= m_endingString.length()) { m_debugMode = (0 == fileName.compare(fileName.length() - m_endingString.length(), m_endingString.length(), m_endingString)); } DIR *dir; struct dirent *file; #ifdef __linux__ std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!" #elif defined(_WIN32) if((dir = opendir(folderBuffer)) != NULL) { while((file = readdir(dir)) != NULL) { std::string libName = checkLibrary(file, folderName); if (!libName.empty()) { libraries.push_back(libName); } } closedir (dir); } else { std::cerr << "Could not open directory " << folderName << " failed" << std::endl; } #else std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!" #endif return libraries; } std::string PluginFrameworkImpl::checkLibrary(struct dirent* file, std::string folderName) { std::string name(file->d_name); if(m_debugMode) { if(name.length() >= m_endingDebug.length()) { if((0 == name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug))) { return folderName + "\\" + name; } } } else { if(name.length() >= m_endingRelease.length()) { if((0 == name.compare(name.length() - m_endingRelease.length(), m_endingRelease.length(), m_endingRelease))) { if(name.length() >= m_endingDebug.length()) { if((0 != name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug))) { return folderName + "\\" + name; } } } } } return ""; } void PluginFrameworkImpl::initialize() { std::vector<std::string> libraries = findAllAvailableLibraries(); for (std::string libraryPath : libraries) { loadLibrary(libraryPath); } } void PluginFrameworkImpl::loadLibrary(std::string libraryPath) { HINSTANCE hGetProcIDDLL = LoadLibrary(libraryPath.c_str()); if(!hGetProcIDDLL) { std::cerr << "could not load the dynamic library, ErrorCode: " << GetLastError() << std::endl; return; } StartFunction startFunction = (StartFunction) GetProcAddress(hGetProcIDDLL, "_Z5startv"); if(!startFunction) { DEBUG_MESSAGE(std::cout << "Could not locate the start function 'std::shared_ptr<MDE4CPPPlugin> start()' in library " << libraryPath << std::endl;) } else { std::shared_ptr<MDE4CPPPlugin> plugin = startFunction(); m_mapPluginName.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNAME(), plugin)); m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNS_URI(), plugin)); std::string eclipseURI = plugin->eclipseURI(); if (!eclipseURI.empty()) { m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(eclipseURI, plugin)); } DEBUG_MESSAGE(std::cout << "library " << plugin << " started" << std::endl;) } } void PluginFrameworkImpl::clear() { m_mapPluginName.clear(); m_mapPluginUri.clear(); } std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByName(const std::string name) const { std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginName.find(name); std::shared_ptr<MDE4CPPPlugin> pluginObject; if(iter != m_mapPluginName.end()) { return iter->second; } return nullptr; } std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByUri(const std::string uri) const { std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginUri.find(uri); std::shared_ptr<MDE4CPPPlugin> pluginObject; if(iter != m_mapPluginUri.end()) { return iter->second; } return nullptr; } <commit_msg>[PluginFramework] add missing ";", define variable libraries on top of function findAllAvailableLibraries<commit_after>/* * PluginFramework.cpp * * Created on: 21.06.2017 * Author: alwi0251 */ #include "pluginFramework/impl/PluginFrameworkImpl.hpp" #ifdef NDEBUG #define DEBUG_MESSAGE(a) /**/ #else #define DEBUG_MESSAGE(a) a #endif #define MAX_CHAR 260 typedef std::shared_ptr<MDE4CPPPlugin> (__stdcall *StartFunction)(); #include <iostream> #include <dirent.h> #ifdef __linux__ #elif defined(_WIN32) #include <windows.h> #endif #include "pluginFramework/MDE4CPPPlugin.hpp" PluginFrameworkImpl::PluginFrameworkImpl() { initialize(); } PluginFrameworkImpl::~PluginFrameworkImpl() { m_mapPluginName.clear(); m_mapPluginUri.clear(); } PluginFramework* PluginFrameworkImpl::create() { return new PluginFrameworkImpl(); } std::vector<std::string> PluginFrameworkImpl::findAllAvailableLibraries() { char folderBuffer[MAX_CHAR]; char nameBuffer[MAX_CHAR]; std::vector<std::string> libraries; m_debugMode = false; #ifdef __linux__ m_endingDebug = "d.so"; m_endingRelease = ".so"; m_endingString = "d"; std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!"; return libraries; #elif defined(_WIN32) GetCurrentDirectory(MAX_CHAR, folderBuffer); GetModuleFileName(NULL, nameBuffer, MAX_CHAR); m_endingDebug = "d.dll"; m_endingRelease = ".dll"; m_endingString = "d.exe"; #else std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!"; return libraries; #endif std::string fileName(nameBuffer); std::string folderName(folderBuffer); if (fileName.length() >= m_endingString.length()) { m_debugMode = (0 == fileName.compare(fileName.length() - m_endingString.length(), m_endingString.length(), m_endingString)); } DIR *dir; struct dirent *file; #ifdef __linux__ std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!"; #elif defined(_WIN32) if((dir = opendir(folderBuffer)) != NULL) { while((file = readdir(dir)) != NULL) { std::string libName = checkLibrary(file, folderName); if (!libName.empty()) { libraries.push_back(libName); } } closedir (dir); } else { std::cerr << "Could not open directory " << folderName << " failed" << std::endl; } #else std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!"; #endif return libraries; } std::string PluginFrameworkImpl::checkLibrary(struct dirent* file, std::string folderName) { std::string name(file->d_name); if(m_debugMode) { if(name.length() >= m_endingDebug.length()) { if((0 == name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug))) { return folderName + "\\" + name; } } } else { if(name.length() >= m_endingRelease.length()) { if((0 == name.compare(name.length() - m_endingRelease.length(), m_endingRelease.length(), m_endingRelease))) { if(name.length() >= m_endingDebug.length()) { if((0 != name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug))) { return folderName + "\\" + name; } } } } } return ""; } void PluginFrameworkImpl::initialize() { std::vector<std::string> libraries = findAllAvailableLibraries(); for (std::string libraryPath : libraries) { loadLibrary(libraryPath); } } void PluginFrameworkImpl::loadLibrary(std::string libraryPath) { HINSTANCE hGetProcIDDLL = LoadLibrary(libraryPath.c_str()); if(!hGetProcIDDLL) { std::cerr << "could not load the dynamic library, ErrorCode: " << GetLastError() << std::endl; return; } StartFunction startFunction = (StartFunction) GetProcAddress(hGetProcIDDLL, "_Z5startv"); if(!startFunction) { DEBUG_MESSAGE(std::cout << "Could not locate the start function 'std::shared_ptr<MDE4CPPPlugin> start()' in library " << libraryPath << std::endl;) } else { std::shared_ptr<MDE4CPPPlugin> plugin = startFunction(); m_mapPluginName.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNAME(), plugin)); m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNS_URI(), plugin)); std::string eclipseURI = plugin->eclipseURI(); if (!eclipseURI.empty()) { m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(eclipseURI, plugin)); } DEBUG_MESSAGE(std::cout << "library " << plugin << " started" << std::endl;) } } void PluginFrameworkImpl::clear() { m_mapPluginName.clear(); m_mapPluginUri.clear(); } std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByName(const std::string name) const { std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginName.find(name); std::shared_ptr<MDE4CPPPlugin> pluginObject; if(iter != m_mapPluginName.end()) { return iter->second; } return nullptr; } std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByUri(const std::string uri) const { std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginUri.find(uri); std::shared_ptr<MDE4CPPPlugin> pluginObject; if(iter != m_mapPluginUri.end()) { return iter->second; } return nullptr; } <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * 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 "kitBase/devicesConfigurationWidget.h" #include <QtWidgets/QBoxLayout> #include <QtWidgets/QComboBox> #include <QtWidgets/QLabel> #include "kitBase/robotModel/robotModelInterface.h" using namespace kitBase; using namespace robotModel; DevicesConfigurationWidget::DevicesConfigurationWidget(QWidget *parent, bool autosaveMode, bool compactMode) : QScrollArea(parent) , mAutosaveMode(autosaveMode) , mCompactMode(compactMode) , mSaving(false) , mRefreshing(false) { setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMinimumHeight(125); setFrameShape(QFrame::NoFrame); setWidgetResizable(true); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::transparent); setPalette(palette); } void DevicesConfigurationWidget::loadRobotModels(QList<RobotModelInterface *> const &models) { for (RobotModelInterface * const model : models) { const QString name = model->name(); mRobotModels[name] = model; QWidget * const configurer = configurerForRobotModel(*model); mRobotModelConfigurers[name] = configurer; } } void DevicesConfigurationWidget::selectRobotModel(RobotModelInterface &robotModel) { mCurrentModelType = robotModel.name(); mCurrentModelId = robotModel.robotId(); takeWidget(); if (mRobotModels.contains(mCurrentModelType)) { setWidget(mRobotModelConfigurers[mCurrentModelType]); refresh(); } } void DevicesConfigurationWidget::prependCustomWidget(RobotModelInterface &robotModel, QWidget * const widget) { if (!widget) { return; } Q_ASSERT(mRobotModelConfigurers.contains(robotModel.name())); QVBoxLayout *layout = dynamic_cast<QVBoxLayout *>(mRobotModelConfigurers[robotModel.name()]->layout()); Q_ASSERT(layout); layout->insertWidget(0, widget); } QWidget *DevicesConfigurationWidget::configurerForRobotModel(RobotModelInterface &robotModel) { /// @todo: What if robot model has no configurable sensors? QWidget *result = new QWidget; QPalette palette = result->palette(); palette.setColor(QPalette::Background, Qt::transparent); result->setPalette(palette); QVBoxLayout * const layout = new QVBoxLayout(result); layout->setContentsMargins(0, 0, 0, 0); QList<PortInfo> const configurablePorts = robotModel.configurablePorts(); for (const PortInfo &port : configurablePorts) { layout->addLayout(initPort(robotModel.name(), port, robotModel.allowedDevices(port))); } return result; } QLayout *DevicesConfigurationWidget::initPort(const QString &robotModel , const PortInfo &port, QList<DeviceInfo> const &sensors) { const QString labelText = mCompactMode ? tr("%1:") : tr("Port %1:"); QLabel * const portLabel = new QLabel(labelText.arg(port.userFriendlyName()), this); QComboBox * const comboBox = new QComboBox(this); comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon); comboBox->setProperty("robotModel", robotModel); comboBox->setProperty("port", QVariant::fromValue(port)); mConfigurers << comboBox; comboBox->addItem(tr("Unused"), QVariant::fromValue(DeviceInfo())); for (const DeviceInfo &sensor : sensors) { comboBox->addItem(sensor.friendlyName(), QVariant::fromValue(sensor)); } if (mAutosaveMode) { connect(comboBox, &QComboBox::currentTextChanged, this, &DevicesConfigurationWidget::save); } QHBoxLayout * const layout = new QHBoxLayout; layout->addWidget(portLabel); layout->addWidget(comboBox); layout->setStretch(0, 0); layout->setStretch(1, 1); return layout; } void DevicesConfigurationWidget::onDeviceConfigurationChanged(const QString &robotModel , const PortInfo &port, const DeviceInfo &sensor, Reason reason) { Q_UNUSED(port) Q_UNUSED(sensor) Q_UNUSED(reason) // This method can be called when we did not accomplish processing all combo boxes during saving. // So ignoring such case. if (!mSaving && robotModel == mCurrentModelId) { refresh(); } } void DevicesConfigurationWidget::refresh() { mRefreshing = true; for (QComboBox * const box : mConfigurers) { const PortInfo port = box->property("port").value<PortInfo>(); const DeviceInfo device = currentConfiguration(mCurrentModelId, port); if (device.isNull()) { box->setCurrentIndex(0); } else { for (int index = 0; index < box->count(); ++index) { if (box->itemData(index).value<DeviceInfo>().isA(device)) { box->setCurrentIndex(index); break; } } } } mRefreshing = false; } void DevicesConfigurationWidget::save() { // Refreshing may affect combobox current index. No saving is needed then. if (mRefreshing) { return; } mSaving = true; for (QComboBox * const box : mConfigurers) { if (!box->isVisible()) { continue; } const QString robotModel = box->property("robotModel").toString(); const PortInfo port = box->property("port").value<PortInfo>(); const DeviceInfo device = box->itemData(box->currentIndex()).value<DeviceInfo>(); if (robotModel == mCurrentModelType && currentConfiguration(mCurrentModelId, port) != device) { propagateChanges(port, device); } } mSaving = false; } void DevicesConfigurationWidget::propagateChanges(const PortInfo &port, const DeviceInfo &sensor) { for (const QString &robotModelType : mRobotModels.keys()) { const RobotModelInterface *robotModel = mRobotModels[robotModelType]; for (const PortInfo &otherPort : robotModel->configurablePorts()) { if (areConvertible(port, otherPort)) { if (sensor.isNull()) { deviceConfigurationChanged(robotModel->robotId(), otherPort, DeviceInfo(), Reason::userAction); } else { const DeviceInfo otherDevice = convertibleDevice(robotModel, otherPort, sensor); if (!otherDevice.isNull()) { deviceConfigurationChanged(robotModel->robotId(), otherPort, otherDevice, Reason::userAction); } } } } } } bool DevicesConfigurationWidget::areConvertible(const PortInfo &port1, const PortInfo &port2) const { return (port1.name() == port2.name() || port1.nameAliases().contains(port2.name()) || port2.nameAliases().contains(port1.name())) && port1.direction() == port2.direction(); } DeviceInfo DevicesConfigurationWidget::convertibleDevice(const RobotModelInterface *robotModel , const PortInfo &port, const DeviceInfo &device) const { QList<DeviceInfo> const convertibleBases = robotModel->convertibleBases(); for (const DeviceInfo &allowedDevice : robotModel->allowedDevices(port)) { for (const DeviceInfo &convertibleBase : convertibleBases) { if (device.isA(convertibleBase) && allowedDevice.isA(convertibleBase)) { return allowedDevice; } } } return DeviceInfo(); } <commit_msg>Fixed sensors configurers background in 2D model<commit_after>/* Copyright 2007-2015 QReal Research Group * * 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 "kitBase/devicesConfigurationWidget.h" #include <QtWidgets/QBoxLayout> #include <QtWidgets/QComboBox> #include <QtWidgets/QLabel> #include "kitBase/robotModel/robotModelInterface.h" using namespace kitBase; using namespace robotModel; DevicesConfigurationWidget::DevicesConfigurationWidget(QWidget *parent, bool autosaveMode, bool compactMode) : QScrollArea(parent) , mAutosaveMode(autosaveMode) , mCompactMode(compactMode) , mSaving(false) , mRefreshing(false) { setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMinimumHeight(125); setFrameShape(QFrame::NoFrame); setWidgetResizable(true); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::transparent); setPalette(palette); } void DevicesConfigurationWidget::loadRobotModels(QList<RobotModelInterface *> const &models) { for (RobotModelInterface * const model : models) { const QString name = model->name(); mRobotModels[name] = model; QWidget * const configurer = configurerForRobotModel(*model); mRobotModelConfigurers[name] = configurer; } } void DevicesConfigurationWidget::selectRobotModel(RobotModelInterface &robotModel) { mCurrentModelType = robotModel.name(); mCurrentModelId = robotModel.robotId(); takeWidget(); if (mRobotModels.contains(mCurrentModelType)) { setWidget(mRobotModelConfigurers[mCurrentModelType]); refresh(); } } void DevicesConfigurationWidget::prependCustomWidget(RobotModelInterface &robotModel, QWidget * const widget) { if (!widget) { return; } Q_ASSERT(mRobotModelConfigurers.contains(robotModel.name())); QVBoxLayout *layout = dynamic_cast<QVBoxLayout *>(mRobotModelConfigurers[robotModel.name()]->layout()); Q_ASSERT(layout); layout->insertWidget(0, widget); } QWidget *DevicesConfigurationWidget::configurerForRobotModel(RobotModelInterface &robotModel) { /// @todo: What if robot model has no configurable sensors? QWidget *result = new QWidget; QPalette palette = result->palette(); palette.setColor(QPalette::Background, Qt::transparent); result->setPalette(palette); QVBoxLayout * const layout = new QVBoxLayout(result); layout->setContentsMargins(0, 0, 0, 0); QList<PortInfo> const configurablePorts = robotModel.configurablePorts(); for (const PortInfo &port : configurablePorts) { layout->addLayout(initPort(robotModel.name(), port, robotModel.allowedDevices(port))); } return result; } QLayout *DevicesConfigurationWidget::initPort(const QString &robotModel , const PortInfo &port, QList<DeviceInfo> const &sensors) { const QString labelText = mCompactMode ? tr("%1:") : tr("Port %1:"); QLabel * const portLabel = new QLabel(labelText.arg(port.userFriendlyName()), this); QComboBox * const comboBox = new QComboBox(this); QPalette palette = comboBox->palette(); palette.setColor(QPalette::Base, Qt::white); comboBox->setPalette(Qt::white); comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon); comboBox->setProperty("robotModel", robotModel); comboBox->setProperty("port", QVariant::fromValue(port)); mConfigurers << comboBox; comboBox->addItem(tr("Unused"), QVariant::fromValue(DeviceInfo())); for (const DeviceInfo &sensor : sensors) { comboBox->addItem(sensor.friendlyName(), QVariant::fromValue(sensor)); } if (mAutosaveMode) { connect(comboBox, &QComboBox::currentTextChanged, this, &DevicesConfigurationWidget::save); } QHBoxLayout * const layout = new QHBoxLayout; layout->addWidget(portLabel); layout->addWidget(comboBox); layout->setStretch(0, 0); layout->setStretch(1, 1); return layout; } void DevicesConfigurationWidget::onDeviceConfigurationChanged(const QString &robotModel , const PortInfo &port, const DeviceInfo &sensor, Reason reason) { Q_UNUSED(port) Q_UNUSED(sensor) Q_UNUSED(reason) // This method can be called when we did not accomplish processing all combo boxes during saving. // So ignoring such case. if (!mSaving && robotModel == mCurrentModelId) { refresh(); } } void DevicesConfigurationWidget::refresh() { mRefreshing = true; for (QComboBox * const box : mConfigurers) { const PortInfo port = box->property("port").value<PortInfo>(); const DeviceInfo device = currentConfiguration(mCurrentModelId, port); if (device.isNull()) { box->setCurrentIndex(0); } else { for (int index = 0; index < box->count(); ++index) { if (box->itemData(index).value<DeviceInfo>().isA(device)) { box->setCurrentIndex(index); break; } } } } mRefreshing = false; } void DevicesConfigurationWidget::save() { // Refreshing may affect combobox current index. No saving is needed then. if (mRefreshing) { return; } mSaving = true; for (QComboBox * const box : mConfigurers) { if (!box->isVisible()) { continue; } const QString robotModel = box->property("robotModel").toString(); const PortInfo port = box->property("port").value<PortInfo>(); const DeviceInfo device = box->itemData(box->currentIndex()).value<DeviceInfo>(); if (robotModel == mCurrentModelType && currentConfiguration(mCurrentModelId, port) != device) { propagateChanges(port, device); } } mSaving = false; } void DevicesConfigurationWidget::propagateChanges(const PortInfo &port, const DeviceInfo &sensor) { for (const QString &robotModelType : mRobotModels.keys()) { const RobotModelInterface *robotModel = mRobotModels[robotModelType]; for (const PortInfo &otherPort : robotModel->configurablePorts()) { if (areConvertible(port, otherPort)) { if (sensor.isNull()) { deviceConfigurationChanged(robotModel->robotId(), otherPort, DeviceInfo(), Reason::userAction); } else { const DeviceInfo otherDevice = convertibleDevice(robotModel, otherPort, sensor); if (!otherDevice.isNull()) { deviceConfigurationChanged(robotModel->robotId(), otherPort, otherDevice, Reason::userAction); } } } } } } bool DevicesConfigurationWidget::areConvertible(const PortInfo &port1, const PortInfo &port2) const { return (port1.name() == port2.name() || port1.nameAliases().contains(port2.name()) || port2.nameAliases().contains(port1.name())) && port1.direction() == port2.direction(); } DeviceInfo DevicesConfigurationWidget::convertibleDevice(const RobotModelInterface *robotModel , const PortInfo &port, const DeviceInfo &device) const { QList<DeviceInfo> const convertibleBases = robotModel->convertibleBases(); for (const DeviceInfo &allowedDevice : robotModel->allowedDevices(port)) { for (const DeviceInfo &convertibleBase : convertibleBases) { if (device.isA(convertibleBase) && allowedDevice.isA(convertibleBase)) { return allowedDevice; } } } return DeviceInfo(); } <|endoftext|>
<commit_before>// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "qevent.h" #include "qdialog.h" #include "qpushbutton.h" #include "qlabel.h" #include "qpainter.h" #if (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4 # include "qmenu.h" # include "q3popupmenu.h" typedef Q3PopupMenu QPopupMenu; #else # include "qpopupmenu.h" #endif #include "TQCanvasMenu.h" #include "TClass.h" #include "TROOT.h" #include "TMethod.h" #include "TMethodCall.h" #include "TMethodArg.h" #include "TCanvas.h" #include "TDataType.h" #include "TQRootDialog.h" ClassImp(TQCanvasMenu) //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fCurrObj = 0; fParent = parent; fTabWin = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fParent = parent; fTabWin = tabWin; fCurrObj = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::~TQCanvasMenu() { // dtor if (fPopup) delete fPopup; } //______________________________________________________________________________ char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method ) { // Create title for dialog box retrieving argument values. static char methodTitle[128]; if (object && method) snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName()); else *methodTitle = 0; return methodTitle; } //______________________________________________________________________________ char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument) { // Create string describing argument (for use in dialog box). static Char_t argTitle[128]; if (argument) { snprintf(argTitle, 127, "(%s) %s", argument->GetTitle(), argument->GetName()); const char *arg_def = argument->GetDefault(); if (arg_def && *arg_def) { strncat(argTitle, " [default: ", 127 - strlen(argTitle)); strncat(argTitle, arg_def, 127 - strlen(argTitle)); strncat(argTitle, "]", 127 - strlen(argTitle)); } } else *argTitle = 0; return argTitle; } //______________________________________________________________________________ void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e) { // Perform the corresponding selected TObject popup // in the position defined // by x, y coordinates (in user coordinate system). // @param obj (TObject*) // @param p (QPoint&) TClass *klass=obj->IsA(); Int_t curId=-1; fCurrObj=obj; fPopup->clear(); fMethods.Clear(); QString buffer=klass->GetName(); buffer+="::"; buffer+=obj->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; klass->GetMenuItems(&fMethods); fPopup->insertSeparator(); TIter iter(&fMethods); TMethod *method=0; while ( (method = dynamic_cast<TMethod*>(iter())) != 0) { buffer=method->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; } // hold the position where the mouse was clicked fMousePosX= x; fMousePosY= y; // let Qt decide how to draw the popup Menu otherwise we have a problem that // the visible rectangle can get outside the screen (M.T. 03.06.02) fPopup->popup(e->globalPos(), 0); } //______________________________________________________________________________ void TQCanvasMenu::Execute(int id) { // Slot defined to execute a method from a selected TObject // using TObject::Execute() function. QString text=""; TVirtualPad *psave = gROOT->GetSelectedPad(); TMethod *method=(TMethod *)fMethods.At(id); fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) ); if ( method->GetListOfMethodArgs()->First() ) { Dialog(fCurrObj,method); } else { gROOT->SetFromPopUp(kTRUE); fCurrObj->Execute((char *) method->GetName(), ""); } fc->GetPadSave()->Update(); fc->GetPadSave()->Modified(); gROOT->SetSelectedPad(psave); gROOT->GetSelectedPad()->Update(); gROOT->GetSelectedPad()->Modified(); fc->Modified(); fc->ForceUpdate(); gROOT->SetFromPopUp( kFALSE ); } //______________________________________________________________________________ void TQCanvasMenu::Dialog(TObject* object, TMethod* method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". if (!(object && method)) return; fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method); fDialog->SetTCanvas(fc); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(method->GetListOfMethodArgs()); while ((argument = (TMethodArg *) next())) { char *argname = CreateArgumentTitle(argument); const char *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const char *charstar = "char*"; char basictype [32]; if (datatype) { strlcpy(basictype, datatype->GetTypeName(),32); } else { if (strncmp(type, "enum", 4) != 0) cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n"; strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod()) { char gettername[256] = ""; strlcpy(gettername, m->GetterMethod()->GetMethodName(),256); m->GetterMethod()->Init(object->IsA(), gettername, ""); // Get the current value and form it as a text: char val[256]; if (!strncmp(basictype, "char*", 5)) { char *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strlcpy(val, tdefval, 256); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval; m->GetterMethod()->Execute(object, "", ddefval); snprintf(val, 255, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval; m->GetterMethod()->Execute(object, "", ldefval); snprintf(val, 255, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl; // should stop dialog return; } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strlcpy(val, tval, 256); fDialog->Add(argname, val, type); } } //end while fDialog->Popup(); } <commit_msg>Fix coverity reports #32499 & #32500 (uninitialized scalar variables)<commit_after>// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "qevent.h" #include "qdialog.h" #include "qpushbutton.h" #include "qlabel.h" #include "qpainter.h" #if (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4 # include "qmenu.h" # include "q3popupmenu.h" typedef Q3PopupMenu QPopupMenu; #else # include "qpopupmenu.h" #endif #include "TQCanvasMenu.h" #include "TClass.h" #include "TROOT.h" #include "TMethod.h" #include "TMethodCall.h" #include "TMethodArg.h" #include "TCanvas.h" #include "TDataType.h" #include "TQRootDialog.h" ClassImp(TQCanvasMenu) //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fCurrObj = 0; fParent = parent; fTabWin = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fParent = parent; fTabWin = tabWin; fCurrObj = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::~TQCanvasMenu() { // dtor if (fPopup) delete fPopup; } //______________________________________________________________________________ char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method ) { // Create title for dialog box retrieving argument values. static char methodTitle[128]; if (object && method) snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName()); else *methodTitle = 0; return methodTitle; } //______________________________________________________________________________ char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument) { // Create string describing argument (for use in dialog box). static Char_t argTitle[128]; if (argument) { snprintf(argTitle, 127, "(%s) %s", argument->GetTitle(), argument->GetName()); const char *arg_def = argument->GetDefault(); if (arg_def && *arg_def) { strncat(argTitle, " [default: ", 127 - strlen(argTitle)); strncat(argTitle, arg_def, 127 - strlen(argTitle)); strncat(argTitle, "]", 127 - strlen(argTitle)); } } else *argTitle = 0; return argTitle; } //______________________________________________________________________________ void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e) { // Perform the corresponding selected TObject popup // in the position defined // by x, y coordinates (in user coordinate system). // @param obj (TObject*) // @param p (QPoint&) TClass *klass=obj->IsA(); Int_t curId=-1; fCurrObj=obj; fPopup->clear(); fMethods.Clear(); QString buffer=klass->GetName(); buffer+="::"; buffer+=obj->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; klass->GetMenuItems(&fMethods); fPopup->insertSeparator(); TIter iter(&fMethods); TMethod *method=0; while ( (method = dynamic_cast<TMethod*>(iter())) != 0) { buffer=method->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; } // hold the position where the mouse was clicked fMousePosX= x; fMousePosY= y; // let Qt decide how to draw the popup Menu otherwise we have a problem that // the visible rectangle can get outside the screen (M.T. 03.06.02) fPopup->popup(e->globalPos(), 0); } //______________________________________________________________________________ void TQCanvasMenu::Execute(int id) { // Slot defined to execute a method from a selected TObject // using TObject::Execute() function. QString text=""; TVirtualPad *psave = gROOT->GetSelectedPad(); TMethod *method=(TMethod *)fMethods.At(id); fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) ); if ( method->GetListOfMethodArgs()->First() ) { Dialog(fCurrObj,method); } else { gROOT->SetFromPopUp(kTRUE); fCurrObj->Execute((char *) method->GetName(), ""); } fc->GetPadSave()->Update(); fc->GetPadSave()->Modified(); gROOT->SetSelectedPad(psave); gROOT->GetSelectedPad()->Update(); gROOT->GetSelectedPad()->Modified(); fc->Modified(); fc->ForceUpdate(); gROOT->SetFromPopUp( kFALSE ); } //______________________________________________________________________________ void TQCanvasMenu::Dialog(TObject* object, TMethod* method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". if (!(object && method)) return; fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method); fDialog->SetTCanvas(fc); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(method->GetListOfMethodArgs()); while ((argument = (TMethodArg *) next())) { char *argname = CreateArgumentTitle(argument); const char *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const char *charstar = "char*"; char basictype [32]; if (datatype) { strlcpy(basictype, datatype->GetTypeName(),32); } else { if (strncmp(type, "enum", 4) != 0) cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n"; strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod()) { char gettername[256] = ""; strlcpy(gettername, m->GetterMethod()->GetMethodName(),256); m->GetterMethod()->Init(object->IsA(), gettername, ""); // Get the current value and form it as a text: char val[256]; if (!strncmp(basictype, "char*", 5)) { char *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strlcpy(val, tdefval, 256); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval = 0.0; m->GetterMethod()->Execute(object, "", ddefval); snprintf(val, 255, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval = 0L; m->GetterMethod()->Execute(object, "", ldefval); snprintf(val, 255, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl; // should stop dialog return; } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strlcpy(val, tval, 256); fDialog->Add(argname, val, type); } } //end while fDialog->Popup(); } <|endoftext|>
<commit_before>#include "GMSAssetResourceManagementSystem.hpp" #include "../AssetResources/TextureInfoResource.hpp" #include "../AssetResources/GMSRoomResource.hpp" #include <KEngine/Events/OtherGraphicsEvents.hpp> #include <KEngine/App.hpp> #include <KEngine/Core/EventManager.hpp> #include <KEngine/Utility/FileSystemHelper.hpp> #include <KEngine/Log/Log.hpp> #include <SFML/Graphics/Image.hpp> #include <algorithm> #include <execution> #include <filesystem> #include <fstream> #include <limits> #include <mutex> #include <utility> namespace { static const auto ProjectForecastExecAssetsRoot = "D:/workspace/ProjectForecastExecAssetsRoot"; static const auto ProjectForecastExecAssetPath = "D:/workspace/ProjectForecastExecAssetsRoot/assets"; } namespace pf { bool GMSAssetResourceManagementSystem::initialise() { ke::Log::instance()->info("Scanning assets..."); namespace fs = std::filesystem; ke::Log::instance()->info("Scanning texture assets..."); fs::path texturesRootDirPath = fs::path{ ProjectForecastExecAssetPath } / "textures"; sf::Image tempImage; std::hash<ke::String> hasher; for (const auto & texDirPath : ke::FileSystemHelper::getChildPaths(texturesRootDirPath)) { ke::Log::instance()->info("Discovered texture asset: {}", texDirPath.string()); auto textureFilePaths = ke::FileSystemHelper::getFilePaths(texDirPath); if (textureFilePaths.size() == 1) { auto texPath = textureFilePaths[0]; auto textureResource = std::make_shared<TextureInfoResource>(); textureResource->setName(texPath.stem().string()); textureResource->setTextureId(hasher(textureResource->getName())); textureResource->setSourcePath(texPath.string()); // retrieve size bool ret = tempImage.loadFromFile(texPath.string()); assert(ret); TextureInfoResource::DimensionType dimension; dimension.width = tempImage.getSize().x; dimension.height = tempImage.getSize().y; textureResource->setTextureSize(dimension); ke::App::instance()->getResourceManager()->registerResource(textureResource); } else { // ignore when there're multiple texture files in a single dir for now. } } ke::Log::instance()->info("Scanning GM:S room assets..."); const auto gmsRoomsRootDirPath = fs::path{ ProjectForecastExecAssetPath } / "rooms"; const auto gmsRoomPaths = ke::FileSystemHelper::getFilePaths(gmsRoomsRootDirPath); std::mutex gmsRoomLoadMutex; std::for_each(std::execution::par, std::begin(gmsRoomPaths), std::end(gmsRoomPaths), [&](const auto & gmsRoomPath) { ke::Log::instance()->info("Discovered GM:S room asset: {}", gmsRoomPath.string()); auto roomResource = std::make_shared<GMSRoomResource>(); roomResource->setName(gmsRoomPath.stem().string()); roomResource->setSourcePath(gmsRoomPath.string()); std::ifstream roomFileStream{ gmsRoomPath.string() }; ke::json roomJson; roomFileStream >> roomJson; // // Load general room info. // GMSRoomResource::SizeType roomSize; roomSize.width = roomJson["size"]["width"].get<unsigned>(); roomSize.height = roomJson["size"]["height"].get<unsigned>(); roomResource->setSize(roomSize); roomResource->setSpeed(roomJson["speed"].get<int>()); auto roomColourStr = roomJson["colour"].get<ke::String>(); assert(roomColourStr.length() == 9); assert(roomColourStr[0] == '#'); ke::Colour roomColour = { // assume colour is in hex RGBA starting with the '#' symbol. static_cast<uint8_t>(std::stol(roomColourStr.substr(1, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(roomColourStr.substr(3, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(roomColourStr.substr(5, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(roomColourStr.substr(7, 2), nullptr, 16)) }; roomResource->setColour(roomColour); // // load background info // auto roomBackgroundsJson = roomJson["bgs"]; for (const auto & backgroundJson : roomBackgroundsJson) { GMSRoomBackgroundInfo backgroundInfo; backgroundInfo.enabled = backgroundJson["enabled"].get<bool>(); backgroundInfo.foreground = backgroundJson["foreground"].get<bool>(); backgroundInfo.pos = { backgroundJson["pos"]["x"].get<int>(), -backgroundJson["pos"]["y"].get<int>() }; backgroundInfo.tilex = backgroundJson["tilex"].get<bool>(); backgroundInfo.tiley = backgroundJson["tiley"].get<bool>(); backgroundInfo.speed = { backgroundJson["speed"]["x"].get<int>(), -backgroundJson["speed"]["y"].get<int>() }; backgroundInfo.stretch = backgroundJson["stretch"].get<bool>(); backgroundInfo.bg = backgroundJson.value("bg", ""); backgroundInfo.bg_hash = hasher(backgroundInfo.bg); roomResource->addBackgroundInfo(backgroundInfo); } // // load tile instances // auto roomTilesJson = roomJson["tiles"]; for (const auto & tileJson : roomTilesJson) { pf::GMSRoomTileInstance newTile; newTile.instanceid = tileJson["instanceid"].get<unsigned>(); // Here we make sure to convert the GM:S room coordinates to KEngine's world coordinates. // I.e. y-down to y-up. // Texture coordinates are the same at the moment at y-down. I.e. (0,0) at top left. newTile.pos = { tileJson["pos"]["x"].get<int>(), -tileJson["pos"]["y"].get<int>() }; newTile.bg = tileJson["bg"].get<ke::String>(); newTile.bg_hash = hasher(newTile.bg); newTile.sourcepos = { tileJson["sourcepos"]["x"].get<int>(), tileJson["sourcepos"]["y"].get<int>() }; // sourcepos is y-down local image coordinates. newTile.size = { tileJson["size"]["width"].get<int>(), tileJson["size"]["height"].get<int>() }; newTile.scale = { tileJson["scale"]["x"].get<float>(), tileJson["scale"]["y"].get<float>() }; auto colourStr = tileJson["colour"].get<ke::String>(); assert(colourStr.length() == 9); assert(colourStr[0] == '#'); newTile.colour = { // assume colour is in hex RGBA starting with the '#' symbol. static_cast<uint8_t>(std::stol(colourStr.substr(1, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(colourStr.substr(3, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(colourStr.substr(5, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(colourStr.substr(7, 2), nullptr, 16)) }; // Here convert GM:S' depth system to KEngine's depth system. // GM:S depth value: larger == further back. // KEngine depth value: larger == further in front. newTile.tiledepth = -tileJson["tiledepth"].get<ke::graphics::DepthType>(); roomResource->addTile(newTile); } std::scoped_lock lock(gmsRoomLoadMutex); ke::App::instance()->getResourceManager()->registerResource(roomResource); }); ke::Log::instance()->info("Scanning assets... DONE"); return true; } void GMSAssetResourceManagementSystem::shutdown() { } void GMSAssetResourceManagementSystem::update(ke::Time elapsedTime) { KE_UNUSED(elapsedTime); } }<commit_msg>use std::execution::par_unseq intead of std::execution::par when loading GMS rooms<commit_after>#include "GMSAssetResourceManagementSystem.hpp" #include "../AssetResources/TextureInfoResource.hpp" #include "../AssetResources/GMSRoomResource.hpp" #include <KEngine/Events/OtherGraphicsEvents.hpp> #include <KEngine/App.hpp> #include <KEngine/Core/EventManager.hpp> #include <KEngine/Utility/FileSystemHelper.hpp> #include <KEngine/Log/Log.hpp> #include <SFML/Graphics/Image.hpp> #include <algorithm> #include <execution> #include <filesystem> #include <fstream> #include <limits> #include <mutex> #include <utility> namespace { static const auto ProjectForecastExecAssetsRoot = "D:/workspace/ProjectForecastExecAssetsRoot"; static const auto ProjectForecastExecAssetPath = "D:/workspace/ProjectForecastExecAssetsRoot/assets"; } namespace pf { bool GMSAssetResourceManagementSystem::initialise() { ke::Log::instance()->info("Scanning assets..."); namespace fs = std::filesystem; ke::Log::instance()->info("Scanning texture assets..."); fs::path texturesRootDirPath = fs::path{ ProjectForecastExecAssetPath } / "textures"; sf::Image tempImage; std::hash<ke::String> hasher; for (const auto & texDirPath : ke::FileSystemHelper::getChildPaths(texturesRootDirPath)) { ke::Log::instance()->info("Discovered texture asset: {}", texDirPath.string()); auto textureFilePaths = ke::FileSystemHelper::getFilePaths(texDirPath); if (textureFilePaths.size() == 1) { auto texPath = textureFilePaths[0]; auto textureResource = std::make_shared<TextureInfoResource>(); textureResource->setName(texPath.stem().string()); textureResource->setTextureId(hasher(textureResource->getName())); textureResource->setSourcePath(texPath.string()); // retrieve size bool ret = tempImage.loadFromFile(texPath.string()); assert(ret); TextureInfoResource::DimensionType dimension; dimension.width = tempImage.getSize().x; dimension.height = tempImage.getSize().y; textureResource->setTextureSize(dimension); ke::App::instance()->getResourceManager()->registerResource(textureResource); } else { // ignore when there're multiple texture files in a single dir for now. } } ke::Log::instance()->info("Scanning GM:S room assets..."); const auto gmsRoomsRootDirPath = fs::path{ ProjectForecastExecAssetPath } / "rooms"; const auto gmsRoomPaths = ke::FileSystemHelper::getFilePaths(gmsRoomsRootDirPath); std::mutex gmsRoomLoadMutex; std::for_each(std::execution::par_unseq, std::begin(gmsRoomPaths), std::end(gmsRoomPaths), [&](const auto & gmsRoomPath) { ke::Log::instance()->info("Discovered GM:S room asset: {}", gmsRoomPath.string()); auto roomResource = std::make_shared<GMSRoomResource>(); roomResource->setName(gmsRoomPath.stem().string()); roomResource->setSourcePath(gmsRoomPath.string()); std::ifstream roomFileStream{ gmsRoomPath.string() }; ke::json roomJson; roomFileStream >> roomJson; // // Load general room info. // GMSRoomResource::SizeType roomSize; roomSize.width = roomJson["size"]["width"].get<unsigned>(); roomSize.height = roomJson["size"]["height"].get<unsigned>(); roomResource->setSize(roomSize); roomResource->setSpeed(roomJson["speed"].get<int>()); auto roomColourStr = roomJson["colour"].get<ke::String>(); assert(roomColourStr.length() == 9); assert(roomColourStr[0] == '#'); ke::Colour roomColour = { // assume colour is in hex RGBA starting with the '#' symbol. static_cast<uint8_t>(std::stol(roomColourStr.substr(1, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(roomColourStr.substr(3, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(roomColourStr.substr(5, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(roomColourStr.substr(7, 2), nullptr, 16)) }; roomResource->setColour(roomColour); // // load background info // auto roomBackgroundsJson = roomJson["bgs"]; for (const auto & backgroundJson : roomBackgroundsJson) { GMSRoomBackgroundInfo backgroundInfo; backgroundInfo.enabled = backgroundJson["enabled"].get<bool>(); backgroundInfo.foreground = backgroundJson["foreground"].get<bool>(); backgroundInfo.pos = { backgroundJson["pos"]["x"].get<int>(), -backgroundJson["pos"]["y"].get<int>() }; backgroundInfo.tilex = backgroundJson["tilex"].get<bool>(); backgroundInfo.tiley = backgroundJson["tiley"].get<bool>(); backgroundInfo.speed = { backgroundJson["speed"]["x"].get<int>(), -backgroundJson["speed"]["y"].get<int>() }; backgroundInfo.stretch = backgroundJson["stretch"].get<bool>(); backgroundInfo.bg = backgroundJson.value("bg", ""); backgroundInfo.bg_hash = hasher(backgroundInfo.bg); roomResource->addBackgroundInfo(backgroundInfo); } // // load tile instances // auto roomTilesJson = roomJson["tiles"]; for (const auto & tileJson : roomTilesJson) { pf::GMSRoomTileInstance newTile; newTile.instanceid = tileJson["instanceid"].get<unsigned>(); // Here we make sure to convert the GM:S room coordinates to KEngine's world coordinates. // I.e. y-down to y-up. // Texture coordinates are the same at the moment at y-down. I.e. (0,0) at top left. newTile.pos = { tileJson["pos"]["x"].get<int>(), -tileJson["pos"]["y"].get<int>() }; newTile.bg = tileJson["bg"].get<ke::String>(); newTile.bg_hash = hasher(newTile.bg); newTile.sourcepos = { tileJson["sourcepos"]["x"].get<int>(), tileJson["sourcepos"]["y"].get<int>() }; // sourcepos is y-down local image coordinates. newTile.size = { tileJson["size"]["width"].get<int>(), tileJson["size"]["height"].get<int>() }; newTile.scale = { tileJson["scale"]["x"].get<float>(), tileJson["scale"]["y"].get<float>() }; auto colourStr = tileJson["colour"].get<ke::String>(); assert(colourStr.length() == 9); assert(colourStr[0] == '#'); newTile.colour = { // assume colour is in hex RGBA starting with the '#' symbol. static_cast<uint8_t>(std::stol(colourStr.substr(1, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(colourStr.substr(3, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(colourStr.substr(5, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(colourStr.substr(7, 2), nullptr, 16)) }; // Here convert GM:S' depth system to KEngine's depth system. // GM:S depth value: larger == further back. // KEngine depth value: larger == further in front. newTile.tiledepth = -tileJson["tiledepth"].get<ke::graphics::DepthType>(); roomResource->addTile(newTile); } std::scoped_lock lock(gmsRoomLoadMutex); ke::App::instance()->getResourceManager()->registerResource(roomResource); }); ke::Log::instance()->info("Scanning assets... DONE"); return true; } void GMSAssetResourceManagementSystem::shutdown() { } void GMSAssetResourceManagementSystem::update(ke::Time elapsedTime) { KE_UNUSED(elapsedTime); } }<|endoftext|>
<commit_before>#ifdef CHEMISTRY_GPU #include "chemistry_gpu.h" #include "../grid3D.h" #include "../io.h" #ifdef DE #include"../hydro_cuda.h" #endif void Grid3D::Initialize_Chemistry( struct parameters *P ){ chprintf( "Initializing the GPU Chemistry Solver... \n"); Chem.nx = H.nx; Chem.ny = H.ny; Chem.nz = H.nz; Chem.gamma = gama; Chem.Initialize( P ); // Initialize the Chemistry Header #ifdef COSMOLOGY Real kpc_cgs = KPC_CGS; Chem.H.density_conversion = Cosmo.rho_0_gas * Cosmo.cosmo_h * Cosmo.cosmo_h / pow( kpc_cgs, 3) * MSUN_CGS ; Chem.H.energy_conversion = Cosmo.v_0_gas * Cosmo.v_0_gas * 1e10; //km^2 -> cm^2 ; Chem.H.cosmological_parameters_d = Chem.cosmo_params_d; #else // Not COSMOLOGY Chem.H.density_conversion = 1.0; Chem.H.energy_conversion = 1.0; Chem.H.cosmological_parameters_d = NULL; #endif Chem.H.n_uvb_rates_samples = Chem.n_uvb_rates_samples; Chem.H.uvb_rates_redshift_d = Chem.rates_z_d; Chem.H.photo_ion_HI_rate_d = Chem.Ion_rates_HI_d; Chem.H.photo_ion_HeI_rate_d = Chem.Ion_rates_HeI_d; Chem.H.photo_ion_HeII_rate_d = Chem.Ion_rates_HeII_d; Chem.H.photo_heat_HI_rate_d = Chem.Heat_rates_HI_d; Chem.H.photo_heat_HeI_rate_d = Chem.Heat_rates_HeI_d; Chem.H.photo_heat_HeII_rate_d = Chem.Heat_rates_HeII_d; chprintf( "Allocating Memory. \n\n"); int n_cells = H.nx * H.ny * H.nz; Chem.Fields.temperature_h = (Real *) malloc(n_cells * sizeof(Real)); chprintf( "Chemistry Solver Successfully Initialized. \n\n"); } void Chem_GPU::Initialize( struct parameters *P ){ chprintf( " Initializing Cosmological Parameters... \n"); cosmo_params_h = (float *)malloc(3*sizeof(Real)); cosmo_params_h[0] = (float)P->H0; cosmo_params_h[1] = (float)P->Omega_M; cosmo_params_h[2] = (float)P->Omega_L; Allocate_Array_GPU_float( &cosmo_params_d, 3 ); Copy_Float_Array_to_Device( 3, cosmo_params_h, cosmo_params_d ); Initialize_UVB_Ionization_and_Heating_Rates( P ); } void Chem_GPU::Initialize_UVB_Ionization_and_Heating_Rates( struct parameters *P ){ Load_UVB_Ionization_and_Heating_Rates( P ); Copy_UVB_Rates_to_GPU( ); Bind_GPU_Textures( n_uvb_rates_samples, Heat_rates_HI_h, Heat_rates_HeI_h, Heat_rates_HeII_h, Ion_rates_HI_h, Ion_rates_HeI_h, Ion_rates_HeII_h); } void Chem_GPU::Copy_UVB_Rates_to_GPU( ){ Allocate_Array_GPU_float( &rates_z_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Heat_rates_HI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Heat_rates_HeI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Heat_rates_HeII_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Ion_rates_HI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Ion_rates_HeI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Ion_rates_HeII_d, n_uvb_rates_samples ); Copy_Float_Array_to_Device( n_uvb_rates_samples, rates_z_h, rates_z_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Heat_rates_HI_h, Heat_rates_HI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Heat_rates_HeI_h, Heat_rates_HeI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Heat_rates_HeII_h, Heat_rates_HeII_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Ion_rates_HI_h, Ion_rates_HI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Ion_rates_HeI_h, Ion_rates_HeI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Ion_rates_HeII_h, Ion_rates_HeII_d ); } void Grid3D::Update_Chemistry_Header(){ #ifdef COSMOLOGY Chem.H.current_z = Cosmo.current_z; #else Chem.H.current_z = 0; #endif Chem.H.runtime_chemistry_step = 0; } void Grid3D::Compute_Gas_Temperature( Real *temperature ){ int k, j, i, id; Real dens_HI, dens_HII, dens_HeI, dens_HeII, dens_HeIII, dens_e, gamma; Real d, vx, vy, vz, E, E_kin, GE, P, mu, temp, cell_dens, cell_n; gamma = gama; for (k=0; k<H.nz; k++) { for (j=0; j<H.ny; j++) { for (i=0; i<H.nx; i++) { id = i + j*H.nx + k*H.nx*H.ny; d = C.density[id]; vx = C.momentum_x[id] / d; vy = C.momentum_y[id] / d; vz = C.momentum_z[id] / d; E = C.Energy[id]; E_kin = 0.5 * d * ( vx*vx + vy*vy + vz*vz ); #ifdef DE GE = C.GasEnergy[id]; P = GE * (gamma - 1.0); #else P = (dev_conserved[4*n_cells + id] - 0.5*d*(vx*vx + vy*vy + vz*vz)) * (gamma - 1.0); #endif dens_HI = C.HI_density[id]; dens_HII = C.HII_density[id]; dens_HeI = C.HeI_density[id]; dens_HeII = C.HeII_density[id]; dens_HeIII = C.HeIII_density[id]; dens_e = C.e_density[id]; cell_dens = dens_HI + dens_HII + dens_HeI + dens_HeII + dens_HeIII; cell_n = dens_HI + dens_HII + ( dens_HeI + dens_HeII + dens_HeIII )/4 + dens_e; mu = cell_dens / cell_n; temp = P * MP * mu / d / KB; #ifdef COSMOLOGY temp *= 1e10; // convert from (km/s)^2 to (cm/s)^2 #endif temperature[id] = temp; // chprintf( "mu: %e \n", mu ); if ( temp < 0 ) chprintf( "Negative Temperature: %e \n", temp ); } } } } void Chem_GPU::Reset(){ free( rates_z_h ); free( Heat_rates_HI_h ); free( Heat_rates_HeI_h ); free( Heat_rates_HeII_h ); free( Ion_rates_HI_h ); free( Ion_rates_HeI_h ); free( Ion_rates_HeII_h ); Free_Array_GPU_float( rates_z_d ); Free_Array_GPU_float( Heat_rates_HI_d ); Free_Array_GPU_float( Heat_rates_HeI_d ); Free_Array_GPU_float( Heat_rates_HeII_d ); Free_Array_GPU_float( Ion_rates_HI_d ); Free_Array_GPU_float( Ion_rates_HeI_d ); Free_Array_GPU_float( Ion_rates_HeII_d ); free( Fields.temperature_h ); } #endif<commit_msg>fixed temperature calculation<commit_after>#ifdef CHEMISTRY_GPU #include "chemistry_gpu.h" #include "../grid3D.h" #include "../io.h" #ifdef DE #include"../hydro_cuda.h" #endif void Grid3D::Initialize_Chemistry( struct parameters *P ){ chprintf( "Initializing the GPU Chemistry Solver... \n"); Chem.nx = H.nx; Chem.ny = H.ny; Chem.nz = H.nz; Chem.gamma = gama; Chem.Initialize( P ); // Initialize the Chemistry Header #ifdef COSMOLOGY Real kpc_cgs = KPC_CGS; Chem.H.density_conversion = Cosmo.rho_0_gas * Cosmo.cosmo_h * Cosmo.cosmo_h / pow( kpc_cgs, 3) * MSUN_CGS ; Chem.H.energy_conversion = Cosmo.v_0_gas * Cosmo.v_0_gas * 1e10; //km^2 -> cm^2 ; Chem.H.cosmological_parameters_d = Chem.cosmo_params_d; #else // Not COSMOLOGY Chem.H.density_conversion = 1.0; Chem.H.energy_conversion = 1.0; Chem.H.cosmological_parameters_d = NULL; #endif Chem.H.n_uvb_rates_samples = Chem.n_uvb_rates_samples; Chem.H.uvb_rates_redshift_d = Chem.rates_z_d; Chem.H.photo_ion_HI_rate_d = Chem.Ion_rates_HI_d; Chem.H.photo_ion_HeI_rate_d = Chem.Ion_rates_HeI_d; Chem.H.photo_ion_HeII_rate_d = Chem.Ion_rates_HeII_d; Chem.H.photo_heat_HI_rate_d = Chem.Heat_rates_HI_d; Chem.H.photo_heat_HeI_rate_d = Chem.Heat_rates_HeI_d; Chem.H.photo_heat_HeII_rate_d = Chem.Heat_rates_HeII_d; chprintf( "Allocating Memory. \n\n"); int n_cells = H.nx * H.ny * H.nz; Chem.Fields.temperature_h = (Real *) malloc(n_cells * sizeof(Real)); chprintf( "Chemistry Solver Successfully Initialized. \n\n"); } void Chem_GPU::Initialize( struct parameters *P ){ chprintf( " Initializing Cosmological Parameters... \n"); cosmo_params_h = (float *)malloc(3*sizeof(Real)); cosmo_params_h[0] = (float)P->H0; cosmo_params_h[1] = (float)P->Omega_M; cosmo_params_h[2] = (float)P->Omega_L; Allocate_Array_GPU_float( &cosmo_params_d, 3 ); Copy_Float_Array_to_Device( 3, cosmo_params_h, cosmo_params_d ); Initialize_UVB_Ionization_and_Heating_Rates( P ); } void Chem_GPU::Initialize_UVB_Ionization_and_Heating_Rates( struct parameters *P ){ Load_UVB_Ionization_and_Heating_Rates( P ); Copy_UVB_Rates_to_GPU( ); Bind_GPU_Textures( n_uvb_rates_samples, Heat_rates_HI_h, Heat_rates_HeI_h, Heat_rates_HeII_h, Ion_rates_HI_h, Ion_rates_HeI_h, Ion_rates_HeII_h); } void Chem_GPU::Copy_UVB_Rates_to_GPU( ){ Allocate_Array_GPU_float( &rates_z_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Heat_rates_HI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Heat_rates_HeI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Heat_rates_HeII_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Ion_rates_HI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Ion_rates_HeI_d, n_uvb_rates_samples ); Allocate_Array_GPU_float( &Ion_rates_HeII_d, n_uvb_rates_samples ); Copy_Float_Array_to_Device( n_uvb_rates_samples, rates_z_h, rates_z_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Heat_rates_HI_h, Heat_rates_HI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Heat_rates_HeI_h, Heat_rates_HeI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Heat_rates_HeII_h, Heat_rates_HeII_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Ion_rates_HI_h, Ion_rates_HI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Ion_rates_HeI_h, Ion_rates_HeI_d ); Copy_Float_Array_to_Device( n_uvb_rates_samples, Ion_rates_HeII_h, Ion_rates_HeII_d ); } void Grid3D::Update_Chemistry_Header(){ #ifdef COSMOLOGY Chem.H.current_z = Cosmo.current_z; #else Chem.H.current_z = 0; #endif Chem.H.runtime_chemistry_step = 0; } void Grid3D::Compute_Gas_Temperature( Real *temperature ){ int k, j, i, id; Real dens_HI, dens_HII, dens_HeI, dens_HeII, dens_HeIII, dens_e, gamma; Real d, vx, vy, vz, E, GE, mu, temp, cell_dens, cell_n; Real current_a, a2; gamma = gama; for (k=0; k<H.nz; k++) { for (j=0; j<H.ny; j++) { for (i=0; i<H.nx; i++) { id = i + j*H.nx + k*H.nx*H.ny; d = C.density[id]; vx = C.momentum_x[id] / d; vy = C.momentum_y[id] / d; vz = C.momentum_z[id] / d; E = C.Energy[id]; #ifdef DE GE = C.GasEnergy[id]; #else GE = (dev_conserved[4*n_cells + id] - 0.5*d*(vx*vx + vy*vy + vz*vz)); #endif dens_HI = C.HI_density[id]; dens_HII = C.HII_density[id]; dens_HeI = C.HeI_density[id]; dens_HeII = C.HeII_density[id]; dens_HeIII = C.HeIII_density[id]; dens_e = C.e_density[id]; cell_dens = dens_HI + dens_HII + dens_HeI + dens_HeII + dens_HeIII; cell_n = dens_HI + dens_HII + ( dens_HeI + dens_HeII + dens_HeIII )/4 + dens_e; mu = cell_dens / cell_n; #ifdef COSMOLOGY current_a = Cosmo.current_a; a2 = current_a * current_a; GE *= Chem.H.energy_conversion / a2; #endif temp = GE * MP * mu / d / KB * (gamma - 1.0); ; temperature[id] = temp; // chprintf( "mu: %e \n", mu ); // if ( temp > 1e7 ) chprintf( "Temperature: %e mu: %e \n", temp, mu ); } } } } void Chem_GPU::Reset(){ free( rates_z_h ); free( Heat_rates_HI_h ); free( Heat_rates_HeI_h ); free( Heat_rates_HeII_h ); free( Ion_rates_HI_h ); free( Ion_rates_HeI_h ); free( Ion_rates_HeII_h ); Free_Array_GPU_float( rates_z_d ); Free_Array_GPU_float( Heat_rates_HI_d ); Free_Array_GPU_float( Heat_rates_HeI_d ); Free_Array_GPU_float( Heat_rates_HeII_d ); Free_Array_GPU_float( Ion_rates_HI_d ); Free_Array_GPU_float( Ion_rates_HeI_d ); Free_Array_GPU_float( Ion_rates_HeII_d ); free( Fields.temperature_h ); } #endif<|endoftext|>
<commit_before><commit_msg>Prediction: minor fixes.<commit_after><|endoftext|>
<commit_before>#ifndef CTHREADPOOLITEM_RET #define CTHREADPOOLITEM_RET #include<functional> //bind, ref #include<utility> //forward #include"../../lib/header/tool/CScopeGuard.hpp" #include"../../lib/header/thread/CTask.hpp" #include"../../lib/header/thread/CWait_bounded_queue.hpp" #include"IThreadPoolItemBase.hpp" namespace nThread { template<class Ret> class CThreadPoolItem_Ret:public IThreadPoolItemBase { CTask<Ret> exec_; CWait_bounded_queue<CThreadPoolItem_Ret<Ret>*> *waiting_queue_; public: CThreadPoolItem_Ret(CWait_bounded_queue<CThreadPoolItem_Ret<Ret>*> *waitingQue) :waiting_queue_{waitingQue}{} CThreadPoolItem_Ret(const CThreadPoolItem_Ret &)=delete; CThreadPoolItem_Ret(CThreadPoolItem_Ret &&)=default; template<class Func,class ... Args> void assign(Func &&func,Args &&...args) { exec_=CTask<Ret>{std::forward<Func>(func),std::forward<Args>(args)...}; IThreadPoolItemBase::exec_(std::bind(&CTask<Ret>::operator(),std::ref(exec_))); } inline Ret get() { const nTool::CScopeGuard sg{[this]{waiting_queue_->emplace_and_notify(this);}}; return exec_.get(); } bool is_running() const noexcept override { return exec_.valid(); } void wait() const override { exec_.wait(); } CThreadPoolItem_Ret& operator=(const CThreadPoolItem_Ret &)=delete; CThreadPoolItem_Ret& operator=(CThreadPoolItem_Ret &&)=default; ~CThreadPoolItem_Ret() { if(is_running()) wait(); } }; } #endif<commit_msg>reorder code<commit_after>#ifndef CTHREADPOOLITEM_RET #define CTHREADPOOLITEM_RET #include<functional> //bind, ref #include<utility> //forward #include"../../lib/header/thread/CTask.hpp" #include"../../lib/header/thread/CWait_bounded_queue.hpp" #include"../../lib/header/tool/CScopeGuard.hpp" #include"IThreadPoolItemBase.hpp" namespace nThread { template<class Ret> class CThreadPoolItem_Ret:public IThreadPoolItemBase { CTask<Ret> exec_; CWait_bounded_queue<CThreadPoolItem_Ret<Ret>*> *waiting_queue_; public: CThreadPoolItem_Ret(CWait_bounded_queue<CThreadPoolItem_Ret<Ret>*> *waitingQue) :waiting_queue_{waitingQue}{} CThreadPoolItem_Ret(const CThreadPoolItem_Ret &)=delete; CThreadPoolItem_Ret(CThreadPoolItem_Ret &&)=default; template<class Func,class ... Args> void assign(Func &&func,Args &&...args) { exec_=CTask<Ret>{std::forward<Func>(func),std::forward<Args>(args)...}; IThreadPoolItemBase::exec_(std::bind(&CTask<Ret>::operator(),std::ref(exec_))); } inline Ret get() { const nTool::CScopeGuard sg{[this]{waiting_queue_->emplace_and_notify(this);}}; return exec_.get(); } bool is_running() const noexcept override { return exec_.valid(); } void wait() const override { exec_.wait(); } CThreadPoolItem_Ret& operator=(const CThreadPoolItem_Ret &)=delete; CThreadPoolItem_Ret& operator=(CThreadPoolItem_Ret &&)=default; ~CThreadPoolItem_Ret() { if(is_running()) wait(); } }; } #endif<|endoftext|>
<commit_before>#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ #include <sqlite3.h> int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_md49_speed (unsigned char speed_l, unsigned char speed_r); // sqlite globals sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; const char* data = "Callback function called"; using namespace std; base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; } if (vel_cmd.linear.x<0){ speed_l = 1; speed_r = 1; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 1; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 1; } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ // Setup as ROS node // ***************** ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); ros::Rate loop_rate(10); ROS_INFO("Starting base_controller node:"); ROS_INFO("============================================"); ROS_INFO("subscribing to /cmd_vel"); ROS_INFO("publishing to /encoders"); ROS_INFO("publishing to /md49data"); ROS_INFO("============================================"); // Open database md49data.db and add // table md49commands // ********************************* rc = sqlite3_open("data/md49data.db", &db); if( rc ){ ROS_INFO("Can't open database: %s", sqlite3_errmsg(db)); exit(0); }else{ ROS_INFO("Opened database successfully,"); } // Create table md49commands // ************************* sql = "CREATE TABLE md49commands(" \ "ID INT PRIMARY KEY NOT NULL," \ "SpeedL INT DEFAULT 128," \ "SpeedR INT DEFAULT 128 );" \ "INSERT INTO md49commands (ID,SpeedL,SpeedR) VALUES (1,128,128);"; rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); // Execute SQL statement if( rc != SQLITE_OK ){ ROS_INFO("SQL message: %s", zErrMsg); sqlite3_free(zErrMsg); }else{ ROS_INFO("table created successfully"); } // Set SpeedL and SpeedR to // defaults =128 // ************************ char sql_buffer[200]; int cx; cx = snprintf (sql_buffer,200,"UPDATE md49commands SET SpeedL=%i, SpeedR=%i WHERE ID=1", 128,128); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ ROS_INFO("SQL message: %s", zErrMsg); sqlite3_free(zErrMsg); }else{ ROS_INFO("SpeedL & SpeedR set to defaults in Table md49commands(md49data.db)"); } while(n.ok()) { // Read encoder values and other data from MD49: // serial_controller_node reads data from AVR-Master // and provides that data in md49_data.txt // ************************************************* // read_MD49_Data(); // Set MD49 speed_l and speed_r: // serial_controller_node reads commands from // md49_commands.txt and writes commands to AVR-Master // *************************************************** if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_md49_speed(speed_l,speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = serialBuffer[8]; md49data.speed_r = serialBuffer[9]; md49data.volt = serialBuffer[10]; md49data.current_l = serialBuffer[11]; md49data.current_r = serialBuffer[12]; md49data.error = serialBuffer[13]; md49data.acceleration = serialBuffer[14]; md49data.mode = serialBuffer[15]; md49data.regulator = serialBuffer[16]; md49data.timeout = serialBuffer[17]; md49data_pub.publish(md49data); ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ // Read all MD49 data from md49_data.txt // ************************************* string line; ifstream myfile ("md49_data.txt"); if (myfile.is_open()){ int i=0; while (getline (myfile,line)){ //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); serialBuffer[i]=atoi(data); i =i++; } myfile.close(); } else ROS_ERROR("Unable to open file: md49_data.txt"); // Put toghether new encodervalues // ******************************* EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_md49_speed (unsigned char speed_l, unsigned char speed_r){ // Set SpeedL=speed_l and // SpeedR=speed_r in Table md49commands // ************************************ char sql_buffer[200]; int cx; cx = snprintf (sql_buffer,200,"UPDATE md49commands SET SpeedL=%i, SpeedR=%i WHERE ID=1", speed_l,speed_r); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ ROS_WARN("SQL message: %s", zErrMsg); sqlite3_free(zErrMsg); }else{ ROS_INFO("Set SpeedL=%i and SpeedR=%i in Table md49commands(md49data.db)",speed_l, speed_r); } } <commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ #include <sqlite3.h> int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_md49_speed (unsigned char speed_l, unsigned char speed_r); void open_sql_db_md49data(void); // sqlite globals sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; const char* data = "Callback function called"; using namespace std; base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } void open_sql_db_md49data(void){ // Open database md49data.db and add // table md49commands // ********************************* rc = sqlite3_open("data/md49data.db", &db); if( rc ){ ROS_INFO("Can't open database: %s", sqlite3_errmsg(db)); exit(0); }else{ ROS_INFO("Opened database successfully,"); } // Create table md49commands // ************************* sql = "CREATE TABLE md49commands(" \ "ID INT PRIMARY KEY NOT NULL," \ "SpeedL INT DEFAULT 128," \ "SpeedR INT DEFAULT 128 );" \ "INSERT INTO md49commands (ID,SpeedL,SpeedR) VALUES (1,128,128);"; rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); // Execute SQL statement if( rc != SQLITE_OK ){ ROS_INFO("SQL message: %s", zErrMsg); sqlite3_free(zErrMsg); }else{ ROS_INFO("table created successfully"); } // Set SpeedL and SpeedR to // defaults =128 // ************************ char sql_buffer[200]; int cx; cx = snprintf (sql_buffer,200,"UPDATE md49commands SET SpeedL=%i, SpeedR=%i WHERE ID=1", 128,128); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ ROS_INFO("SQL message: %s", zErrMsg); sqlite3_free(zErrMsg); }else{ ROS_INFO("SpeedL & SpeedR set to defaults in Table md49commands(md49data.db)"); } } int main( int argc, char* argv[] ){ // Setup as ROS node // ***************** ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); ros::Rate loop_rate(10); ROS_INFO("Starting base_controller node:"); ROS_INFO("============================================"); ROS_INFO("subscribing to /cmd_vel"); ROS_INFO("publishing to /encoders"); ROS_INFO("publishing to /md49data"); ROS_INFO("============================================"); open_sql_db_md49data(); while(n.ok()) { // Read encoder values and other data from MD49: // serial_controller_node reads data from AVR-Master // and provides that data in md49_data.txt // ************************************************* // read_MD49_Data(); // Set MD49 speed_l and speed_r: // serial_controller_node reads commands from // md49_commands.txt and writes commands to AVR-Master // *************************************************** if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_md49_speed(speed_l,speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = serialBuffer[8]; md49data.speed_r = serialBuffer[9]; md49data.volt = serialBuffer[10]; md49data.current_l = serialBuffer[11]; md49data.current_r = serialBuffer[12]; md49data.error = serialBuffer[13]; md49data.acceleration = serialBuffer[14]; md49data.mode = serialBuffer[15]; md49data.regulator = serialBuffer[16]; md49data.timeout = serialBuffer[17]; md49data_pub.publish(md49data); ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ // Read MD49 data from md49data.db // ******************************* // code here! // Read all MD49 data from md49_data.txt // ************************************* string line; ifstream myfile ("md49_data.txt"); if (myfile.is_open()){ int i=0; while (getline (myfile,line)){ //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); serialBuffer[i]=atoi(data); i =i++; } myfile.close(); } else ROS_ERROR("Unable to open file: md49_data.txt"); // Put toghether new encodervalues // ******************************* EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_md49_speed (unsigned char speed_l, unsigned char speed_r){ // Set SpeedL=speed_l and // SpeedR=speed_r in Table md49commands // ************************************ char sql_buffer[200]; int cx; cx = snprintf (sql_buffer,200,"UPDATE md49commands SET SpeedL=%i, SpeedR=%i WHERE ID=1", speed_l,speed_r); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ ROS_WARN("SQL message: %s", zErrMsg); sqlite3_free(zErrMsg); }else{ ROS_INFO("Set SpeedL=%s and SpeedR=%s in Table md49commands(md49data.db)",speed_l, speed_r); } } <|endoftext|>
<commit_before>#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ //#include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int16_t EncoderL; /* stores encoder value left read from md49 */ int16_t EncoderR; /* stores encoder value right read from md49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 255; // speed1 serialBuffer[3] = 255; // speed2 writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 0; // speed1 serialBuffer[3] = 0; // speed2 writeBytes(fd, 4); } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 128; // speed1 serialBuffer[3] = 128; // speed2 writeBytes(fd, 4); } if (vel_cmd.angular.z>0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 0; // speed1 serialBuffer[3] = 255; // speed2 writeBytes(fd, 4); } if (vel_cmd.angular.z<0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 255; // speed1 serialBuffer[3] = 0; // speed2 writeBytes(fd, 4); } } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(5); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); } <commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ //#include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int16_t EncoderL; /* stores encoder value left read from md49 */ int16_t EncoderR; /* stores encoder value right read from md49 */ int speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (int speed_l, int speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(10); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left andright for MD49 // ******************************** //if (cmd_vel_received=true) {set_MD49_speed(speed_l,speed_r); cmd_vel_received=false;} set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); //printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); } void set_MD49_speed (int speed_l, int speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); } <|endoftext|>
<commit_before>/** @file @brief Main file for a unified video-based and inertial tracking system. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "ImageSources/ImageSource.h" #include "ImageSources/ImageSourceFactories.h" #include "MakeHDKTrackingSystem.h" #include "TrackingSystem.h" #include "ThreadsafeBodyReporting.h" #include "HDKLedIdentifierFactory.h" #include "CameraParameters.h" #include "HDKData.h" #include <osvr/AnalysisPluginKit/AnalysisPluginKitC.h> #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include <osvr/PluginKit/AnalogInterfaceC.h> #include <osvr/Util/EigenInterop.h> #include "ConfigurationParser.h" // Generated JSON header file #include "org_osvr_unifiedvideoinertial_json.h" // Library/third-party includes #include <opencv2/core/core.hpp> // for basic OpenCV types #include <opencv2/core/operations.hpp> #include <opencv2/highgui/highgui.hpp> // for image capture #include <opencv2/imgproc/imgproc.hpp> // for image scaling #include <json/value.h> #include <json/reader.h> #include <boost/noncopyable.hpp> #include <util/Stride.h> // Standard includes #include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <memory> #include <thread> #include <mutex> #include <stdexcept> // Anonymous namespace to avoid symbol collision namespace { static const auto DRIVER_NAME = "UnifiedTrackingSystem"; static const auto DEBUGGABLE_BEACONS = 34; static const auto DATAPOINTS_PER_BEACON = 5; using TrackingSystemPtr = std::unique_ptr<osvr::vbtracker::TrackingSystem>; using BodyReportingVector = std::vector<osvr::vbtracker::BodyReportingPtr>; class TrackerThread : boost::noncopyable { public: TrackerThread(osvr::vbtracker::TrackingSystem &trackingSystem, osvr::vbtracker::ImageSource &imageSource, BodyReportingVector &reportingVec, osvr::vbtracker::CameraParameters const &camParams) : m_trackingSystem(trackingSystem), m_cam(imageSource), m_reportingVec(reportingVec), m_camParams(camParams) { msg() << "Tracker thread object created." << std::endl; } void operator()() { msg() << "Tracker thread object invoked." << std::endl; bool keepGoing = true; while (keepGoing) { doFrame(); { /// Copy the run flag. std::lock_guard<std::mutex> lock(m_runMutex); keepGoing = m_run; } if (!keepGoing) { msg() << "Tracker thread object: Just checked our run flag and " "noticed it turned false..." << std::endl; } } msg() << "Tracker thread object: functor exiting." << std::endl; } /// Call from the main thread! void triggerStop() { msg() << "Tracker thread object: triggerStop() called" << std::endl; std::lock_guard<std::mutex> lock(m_runMutex); m_run = false; } private: std::ostream &msg() const { return std::cout << "[UnifiedTracker] "; } std::ostream &warn() const { return msg() << "Warning: "; } void doFrame() { // Check camera status. if (!m_cam.ok()) { // Hmm, camera seems bad. Might regain it? Skip for now... warn() << "Camera is reporting it is not OK." << std::endl; return; } // Trigger a grab. if (!m_cam.grab()) { // Again failing without quitting, in hopes we get better luck next // time... warn() << "Camera grab failed." << std::endl; return; } // When we triggered the grab is our current best guess of the time for // the image /// @todo backdate to account for image transfer image, exposure time, /// etc. auto tv = osvr::util::time::getNow(); // Pull the image into an OpenCV matrix named m_frame. m_cam.retrieve(m_frame, m_frameGray); if (!m_frame.data || !m_frameGray.data) { warn() << "Camera retrieve appeared to fail: frames had null pointers!" << std::endl; return; } // Submit to the tracking system. auto bodyIds = m_trackingSystem.processFrame(tv, m_frame, m_frameGray, m_camParams); for (auto const &bodyId : bodyIds) { auto &body = m_trackingSystem.getBody(bodyId); m_reportingVec[bodyId.value()]->updateState( body.getStateTime(), body.getState(), body.getProcessModel()); } } osvr::vbtracker::TrackingSystem &m_trackingSystem; osvr::vbtracker::ImageSource &m_cam; BodyReportingVector &m_reportingVec; osvr::vbtracker::CameraParameters m_camParams; cv::Mat m_frame; cv::Mat m_frameGray; std::mutex m_runMutex; volatile bool m_run = true; }; class UnifiedVideoInertialTracker : boost::noncopyable { public: using size_type = std::size_t; UnifiedVideoInertialTracker(OSVR_PluginRegContext ctx, osvr::vbtracker::ImageSourcePtr &&source, osvr::vbtracker::ConfigParams params, TrackingSystemPtr &&trackingSystem) : m_source(std::move(source)), m_trackingSystem(std::move(trackingSystem)), m_additionalPrediction(params.additionalPrediction) { if (params.numThreads > 0) { // Set the number of threads for OpenCV to use. cv::setNumThreads(params.numThreads); } /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); // Configure the tracker interface. osvrDeviceTrackerConfigure(opts, &m_tracker); #if 0 osvrDeviceAnalogConfigure(opts, &m_analog, DEBUGGABLE_BEACONS * DATAPOINTS_PER_BEACON); #endif /// Create the analysis device token with the options OSVR_DeviceToken dev; if (OSVR_RETURN_FAILURE == osvrAnalysisSyncInit(ctx, DRIVER_NAME, opts, &dev, &m_clientCtx)) { throw std::runtime_error("Could not initialize analysis plugin!"); } m_dev = osvr::pluginkit::DeviceToken(dev); /// Send JSON descriptor m_dev.sendJsonDescriptor(org_osvr_unifiedvideoinertial_json); /// Set up thread communication. setupBodyReporting(); /// Set up the object that will run in the other thread, and spawn the /// thread. startTrackerThread(); /// Register update callback m_dev.registerUpdateCallback(this); } ~UnifiedVideoInertialTracker() { stopTrackerThread(); } /// Create a "BodyReporting" interchange structure for each body we track. void setupBodyReporting() { m_bodyReportingVector.clear(); auto n = m_trackingSystem->getNumBodies(); for (size_type i = 0; i < n; ++i) { m_bodyReportingVector.emplace_back( osvr::vbtracker::BodyReporting::make()); } } OSVR_ReturnCode update(); void startTrackerThread() { if (m_trackerThreadFunctor) { throw std::logic_error("Trying to start the tracker thread when " "it's already started!"); } std::cout << "Starting the tracker thread..." << std::endl; m_trackerThreadFunctor.reset(new TrackerThread( *m_trackingSystem, *m_source, m_bodyReportingVector, osvr::vbtracker::getHDKCameraParameters())); m_trackerThread = std::thread([&] { (*m_trackerThreadFunctor)(); }); } void stopTrackerThread() { if (m_trackerThreadFunctor) { std::cout << "Shutting down the tracker thread..." << std::endl; m_trackerThreadFunctor->triggerStop(); m_trackerThread.join(); m_trackerThreadFunctor.reset(); m_trackerThread = std::thread(); } } private: osvr::pluginkit::DeviceToken m_dev; OSVR_ClientContext m_clientCtx; OSVR_ClientInterface m_clientInterface; OSVR_TrackerDeviceInterface m_tracker; #if 0 OSVR_AnalogDeviceInterface m_analog; #endif osvr::vbtracker::ImageSourcePtr m_source; cv::Mat m_frame; cv::Mat m_imageGray; TrackingSystemPtr m_trackingSystem; const double m_additionalPrediction; std::vector<osvr::vbtracker::BodyReportingPtr> m_bodyReportingVector; std::unique_ptr<TrackerThread> m_trackerThreadFunctor; std::thread m_trackerThread; }; inline OSVR_ReturnCode UnifiedVideoInertialTracker::update() { namespace ei = osvr::util::eigen_interop; std::size_t numSensors = m_bodyReportingVector.size(); for (std::size_t i = 0; i < numSensors; ++i) { auto report = m_bodyReportingVector[i]->getReport(m_additionalPrediction); if (!report) { /// couldn't get a report for this sensor for one reason or another. // std::cout << "Couldn't get report for " << i << std::endl; continue; } osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &report.pose, i, &report.timestamp); } return OSVR_RETURN_SUCCESS; } class ConfiguredDeviceConstructor { public: /// @brief This is the required signature for a device instantiation /// callback. OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) { // Read the JSON data from parameters. Json::Value root; if (params) { Json::Reader r; if (!r.parse(params, root)) { std::cerr << "Could not parse parameters!" << std::endl; } } // Read these parameters from a "params" field in the device Json // configuration file. // This is in a separate function/header for sharing and for clarity. auto config = osvr::vbtracker::parseConfigParams(root); #ifdef _WIN32 auto cam = osvr::vbtracker::openHDKCameraDirectShow(); #else // !_WIN32 /// @todo This is rather crude, as we can't select the exact camera we /// want, nor set the "50Hz" high-gain mode (and only works with HDK /// camera firmware v7 and up). Presumably eventually use libuvc on /// other platforms instead, at least for the HDK IR camera. auto cam = osvr::vbtracker::openOpenCVCamera(0); #endif if (!cam || !cam->ok()) { std::cerr << "Could not access the tracking camera, skipping " "video-based tracking!" << std::endl; return OSVR_RETURN_FAILURE; } auto trackingSystem = osvr::vbtracker::makeHDKTrackingSystem(config); // OK, now that we have our parameters, create the device. osvr::pluginkit::PluginContext context(ctx); auto newTracker = osvr::pluginkit::registerObjectForDeletion( ctx, new UnifiedVideoInertialTracker(ctx, std::move(cam), config, std::move(trackingSystem))); return OSVR_RETURN_SUCCESS; } }; } // namespace OSVR_PLUGIN(org_osvr_unifiedvideoinertial) { osvr::pluginkit::PluginContext context(ctx); /// Tell the core we're available to create a device object. osvr::pluginkit::registerDriverInstantiationCallback( ctx, DRIVER_NAME, new ConfiguredDeviceConstructor); return OSVR_RETURN_SUCCESS; } <commit_msg>Stub in the async<commit_after>/** @file @brief Main file for a unified video-based and inertial tracking system. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "ImageSources/ImageSource.h" #include "ImageSources/ImageSourceFactories.h" #include "MakeHDKTrackingSystem.h" #include "TrackingSystem.h" #include "ThreadsafeBodyReporting.h" #include "HDKLedIdentifierFactory.h" #include "CameraParameters.h" #include "HDKData.h" #include <osvr/AnalysisPluginKit/AnalysisPluginKitC.h> #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include <osvr/PluginKit/AnalogInterfaceC.h> #include <osvr/Util/EigenInterop.h> #include "ConfigurationParser.h" // Generated JSON header file #include "org_osvr_unifiedvideoinertial_json.h" // Library/third-party includes #include <opencv2/core/core.hpp> // for basic OpenCV types #include <opencv2/core/operations.hpp> #include <opencv2/highgui/highgui.hpp> // for image capture #include <opencv2/imgproc/imgproc.hpp> // for image scaling #include <json/value.h> #include <json/reader.h> #include <boost/noncopyable.hpp> #include <util/Stride.h> // Standard includes #include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <memory> #include <thread> #include <mutex> #include <stdexcept> #include <future> // Anonymous namespace to avoid symbol collision namespace { static const auto DRIVER_NAME = "UnifiedTrackingSystem"; static const auto DEBUGGABLE_BEACONS = 34; static const auto DATAPOINTS_PER_BEACON = 5; using TrackingSystemPtr = std::unique_ptr<osvr::vbtracker::TrackingSystem>; using BodyReportingVector = std::vector<osvr::vbtracker::BodyReportingPtr>; class TrackerThread : boost::noncopyable { public: TrackerThread(osvr::vbtracker::TrackingSystem &trackingSystem, osvr::vbtracker::ImageSource &imageSource, BodyReportingVector &reportingVec, osvr::vbtracker::CameraParameters const &camParams) : m_trackingSystem(trackingSystem), m_cam(imageSource), m_reportingVec(reportingVec), m_camParams(camParams) { msg() << "Tracker thread object created." << std::endl; } void operator()() { msg() << "Tracker thread object invoked." << std::endl; bool keepGoing = true; while (keepGoing) { doFrame(); { /// Copy the run flag. std::lock_guard<std::mutex> lock(m_runMutex); keepGoing = m_run; } if (!keepGoing) { msg() << "Tracker thread object: Just checked our run flag and " "noticed it turned false..." << std::endl; } } msg() << "Tracker thread object: functor exiting." << std::endl; } /// Call from the main thread! void triggerStop() { msg() << "Tracker thread object: triggerStop() called" << std::endl; std::lock_guard<std::mutex> lock(m_runMutex); m_run = false; } private: std::ostream &msg() const { return std::cout << "[UnifiedTracker] "; } std::ostream &warn() const { return msg() << "Warning: "; } void doFrame() { // Check camera status. if (!m_cam.ok()) { // Hmm, camera seems bad. Might regain it? Skip for now... warn() << "Camera is reporting it is not OK." << std::endl; return; } // Trigger a grab. if (!m_cam.grab()) { // Again failing without quitting, in hopes we get better luck next // time... warn() << "Camera grab failed." << std::endl; return; } // When we triggered the grab is our current best guess of the time for // the image /// @todo backdate to account for image transfer image, exposure time, /// etc. auto tv = osvr::util::time::getNow(); // Pull the image into an OpenCV matrix named m_frame. m_cam.retrieve(m_frame, m_frameGray); if (!m_frame.data || !m_frameGray.data) { warn() << "Camera retrieve appeared to fail: frames had null pointers!" << std::endl; return; } /// Launch an asynchronous task to perform the initial image processing. auto imageProcFuture = std::async( std::launch::async, [&]() -> osvr::vbtracker::ImageOutputDataPtr { return m_trackingSystem.performInitialImageProcessing( tv, m_frame, m_frameGray, m_camParams); }); /// @todo handle IMU reports in here /// By calling .get() on the std::future we block on the async we /// launched. // Submit to the tracking system. auto bodyIds = m_trackingSystem.updateBodiesFromVideoData(imageProcFuture.get()); for (auto const &bodyId : bodyIds) { auto &body = m_trackingSystem.getBody(bodyId); m_reportingVec[bodyId.value()]->updateState( body.getStateTime(), body.getState(), body.getProcessModel()); } } osvr::vbtracker::TrackingSystem &m_trackingSystem; osvr::vbtracker::ImageSource &m_cam; BodyReportingVector &m_reportingVec; osvr::vbtracker::CameraParameters m_camParams; cv::Mat m_frame; cv::Mat m_frameGray; std::mutex m_runMutex; bool m_run = true; }; class UnifiedVideoInertialTracker : boost::noncopyable { public: using size_type = std::size_t; UnifiedVideoInertialTracker(OSVR_PluginRegContext ctx, osvr::vbtracker::ImageSourcePtr &&source, osvr::vbtracker::ConfigParams params, TrackingSystemPtr &&trackingSystem) : m_source(std::move(source)), m_trackingSystem(std::move(trackingSystem)), m_additionalPrediction(params.additionalPrediction) { if (params.numThreads > 0) { // Set the number of threads for OpenCV to use. cv::setNumThreads(params.numThreads); } /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); // Configure the tracker interface. osvrDeviceTrackerConfigure(opts, &m_tracker); #if 0 osvrDeviceAnalogConfigure(opts, &m_analog, DEBUGGABLE_BEACONS * DATAPOINTS_PER_BEACON); #endif /// Create the analysis device token with the options OSVR_DeviceToken dev; if (OSVR_RETURN_FAILURE == osvrAnalysisSyncInit(ctx, DRIVER_NAME, opts, &dev, &m_clientCtx)) { throw std::runtime_error("Could not initialize analysis plugin!"); } m_dev = osvr::pluginkit::DeviceToken(dev); /// Send JSON descriptor m_dev.sendJsonDescriptor(org_osvr_unifiedvideoinertial_json); /// Set up thread communication. setupBodyReporting(); /// Set up the object that will run in the other thread, and spawn the /// thread. startTrackerThread(); /// Register update callback m_dev.registerUpdateCallback(this); } ~UnifiedVideoInertialTracker() { stopTrackerThread(); } /// Create a "BodyReporting" interchange structure for each body we track. void setupBodyReporting() { m_bodyReportingVector.clear(); auto n = m_trackingSystem->getNumBodies(); for (size_type i = 0; i < n; ++i) { m_bodyReportingVector.emplace_back( osvr::vbtracker::BodyReporting::make()); } } OSVR_ReturnCode update(); void startTrackerThread() { if (m_trackerThreadFunctor) { throw std::logic_error("Trying to start the tracker thread when " "it's already started!"); } std::cout << "Starting the tracker thread..." << std::endl; m_trackerThreadFunctor.reset(new TrackerThread( *m_trackingSystem, *m_source, m_bodyReportingVector, osvr::vbtracker::getHDKCameraParameters())); m_trackerThread = std::thread([&] { (*m_trackerThreadFunctor)(); }); } void stopTrackerThread() { if (m_trackerThreadFunctor) { std::cout << "Shutting down the tracker thread..." << std::endl; m_trackerThreadFunctor->triggerStop(); m_trackerThread.join(); m_trackerThreadFunctor.reset(); m_trackerThread = std::thread(); } } private: osvr::pluginkit::DeviceToken m_dev; OSVR_ClientContext m_clientCtx; OSVR_ClientInterface m_clientInterface; OSVR_TrackerDeviceInterface m_tracker; #if 0 OSVR_AnalogDeviceInterface m_analog; #endif osvr::vbtracker::ImageSourcePtr m_source; cv::Mat m_frame; cv::Mat m_imageGray; TrackingSystemPtr m_trackingSystem; const double m_additionalPrediction; std::vector<osvr::vbtracker::BodyReportingPtr> m_bodyReportingVector; std::unique_ptr<TrackerThread> m_trackerThreadFunctor; std::thread m_trackerThread; }; inline OSVR_ReturnCode UnifiedVideoInertialTracker::update() { namespace ei = osvr::util::eigen_interop; std::size_t numSensors = m_bodyReportingVector.size(); for (std::size_t i = 0; i < numSensors; ++i) { auto report = m_bodyReportingVector[i]->getReport(m_additionalPrediction); if (!report) { /// couldn't get a report for this sensor for one reason or another. // std::cout << "Couldn't get report for " << i << std::endl; continue; } osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &report.pose, i, &report.timestamp); } return OSVR_RETURN_SUCCESS; } class ConfiguredDeviceConstructor { public: /// @brief This is the required signature for a device instantiation /// callback. OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) { // Read the JSON data from parameters. Json::Value root; if (params) { Json::Reader r; if (!r.parse(params, root)) { std::cerr << "Could not parse parameters!" << std::endl; } } // Read these parameters from a "params" field in the device Json // configuration file. // This is in a separate function/header for sharing and for clarity. auto config = osvr::vbtracker::parseConfigParams(root); #ifdef _WIN32 auto cam = osvr::vbtracker::openHDKCameraDirectShow(); #else // !_WIN32 /// @todo This is rather crude, as we can't select the exact camera we /// want, nor set the "50Hz" high-gain mode (and only works with HDK /// camera firmware v7 and up). Presumably eventually use libuvc on /// other platforms instead, at least for the HDK IR camera. auto cam = osvr::vbtracker::openOpenCVCamera(0); #endif if (!cam || !cam->ok()) { std::cerr << "Could not access the tracking camera, skipping " "video-based tracking!" << std::endl; return OSVR_RETURN_FAILURE; } auto trackingSystem = osvr::vbtracker::makeHDKTrackingSystem(config); // OK, now that we have our parameters, create the device. osvr::pluginkit::PluginContext context(ctx); auto newTracker = osvr::pluginkit::registerObjectForDeletion( ctx, new UnifiedVideoInertialTracker(ctx, std::move(cam), config, std::move(trackingSystem))); return OSVR_RETURN_SUCCESS; } }; } // namespace OSVR_PLUGIN(org_osvr_unifiedvideoinertial) { osvr::pluginkit::PluginContext context(ctx); /// Tell the core we're available to create a device object. osvr::pluginkit::registerDriverInstantiationCallback( ctx, DRIVER_NAME, new ConfiguredDeviceConstructor); return OSVR_RETURN_SUCCESS; } <|endoftext|>
<commit_before>#include "commands.h" #include <chrono> #include <iostream> #include "BuildAction.h" #include "FileStates.h" using namespace aBuild; namespace commands { bool build(std::string const& rootProjectName, bool verbose, bool noconsole, int jobs) { std::vector<Project const*> rootProjects; Workspace ws("."); checkingMissingPackages(ws); //checkingNotNeededPackages(ws); checkingInvalidPackages(ws); checkingRequiredPackages(ws); Graph graph; auto allToolchains = getAllToolchains(ws); auto allFlavors = getAllFlavors(ws); Toolchain toolchain = allToolchains.rbegin()->second; std::string toolchainName = ws.accessConfigFile().getToolchain(); std::string lastFlavor = ws.accessConfigFile().getLastFlavor(); std::string buildMode = ws.accessConfigFile().getBuildMode(); if (allToolchains.find(toolchainName) != allToolchains.end()) { toolchain = allToolchains.at(toolchainName); } // check if flavor has toolchain if (allFlavors.find(lastFlavor) != allFlavors.end()) { auto flavor = allFlavors.at(lastFlavor); if (allToolchains.find(flavor.toolchain) != allToolchains.end()) { if (flavor.buildMode == "release" || flavor.buildMode == "debug") { buildMode = flavor.buildMode; toolchain = allToolchains.at(flavor.toolchain); } } } ws.accessConfigFile().setToolchain(toolchain.getName()); ws.accessConfigFile().setBuildMode(buildMode); ws.save(); auto timeSinceBegin = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()); std::cout << "Using buildMode: " << ws.accessConfigFile().getBuildMode() << std::endl; std::cout << "Using toolchain: " << ws.accessConfigFile().getToolchain() << std::endl; std::unique_ptr<BuildAction> action { new BuildAction(&graph, verbose, &ws.accessConfigFile(), toolchain) }; auto linkingLibFunc = action->getLinkingLibFunc(); auto linkingExecFunc = action->getLinkingExecFunc(); auto _compileFileCppFunc = action->getCompileCppFileFunc(); auto _compileFileCppFuncDep = action->getCompileCppFileFuncDep(); auto _compileFileCFunc = action->getCompileCFileFunc(); auto _compileFileCFuncDep = action->getCompileCFileFuncDep(); std::function<bool(std::string*)> compileFileCppFunc = [&] (std::string* p){ bool error = _compileFileCppFunc(p); _compileFileCppFuncDep(p); return error; }; std::function<bool(std::string*)> compileFileCFunc = [&] (std::string* p) { bool error = _compileFileCFunc(p); _compileFileCFuncDep(p); return error; }; auto excludedProjects = ws.getExcludedProjects(); auto requiredProjects = ws.getAllRequiredProjects(); auto packagesDir = utils::listDirs("packages", true); for (auto& p : packagesDir) { p = "packages/" + p; } packagesDir.push_back("."); std::vector<Project*> autoProjects; for (auto const& pDir : packagesDir) { if (not utils::fileExists(pDir + "/src")) continue; // Find auto projects auto projectDirs = utils::listDirs(pDir + "/src", true); for (auto const& d : projectDirs) { if (excludedProjects.count(d) != 0) continue; auto iter = requiredProjects.find(d); if (iter == requiredProjects.end()) { requiredProjects[d].set(d); requiredProjects[d].setPackagePath(pDir); requiredProjects[d].setAuto(true); } auto& project = requiredProjects.at(d); if (project.getIgnore()) continue; if (not project.getAuto()) continue; autoProjects.push_back(&project); } } for (auto p : autoProjects) { auto& project = *p; auto dep = project.getDefaultDependencies(&ws, requiredProjects); auto optDep = project.getDefaultOptionalDependencies(&ws, requiredProjects); for (auto d : optDep) { auto iter = std::find(dep.begin(), dep.end(), d); while (iter != dep.end()) { dep.erase(iter); iter = std::find(dep.begin(), dep.end(), d); } } project.setDependencies(std::move(dep)); project.setOptionalDependencies(std::move(optDep)); } // save all the auto detected dependencies ws.save(); // Create dependency tree auto projects = requiredProjects; for (auto& e : projects) { auto& project = e.second; if (project.getIgnore()) continue; if (excludedProjects.count(project.getName()) != 0) continue; if ((project.getName() == rootProjectName) || (rootProjectName == "" && excludedProjects.size() > 0)) { rootProjects.push_back(&project); } // Adding linking if (project.getType() == "library") { graph.addNode(&project, linkingLibFunc); } else if (project.getType() == "executable") { graph.addNode(&project, linkingExecFunc); if (rootProjectName == "" && excludedProjects.size() > 0) { rootProjects.push_back(&project); } } else { throw std::runtime_error("Project " + project.getName() + " has unknown type " + project.getType()); } // Adding compile files for (auto& f : project.getAllCppFiles()) { graph.addNode(&f, compileFileCppFunc); graph.addEdge(&f, &project); } // Adding compile files for (auto& f : project.getAllCFiles()) { graph.addNode(&f, compileFileCFunc); graph.addEdge(&f, &project); } // adding dependencies between projects for (auto const& dep : project.getDependencies()) { auto l = utils::explode(dep, "/"); if (l.size() != 2) { throw std::runtime_error("Project " + project.getName() + " has unknown dependency " + dep); } auto key = l[l.size() -1]; if (projects.find(key) == projects.end()) { throw std::runtime_error("Project " + project.getName() + " has unknown dependency " + dep); } graph.addEdge(&projects.at(key), &project); } // adding dependencies between optional projects for (auto const& dep : project.getOptionalDependencies()) { auto l = utils::explode(dep, "/"); if (l.size() != 2) { throw std::runtime_error("Project " + project.getName() + " has unknown dependency " + dep); } auto key = l[l.size() -1]; if (projects.find(key) != projects.end()) { if (excludedProjects.count(key) == 0) { graph.addEdge(&projects.at(key), &project); } } } } if (rootProjects.size() > 0) { std::cout << "Compiling project(s): "; for (auto p : rootProjects) { std::cout << p->getName() << ", "; } std::cout << std::endl; // Removing stuff that is not a dependency on rootProject graph.removeUnreachableIngoing(rootProjects); } bool success = graph.visitAllNodes(jobs, [=](int done, int total, int totaltotal) { if (not noconsole) { std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "working on job: " << done << "/" << total << "/" << totaltotal << std::flush; if (done == totaltotal) { std::cout << std::endl; } } else if (done == totaltotal) { std::cout << "working on job: "<< done << "/" << total << "/" << totaltotal << std::endl; } }); if (not success) { std::cout<<"Build failed"<<std::endl; return false; } else { std::cout<<"Build succeeded"<<std::endl; ws.accessConfigFile().setLastCompileTime(timeSinceBegin.count()); ws.save(); } return true; } } <commit_msg>Add color and build time<commit_after>#include "commands.h" #include <chrono> #include <iostream> #include "BuildAction.h" #include "FileStates.h" using namespace aBuild; namespace commands { bool build(std::string const& rootProjectName, bool verbose, bool noconsole, int jobs) { std::vector<Project const*> rootProjects; Workspace ws("."); checkingMissingPackages(ws); //checkingNotNeededPackages(ws); checkingInvalidPackages(ws); checkingRequiredPackages(ws); Graph graph; auto allToolchains = getAllToolchains(ws); auto allFlavors = getAllFlavors(ws); Toolchain toolchain = allToolchains.rbegin()->second; std::string toolchainName = ws.accessConfigFile().getToolchain(); std::string lastFlavor = ws.accessConfigFile().getLastFlavor(); std::string buildMode = ws.accessConfigFile().getBuildMode(); std::chrono::high_resolution_clock::time_point startTime = std::chrono::high_resolution_clock::now(); if (allToolchains.find(toolchainName) != allToolchains.end()) { toolchain = allToolchains.at(toolchainName); } // check if flavor has toolchain if (allFlavors.find(lastFlavor) != allFlavors.end()) { auto flavor = allFlavors.at(lastFlavor); if (allToolchains.find(flavor.toolchain) != allToolchains.end()) { if (flavor.buildMode == "release" || flavor.buildMode == "debug") { buildMode = flavor.buildMode; toolchain = allToolchains.at(flavor.toolchain); } } } ws.accessConfigFile().setToolchain(toolchain.getName()); ws.accessConfigFile().setBuildMode(buildMode); ws.save(); auto timeSinceBegin = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()); std::cout << "Using buildMode: " << ws.accessConfigFile().getBuildMode() << std::endl; std::cout << "Using toolchain: " << ws.accessConfigFile().getToolchain() << std::endl; std::unique_ptr<BuildAction> action { new BuildAction(&graph, verbose, &ws.accessConfigFile(), toolchain) }; auto linkingLibFunc = action->getLinkingLibFunc(); auto linkingExecFunc = action->getLinkingExecFunc(); auto _compileFileCppFunc = action->getCompileCppFileFunc(); auto _compileFileCppFuncDep = action->getCompileCppFileFuncDep(); auto _compileFileCFunc = action->getCompileCFileFunc(); auto _compileFileCFuncDep = action->getCompileCFileFuncDep(); std::function<bool(std::string*)> compileFileCppFunc = [&] (std::string* p){ bool error = _compileFileCppFunc(p); _compileFileCppFuncDep(p); return error; }; std::function<bool(std::string*)> compileFileCFunc = [&] (std::string* p) { bool error = _compileFileCFunc(p); _compileFileCFuncDep(p); return error; }; auto excludedProjects = ws.getExcludedProjects(); auto requiredProjects = ws.getAllRequiredProjects(); auto packagesDir = utils::listDirs("packages", true); for (auto& p : packagesDir) { p = "packages/" + p; } packagesDir.push_back("."); std::vector<Project*> autoProjects; for (auto const& pDir : packagesDir) { if (not utils::fileExists(pDir + "/src")) continue; // Find auto projects auto projectDirs = utils::listDirs(pDir + "/src", true); for (auto const& d : projectDirs) { if (excludedProjects.count(d) != 0) continue; auto iter = requiredProjects.find(d); if (iter == requiredProjects.end()) { requiredProjects[d].set(d); requiredProjects[d].setPackagePath(pDir); requiredProjects[d].setAuto(true); } auto& project = requiredProjects.at(d); if (project.getIgnore()) continue; if (not project.getAuto()) continue; autoProjects.push_back(&project); } } for (auto p : autoProjects) { auto& project = *p; auto dep = project.getDefaultDependencies(&ws, requiredProjects); auto optDep = project.getDefaultOptionalDependencies(&ws, requiredProjects); for (auto d : optDep) { auto iter = std::find(dep.begin(), dep.end(), d); while (iter != dep.end()) { dep.erase(iter); iter = std::find(dep.begin(), dep.end(), d); } } project.setDependencies(std::move(dep)); project.setOptionalDependencies(std::move(optDep)); } // save all the auto detected dependencies ws.save(); // Create dependency tree auto projects = requiredProjects; for (auto& e : projects) { auto& project = e.second; if (project.getIgnore()) continue; if (excludedProjects.count(project.getName()) != 0) continue; if ((project.getName() == rootProjectName) || (rootProjectName == "" && excludedProjects.size() > 0)) { rootProjects.push_back(&project); } // Adding linking if (project.getType() == "library") { graph.addNode(&project, linkingLibFunc); } else if (project.getType() == "executable") { graph.addNode(&project, linkingExecFunc); if (rootProjectName == "" && excludedProjects.size() > 0) { rootProjects.push_back(&project); } } else { throw std::runtime_error("Project " + project.getName() + " has unknown type " + project.getType()); } // Adding compile files for (auto& f : project.getAllCppFiles()) { graph.addNode(&f, compileFileCppFunc); graph.addEdge(&f, &project); } // Adding compile files for (auto& f : project.getAllCFiles()) { graph.addNode(&f, compileFileCFunc); graph.addEdge(&f, &project); } // adding dependencies between projects for (auto const& dep : project.getDependencies()) { auto l = utils::explode(dep, "/"); if (l.size() != 2) { throw std::runtime_error("Project " + project.getName() + " has unknown dependency " + dep); } auto key = l[l.size() -1]; if (projects.find(key) == projects.end()) { throw std::runtime_error("Project " + project.getName() + " has unknown dependency " + dep); } graph.addEdge(&projects.at(key), &project); } // adding dependencies between optional projects for (auto const& dep : project.getOptionalDependencies()) { auto l = utils::explode(dep, "/"); if (l.size() != 2) { throw std::runtime_error("Project " + project.getName() + " has unknown dependency " + dep); } auto key = l[l.size() -1]; if (projects.find(key) != projects.end()) { if (excludedProjects.count(key) == 0) { graph.addEdge(&projects.at(key), &project); } } } } if (rootProjects.size() > 0) { std::cout << "Compiling project(s): "; for (auto p : rootProjects) { std::cout << p->getName() << ", "; } std::cout << std::endl; // Removing stuff that is not a dependency on rootProject graph.removeUnreachableIngoing(rootProjects); } bool success = graph.visitAllNodes(jobs, [=](int done, int total, int totaltotal) { if (not noconsole) { std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "working on job: " << done << "/" << total << "/" << totaltotal << std::flush; if (done == totaltotal) { std::cout << std::endl; } } else if (done == totaltotal) { std::cout << "working on job: "<< done << "/" << total << "/" << totaltotal << std::endl; } }); std::chrono::high_resolution_clock::time_point endTime = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(endTime - startTime); if (not success) { std::cout<<std::endl<<"Build \033[31mfailed\033[0m"; std::cout<< " after " << time_span.count() << " seconds." << std::endl; return false; } else { std::cout<<std::endl<<"Build \033[32msucceeded\033[0m"; std::cout << " after " << time_span.count() << " seconds." << std::endl; ws.accessConfigFile().setLastCompileTime(timeSinceBegin.count()); ws.save(); } return true; } } <|endoftext|>
<commit_before>#include "list.h" #include "gtest/gtest.h" #include <string> class listTest : public testing::Test { protected: virtual void SetUp() { list_1.insert(list_1.begin(), 10); int_iter = list_1.insert(list_1.end(), 30); int_iter = list_1.insert(int_iter, 20); str = "a string"; } virtual void TearDown() {} // class constant // setup fixtures ::list<int> list_1; ::list<int> list_2; list<int> list_empty; ::list<std::string> list_str; list<int>::iterator int_iter; list<std::string>::iterator str_iter; std::string str; }; class listIteratorTest : public testing::Test { // try to make friend with list_const_iterator DOES NOT WORK here // because friendship must be made before template is resolved: // friend class list_const_iterator<int>; protected: virtual void SetUp() { head_ = new listNode<int> (0); head_->next_ = new listNode<int> (10); tail_ = head_->next_->next_ = new listNode<int> (20); head_->next_->prev_ = head_; tail_->prev_ = head_->next_; c_iter = list_const_iterator<int> (head_); c_iter_1 = list_const_iterator<int> (head_->next_); iter = list_iterator<int> (head_); iter_1 = list_iterator<int> (head_->next_); } virtual void TearDown() { delete tail_; delete head_->next_; delete head_; } listNode<int>* head_; listNode<int>* tail_; list_const_iterator<int> c_iter; list_const_iterator<int> c_iter_1; list_iterator<int> iter; list_iterator<int> iter_1; }; // test the helper class listNodeTest // this is a canonical example of writing testable code: // to test private members, just write another helper class // and make its data public TEST(listHelperTest, ListNode) { int element_1 = 100; std::string element_2("Hello world"); listNode<int> node_1(element_1); listNode<std::string> node_2(element_2); EXPECT_EQ(element_1, node_1.element_); EXPECT_EQ(element_2, node_2.element_); EXPECT_EQ(nullptr, node_2.prev_); EXPECT_EQ(nullptr, node_2.next_); // test the move constructor for node: listNode<int> node_3(std::move(element_1)); listNode<std::string> node_4(std::move(element_2)); EXPECT_EQ(100, node_3.element_); EXPECT_EQ("Hello world", node_4.element_); EXPECT_TRUE(element_2.empty()); } TEST_F(listIteratorTest, ConstIterator) { list_const_iterator<int> c_iter_temp = c_iter; // testing increment and decrement of const_iterator EXPECT_EQ(++c_iter_temp, c_iter_1); EXPECT_EQ(--c_iter_temp, c_iter); EXPECT_EQ(c_iter_temp++, c_iter); EXPECT_EQ(c_iter_temp, c_iter_1); EXPECT_EQ(c_iter_temp--, c_iter_1); EXPECT_EQ(c_iter_temp, c_iter); EXPECT_TRUE(c_iter_temp == c_iter); EXPECT_TRUE(c_iter_temp != c_iter_1); // testing access capability of const_iterator EXPECT_EQ(0, *c_iter_temp); EXPECT_EQ(10, *(++c_iter_temp)); EXPECT_EQ(20, *(++c_iter_temp)); EXPECT_EQ(10, *(--c_iter_temp)); // testing non-modifying capability of const_iterator: // will not even compile: //*c_iter_temp = 100; } TEST_F(listIteratorTest, Iterator) { list_iterator<int> iter_temp = iter; // testing increment and decrement of iterator // which are all inherited from base EXPECT_EQ(++iter_temp, iter_1); EXPECT_EQ(--iter_temp, iter); EXPECT_EQ(iter_temp++, iter); EXPECT_EQ(iter_temp, iter_1); EXPECT_EQ(iter_temp--, iter_1); EXPECT_EQ(iter_temp, iter); EXPECT_TRUE(iter_temp == iter); EXPECT_TRUE(iter_temp != iter_1); // testing access capability of iterator EXPECT_EQ(0, *iter_temp); EXPECT_EQ(10, *(++iter_temp)); EXPECT_EQ(20, *(++iter_temp)); EXPECT_EQ(10, *(--iter_temp)); // testing modifying capability of iterator: *iter_temp = 100; EXPECT_EQ(*iter_temp, 100); } TEST_F(listTest, DefaultCtor) { EXPECT_EQ(0u, list_empty.size()); EXPECT_TRUE(list_empty.empty()); } TEST_F(listTest, CopyCtor) { for (int i = 0; i < 100; i++) { list_1.push_back(i); } const list<int> list_temp = list_1; EXPECT_EQ(list_temp.size(), list_1.size()); int_iter = list_1.begin(); list<int>::const_iterator temp_iter = list_temp.begin(); while(temp_iter != list_temp.end() && int_iter != list_1.end()) { EXPECT_EQ(*temp_iter++, *int_iter++); } // edge case: empty list list<int> list_nothing = list_empty; EXPECT_TRUE(list_nothing.empty()); } TEST_F(listTest, BeginEnd) { EXPECT_EQ(list_empty.begin(), list_empty.end()); // decrement pass begin() and increment pass end() should be ok EXPECT_NO_FATAL_FAILURE(--list_empty.begin()); EXPECT_NO_FATAL_FAILURE(++list_empty.end()); } TEST_F(listTest, InsertLvalue) { // iter is pointing to tail_ list<int>::iterator iter = list_empty.begin(); // testing iterator insert (iterator, const E&) int x = 10; list<int>::iterator ret_iter = list_empty.insert(iter, x); EXPECT_TRUE(--iter == ret_iter); // iter--; EXPECT_EQ(*ret_iter, 10); EXPECT_EQ(list_empty.size(), 1); EXPECT_EQ(++ret_iter, list_empty.end()); --ret_iter; // set ret_iter to point to 10 ret_iter = list_empty.insert(ret_iter, x + 10); EXPECT_EQ(list_empty.size(), 2); EXPECT_EQ(*ret_iter, 20); EXPECT_EQ(*(++ret_iter), 10); EXPECT_TRUE(++ret_iter == list_empty.end()); // insert pass begin() and pass end() should fail // the following would not even compile: // list_empty.insert(++list_empty.end(), 100); // list_empty.insert(--list_empty.begin(), 100); } TEST_F(listTest, InsertRvalue) { size_t old_size = list_str.size(); str_iter = list_str.insert(list_str.begin(), std::move(str)); EXPECT_EQ(*str_iter, "a string"); EXPECT_TRUE(str_iter == list_str.begin()); EXPECT_EQ(++old_size, list_str.size()); EXPECT_TRUE(str.empty()); } TEST_F(listTest, InsertConstObject) { // insert const object by lvalue: const std::string const_str("const string"); const std::string CONST_STR(const_str); size_t old_size = list_str.size(); str_iter = list_str.insert(list_str.begin(), const_str); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*str_iter, CONST_STR); EXPECT_EQ(const_str, CONST_STR); // insert const objects by rvalue: // std::move automatically degrade to a copy insert str_iter = list_str.insert(list_str.begin(), std::move(const_str)); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*str_iter, CONST_STR); EXPECT_EQ(const_str, CONST_STR); } TEST_F(listTest, EraseAtIter) { int_iter = list_1.erase(list_1.begin()); // erase 10 EXPECT_EQ(list_1.size(), 2); EXPECT_EQ(*list_1.begin(), 20); EXPECT_EQ(*int_iter, 20); int_iter = list_1.erase(int_iter); // erase 20 int_iter = list_1.erase(int_iter); // erase 30 // test for seg fault if erase end() // it trigers a memory leak error right before core dump, // which it is expected. Turned off when running memtest //EXPECT_DEATH(int_iter = list_1.erase(list_1.end()), ""); } TEST_F(listTest, PushFront) { // lvalue version size_t old_size = list_1.size(); list_1.push_front(100); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*list_1.begin(), 100); list_1.push_front(200); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*list_1.begin(), 200); EXPECT_EQ(*(++list_1.begin()), 100); EXPECT_TRUE(--(++list_1.begin()) == list_1.begin()); // rvalue version old_size = list_str.size(); list_str.push_front(std::move(str)); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*list_str.begin(), "a string"); EXPECT_TRUE(str.empty()); } TEST_F(listTest, PushBack) { // lvalue version size_t old_size = list_1.size(); list_1.push_back(1000); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*(--list_1.end()), 1000); list_1.push_back(2000); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*(--list_1.end()), 2000); EXPECT_EQ(*(--(--list_1.end())), 1000); EXPECT_TRUE(++(--list_1.end()) == list_1.end()); // rvalue version old_size = list_str.size(); list_str.push_back(std::move(str)); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*(--list_str.end()), "a string"); EXPECT_TRUE(str.empty()); } <commit_msg>list: add tests for assignment operator<commit_after>#include "list.h" #include "gtest/gtest.h" #include <string> class listTest : public testing::Test { protected: virtual void SetUp() { list_1.insert(list_1.begin(), 10); int_iter = list_1.insert(list_1.end(), 30); int_iter = list_1.insert(int_iter, 20); str = "a string"; } virtual void TearDown() {} // class constant // setup fixtures ::list<int> list_1; ::list<int> list_2; list<int> list_empty; ::list<std::string> list_str; list<int>::iterator int_iter; list<std::string>::iterator str_iter; std::string str; }; class listIteratorTest : public testing::Test { // try to make friend with list_const_iterator DOES NOT WORK here // because friendship must be made before template is resolved: // friend class list_const_iterator<int>; protected: virtual void SetUp() { head_ = new listNode<int> (0); head_->next_ = new listNode<int> (10); tail_ = head_->next_->next_ = new listNode<int> (20); head_->next_->prev_ = head_; tail_->prev_ = head_->next_; c_iter = list_const_iterator<int> (head_); c_iter_1 = list_const_iterator<int> (head_->next_); iter = list_iterator<int> (head_); iter_1 = list_iterator<int> (head_->next_); } virtual void TearDown() { delete tail_; delete head_->next_; delete head_; } listNode<int>* head_; listNode<int>* tail_; list_const_iterator<int> c_iter; list_const_iterator<int> c_iter_1; list_iterator<int> iter; list_iterator<int> iter_1; }; // test the helper class listNodeTest // this is a canonical example of writing testable code: // to test private members, just write another helper class // and make its data public TEST(listHelperTest, ListNode) { int element_1 = 100; std::string element_2("Hello world"); listNode<int> node_1(element_1); listNode<std::string> node_2(element_2); EXPECT_EQ(element_1, node_1.element_); EXPECT_EQ(element_2, node_2.element_); EXPECT_EQ(nullptr, node_2.prev_); EXPECT_EQ(nullptr, node_2.next_); // test the move constructor for node: listNode<int> node_3(std::move(element_1)); listNode<std::string> node_4(std::move(element_2)); EXPECT_EQ(100, node_3.element_); EXPECT_EQ("Hello world", node_4.element_); EXPECT_TRUE(element_2.empty()); } TEST_F(listIteratorTest, ConstIterator) { list_const_iterator<int> c_iter_temp = c_iter; // testing increment and decrement of const_iterator EXPECT_EQ(++c_iter_temp, c_iter_1); EXPECT_EQ(--c_iter_temp, c_iter); EXPECT_EQ(c_iter_temp++, c_iter); EXPECT_EQ(c_iter_temp, c_iter_1); EXPECT_EQ(c_iter_temp--, c_iter_1); EXPECT_EQ(c_iter_temp, c_iter); EXPECT_TRUE(c_iter_temp == c_iter); EXPECT_TRUE(c_iter_temp != c_iter_1); // testing access capability of const_iterator EXPECT_EQ(0, *c_iter_temp); EXPECT_EQ(10, *(++c_iter_temp)); EXPECT_EQ(20, *(++c_iter_temp)); EXPECT_EQ(10, *(--c_iter_temp)); // testing non-modifying capability of const_iterator: // will not even compile: //*c_iter_temp = 100; } TEST_F(listIteratorTest, Iterator) { list_iterator<int> iter_temp = iter; // testing increment and decrement of iterator // which are all inherited from base EXPECT_EQ(++iter_temp, iter_1); EXPECT_EQ(--iter_temp, iter); EXPECT_EQ(iter_temp++, iter); EXPECT_EQ(iter_temp, iter_1); EXPECT_EQ(iter_temp--, iter_1); EXPECT_EQ(iter_temp, iter); EXPECT_TRUE(iter_temp == iter); EXPECT_TRUE(iter_temp != iter_1); // testing access capability of iterator EXPECT_EQ(0, *iter_temp); EXPECT_EQ(10, *(++iter_temp)); EXPECT_EQ(20, *(++iter_temp)); EXPECT_EQ(10, *(--iter_temp)); // testing modifying capability of iterator: *iter_temp = 100; EXPECT_EQ(*iter_temp, 100); } TEST_F(listTest, DefaultCtor) { EXPECT_EQ(0u, list_empty.size()); EXPECT_TRUE(list_empty.empty()); } TEST_F(listTest, CopyCtor) { for (int i = 0; i < 100; i++) { list_1.push_back(i); } const list<int> list_temp = list_1; EXPECT_EQ(list_temp.size(), list_1.size()); int_iter = list_1.begin(); list<int>::const_iterator temp_iter = list_temp.begin(); while(temp_iter != list_temp.end() && int_iter != list_1.end()) { EXPECT_EQ(*temp_iter++, *int_iter++); } // edge case: empty list list<int> list_nothing = list_empty; EXPECT_TRUE(list_nothing.empty()); } TEST_F(listTest, AssigmentOperator) { for (int i = 0; i < 100; i++) { list_1.push_back(i); } list_2 = list_1; EXPECT_EQ(list_2.size(), list_1.size()); int_iter = list_1.begin(); list<int>::const_iterator temp_iter = list_2.begin(); while(temp_iter != list_2.end() && int_iter != list_1.end()) { EXPECT_EQ(*temp_iter++, *int_iter++); } // edge case: empty list list_1 = list_empty; EXPECT_TRUE(list_1.empty()); // edge case: self-assign const list<int> old_list_2 = list_2; list_2 = list_2; // make sure list_2 is not emptied EXPECT_EQ(list_2.size(), old_list_2.size()); // TODO: compare list_2 and old_list_2 elementwise } TEST_F(listTest, BeginEnd) { EXPECT_EQ(list_empty.begin(), list_empty.end()); // decrement pass begin() and increment pass end() should be ok EXPECT_NO_FATAL_FAILURE(--list_empty.begin()); EXPECT_NO_FATAL_FAILURE(++list_empty.end()); } TEST_F(listTest, InsertLvalue) { // iter is pointing to tail_ list<int>::iterator iter = list_empty.begin(); // testing iterator insert (iterator, const E&) int x = 10; list<int>::iterator ret_iter = list_empty.insert(iter, x); EXPECT_TRUE(--iter == ret_iter); // iter--; EXPECT_EQ(*ret_iter, 10); EXPECT_EQ(list_empty.size(), 1); EXPECT_EQ(++ret_iter, list_empty.end()); --ret_iter; // set ret_iter to point to 10 ret_iter = list_empty.insert(ret_iter, x + 10); EXPECT_EQ(list_empty.size(), 2); EXPECT_EQ(*ret_iter, 20); EXPECT_EQ(*(++ret_iter), 10); EXPECT_TRUE(++ret_iter == list_empty.end()); // insert pass begin() and pass end() should fail // the following would not even compile: // list_empty.insert(++list_empty.end(), 100); // list_empty.insert(--list_empty.begin(), 100); } TEST_F(listTest, InsertRvalue) { size_t old_size = list_str.size(); str_iter = list_str.insert(list_str.begin(), std::move(str)); EXPECT_EQ(*str_iter, "a string"); EXPECT_TRUE(str_iter == list_str.begin()); EXPECT_EQ(++old_size, list_str.size()); EXPECT_TRUE(str.empty()); } TEST_F(listTest, InsertConstObject) { // insert const object by lvalue: const std::string const_str("const string"); const std::string CONST_STR(const_str); size_t old_size = list_str.size(); str_iter = list_str.insert(list_str.begin(), const_str); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*str_iter, CONST_STR); EXPECT_EQ(const_str, CONST_STR); // insert const objects by rvalue: // std::move automatically degrade to a copy insert str_iter = list_str.insert(list_str.begin(), std::move(const_str)); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*str_iter, CONST_STR); EXPECT_EQ(const_str, CONST_STR); } TEST_F(listTest, EraseAtIter) { int_iter = list_1.erase(list_1.begin()); // erase 10 EXPECT_EQ(list_1.size(), 2); EXPECT_EQ(*list_1.begin(), 20); EXPECT_EQ(*int_iter, 20); int_iter = list_1.erase(int_iter); // erase 20 int_iter = list_1.erase(int_iter); // erase 30 // test for seg fault if erase end() // it trigers a memory leak error right before core dump, // which it is expected. Turned off when running memtest //EXPECT_DEATH(int_iter = list_1.erase(list_1.end()), ""); } TEST_F(listTest, PushFront) { // lvalue version size_t old_size = list_1.size(); list_1.push_front(100); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*list_1.begin(), 100); list_1.push_front(200); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*list_1.begin(), 200); EXPECT_EQ(*(++list_1.begin()), 100); EXPECT_TRUE(--(++list_1.begin()) == list_1.begin()); // rvalue version old_size = list_str.size(); list_str.push_front(std::move(str)); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*list_str.begin(), "a string"); EXPECT_TRUE(str.empty()); } TEST_F(listTest, PushBack) { // lvalue version size_t old_size = list_1.size(); list_1.push_back(1000); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*(--list_1.end()), 1000); list_1.push_back(2000); EXPECT_EQ(++old_size, list_1.size()); EXPECT_EQ(*(--list_1.end()), 2000); EXPECT_EQ(*(--(--list_1.end())), 1000); EXPECT_TRUE(++(--list_1.end()) == list_1.end()); // rvalue version old_size = list_str.size(); list_str.push_back(std::move(str)); EXPECT_EQ(++old_size, list_str.size()); EXPECT_EQ(*(--list_str.end()), "a string"); EXPECT_TRUE(str.empty()); } <|endoftext|>
<commit_before>#ifndef LIGHTGBM_PREDICTOR_HPP_ #define LIGHTGBM_PREDICTOR_HPP_ #include <LightGBM/meta.h> #include <LightGBM/boosting.h> #include <LightGBM/utils/text_reader.h> #include <LightGBM/dataset.h> #include <LightGBM/utils/openmp_wrapper.h> #include <cstring> #include <cstdio> #include <vector> #include <utility> #include <functional> #include <string> #include <memory> namespace LightGBM { /*! * \brief Used to predict data with input model */ class Predictor { public: /*! * \brief Constructor * \param boosting Input boosting model * \param num_iteration Number of boosting round * \param is_raw_score True if need to predict result with raw score * \param is_predict_leaf_index True if output leaf index instead of prediction score */ Predictor(Boosting* boosting, int num_iteration, bool is_raw_score, bool is_predict_leaf_index, bool early_stop, int early_stop_freq, double early_stop_margin) { early_stop_ = CreatePredictionEarlyStopInstance("none", LightGBM::PredictionEarlyStopConfig()); if (early_stop && !boosting->NeedAccuratePrediction()) { PredictionEarlyStopConfig pred_early_stop_config; pred_early_stop_config.margin_threshold = early_stop_margin; pred_early_stop_config.round_period = early_stop_freq; if (boosting->NumberOfClasses() == 1) { early_stop_ = CreatePredictionEarlyStopInstance("binary", pred_early_stop_config); } else { early_stop_ = CreatePredictionEarlyStopInstance("multiclass", pred_early_stop_config); } } #pragma omp parallel #pragma omp master { num_threads_ = omp_get_num_threads(); } boosting->InitPredict(num_iteration); boosting_ = boosting; num_pred_one_row_ = boosting_->NumPredictOneRow(num_iteration, is_predict_leaf_index); num_feature_ = boosting_->MaxFeatureIdx() + 1; predict_buf_ = std::vector<std::vector<double>>(num_threads_, std::vector<double>(num_feature_, 0.0f)); if (is_predict_leaf_index) { predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) { int tid = omp_get_thread_num(); CopyToPredictBuffer(predict_buf_[tid].data(), features); // get result for leaf index boosting_->PredictLeafIndex(predict_buf_[tid].data(), output); ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features); }; } else { if (is_raw_score) { predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) { int tid = omp_get_thread_num(); CopyToPredictBuffer(predict_buf_[tid].data(), features); boosting_->PredictRaw(predict_buf_[tid].data(), output, &early_stop_); ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features); }; } else { predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) { int tid = omp_get_thread_num(); CopyToPredictBuffer(predict_buf_[tid].data(), features); boosting_->Predict(predict_buf_[tid].data(), output, &early_stop_); ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features); }; } } } /*! * \brief Destructor */ ~Predictor() { } inline const PredictFunction& GetPredictFunction() const { return predict_fun_; } /*! * \brief predicting on data, then saving result to disk * \param data_filename Filename of data * \param result_filename Filename of output result */ void Predict(const char* data_filename, const char* result_filename, bool has_header) { FILE* result_file; #ifdef _MSC_VER fopen_s(&result_file, result_filename, "w"); #else result_file = fopen(result_filename, "w"); #endif if (result_file == NULL) { Log::Fatal("Prediction results file %s doesn't exist", data_filename); } auto parser = std::unique_ptr<Parser>(Parser::CreateParser(data_filename, has_header, boosting_->MaxFeatureIdx() + 1, boosting_->LabelIdx())); if (parser == nullptr) { Log::Fatal("Could not recognize the data format of data file %s", data_filename); } // function for parse data std::function<void(const char*, std::vector<std::pair<int, double>>*)> parser_fun; double tmp_label; parser_fun = [this, &parser, &tmp_label] (const char* buffer, std::vector<std::pair<int, double>>* feature) { parser->ParseOneLine(buffer, feature, &tmp_label); }; std::function<void(data_size_t, const std::vector<std::string>&)> process_fun = [this, &parser_fun, &result_file] (data_size_t, const std::vector<std::string>& lines) { std::vector<std::pair<int, double>> oneline_features; std::vector<std::string> result_to_write(lines.size()); OMP_INIT_EX(); #pragma omp parallel for schedule(static) firstprivate(oneline_features) for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) { OMP_LOOP_EX_BEGIN(); oneline_features.clear(); // parser parser_fun(lines[i].c_str(), &oneline_features); // predict std::vector<double> result(num_pred_one_row_); predict_fun_(oneline_features, result.data()); auto str_result = Common::Join<double>(result, "\t"); result_to_write[i] = str_result; OMP_LOOP_EX_END(); } OMP_THROW_EX(); for (data_size_t i = 0; i < static_cast<data_size_t>(result_to_write.size()); ++i) { fprintf(result_file, "%s\n", result_to_write[i].c_str()); } }; TextReader<data_size_t> predict_data_reader(data_filename, has_header); predict_data_reader.ReadAllAndProcessParallel(process_fun); fclose(result_file); } private: void CopyToPredictBuffer(double* pred_buf, const std::vector<std::pair<int, double>>& features) { int loop_size = static_cast<int>(features.size()); for (int i = 0; i < loop_size; ++i) { if (features[i].first < num_feature_) { pred_buf[features[i].first] = features[i].second; } } } void ClearPredictBuffer(double* pred_buf, size_t buf_size, const std::vector<std::pair<int, double>>& features) { if (features.size() < static_cast<size_t>(buf_size / 2)) { std::memset(pred_buf, 0, sizeof(double)*(buf_size)); } else { int loop_size = static_cast<int>(features.size()); for (int i = 0; i < loop_size; ++i) { pred_buf[features[i].first] = 0.0f; } } } /*! \brief Boosting model */ const Boosting* boosting_; /*! \brief function for prediction */ PredictFunction predict_fun_; PredictionEarlyStopInstance early_stop_; int num_feature_; int num_pred_one_row_; int num_threads_; std::vector<std::vector<double>> predict_buf_; }; } // namespace LightGBM #endif // LightGBM_PREDICTOR_HPP_ <commit_msg>fix #596<commit_after>#ifndef LIGHTGBM_PREDICTOR_HPP_ #define LIGHTGBM_PREDICTOR_HPP_ #include <LightGBM/meta.h> #include <LightGBM/boosting.h> #include <LightGBM/utils/text_reader.h> #include <LightGBM/dataset.h> #include <LightGBM/utils/openmp_wrapper.h> #include <cstring> #include <cstdio> #include <vector> #include <utility> #include <functional> #include <string> #include <memory> namespace LightGBM { /*! * \brief Used to predict data with input model */ class Predictor { public: /*! * \brief Constructor * \param boosting Input boosting model * \param num_iteration Number of boosting round * \param is_raw_score True if need to predict result with raw score * \param is_predict_leaf_index True if output leaf index instead of prediction score */ Predictor(Boosting* boosting, int num_iteration, bool is_raw_score, bool is_predict_leaf_index, bool early_stop, int early_stop_freq, double early_stop_margin) { early_stop_ = CreatePredictionEarlyStopInstance("none", LightGBM::PredictionEarlyStopConfig()); if (early_stop && !boosting->NeedAccuratePrediction()) { PredictionEarlyStopConfig pred_early_stop_config; pred_early_stop_config.margin_threshold = early_stop_margin; pred_early_stop_config.round_period = early_stop_freq; if (boosting->NumberOfClasses() == 1) { early_stop_ = CreatePredictionEarlyStopInstance("binary", pred_early_stop_config); } else { early_stop_ = CreatePredictionEarlyStopInstance("multiclass", pred_early_stop_config); } } #pragma omp parallel #pragma omp master { num_threads_ = omp_get_num_threads(); } boosting->InitPredict(num_iteration); boosting_ = boosting; num_pred_one_row_ = boosting_->NumPredictOneRow(num_iteration, is_predict_leaf_index); num_feature_ = boosting_->MaxFeatureIdx() + 1; predict_buf_ = std::vector<std::vector<double>>(num_threads_, std::vector<double>(num_feature_, 0.0f)); if (is_predict_leaf_index) { predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) { int tid = omp_get_thread_num(); CopyToPredictBuffer(predict_buf_[tid].data(), features); // get result for leaf index boosting_->PredictLeafIndex(predict_buf_[tid].data(), output); ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features); }; } else { if (is_raw_score) { predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) { int tid = omp_get_thread_num(); CopyToPredictBuffer(predict_buf_[tid].data(), features); boosting_->PredictRaw(predict_buf_[tid].data(), output, &early_stop_); ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features); }; } else { predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) { int tid = omp_get_thread_num(); CopyToPredictBuffer(predict_buf_[tid].data(), features); boosting_->Predict(predict_buf_[tid].data(), output, &early_stop_); ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features); }; } } } /*! * \brief Destructor */ ~Predictor() { } inline const PredictFunction& GetPredictFunction() const { return predict_fun_; } /*! * \brief predicting on data, then saving result to disk * \param data_filename Filename of data * \param result_filename Filename of output result */ void Predict(const char* data_filename, const char* result_filename, bool has_header) { FILE* result_file; #ifdef _MSC_VER fopen_s(&result_file, result_filename, "w"); #else result_file = fopen(result_filename, "w"); #endif if (result_file == NULL) { Log::Fatal("Prediction results file %s doesn't exist", data_filename); } auto parser = std::unique_ptr<Parser>(Parser::CreateParser(data_filename, has_header, boosting_->MaxFeatureIdx() + 1, boosting_->LabelIdx())); if (parser == nullptr) { Log::Fatal("Could not recognize the data format of data file %s", data_filename); } // function for parse data std::function<void(const char*, std::vector<std::pair<int, double>>*)> parser_fun; double tmp_label; parser_fun = [this, &parser, &tmp_label] (const char* buffer, std::vector<std::pair<int, double>>* feature) { parser->ParseOneLine(buffer, feature, &tmp_label); }; std::function<void(data_size_t, const std::vector<std::string>&)> process_fun = [this, &parser_fun, &result_file] (data_size_t, const std::vector<std::string>& lines) { std::vector<std::pair<int, double>> oneline_features; std::vector<std::string> result_to_write(lines.size()); OMP_INIT_EX(); #pragma omp parallel for schedule(static) firstprivate(oneline_features) for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) { OMP_LOOP_EX_BEGIN(); oneline_features.clear(); // parser parser_fun(lines[i].c_str(), &oneline_features); // predict std::vector<double> result(num_pred_one_row_); predict_fun_(oneline_features, result.data()); auto str_result = Common::Join<double>(result, "\t"); result_to_write[i] = str_result; OMP_LOOP_EX_END(); } OMP_THROW_EX(); for (data_size_t i = 0; i < static_cast<data_size_t>(result_to_write.size()); ++i) { fprintf(result_file, "%s\n", result_to_write[i].c_str()); } }; TextReader<data_size_t> predict_data_reader(data_filename, has_header); predict_data_reader.ReadAllAndProcessParallel(process_fun); fclose(result_file); } private: void CopyToPredictBuffer(double* pred_buf, const std::vector<std::pair<int, double>>& features) { int loop_size = static_cast<int>(features.size()); for (int i = 0; i < loop_size; ++i) { if (features[i].first < num_feature_) { pred_buf[features[i].first] = features[i].second; } } } void ClearPredictBuffer(double* pred_buf, size_t buf_size, const std::vector<std::pair<int, double>>& features) { if (features.size() < static_cast<size_t>(buf_size / 2)) { std::memset(pred_buf, 0, sizeof(double)*(buf_size)); } else { int loop_size = static_cast<int>(features.size()); for (int i = 0; i < loop_size; ++i) { if (features[i].first < num_feature_) { pred_buf[features[i].first] = 0.0f; } } } } /*! \brief Boosting model */ const Boosting* boosting_; /*! \brief function for prediction */ PredictFunction predict_fun_; PredictionEarlyStopInstance early_stop_; int num_feature_; int num_pred_one_row_; int num_threads_; std::vector<std::vector<double>> predict_buf_; }; } // namespace LightGBM #endif // LightGBM_PREDICTOR_HPP_ <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qt4symbiantargetfactory.h" #include "qt4projectmanagerconstants.h" #include "qt4project.h" #include "buildconfigurationinfo.h" #include "qt-s60/s60deployconfiguration.h" #include "qt-s60/s60devicerunconfiguration.h" #include "qt-s60/s60emulatorrunconfiguration.h" #include "qt-s60/s60createpackagestep.h" #include "qt-s60/s60deploystep.h" #include "qt-s60/qt4symbiantarget.h" #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/customexecutablerunconfiguration.h> #include <projectexplorer/toolchainmanager.h> using ProjectExplorer::idFromMap; using ProjectExplorer::Task; using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; // ------------------------------------------------------------------------- // Qt4SymbianTargetFactory // ------------------------------------------------------------------------- Qt4SymbianTargetFactory::Qt4SymbianTargetFactory(QObject *parent) : Qt4BaseTargetFactory(parent) { connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>)), this, SIGNAL(supportedTargetIdsChanged())); } Qt4SymbianTargetFactory::~Qt4SymbianTargetFactory() { } bool Qt4SymbianTargetFactory::supportsTargetId(const QString &id) const { return id == QLatin1String(Constants::S60_DEVICE_TARGET_ID) || id == QLatin1String(Constants::S60_EMULATOR_TARGET_ID); } QStringList Qt4SymbianTargetFactory::supportedTargetIds(ProjectExplorer::Project *parent) const { if (parent && !qobject_cast<Qt4Project *>(parent)) return QStringList(); QStringList ids; if (QtVersionManager::instance()->supportsTargetId(Constants::S60_DEVICE_TARGET_ID)) ids << QLatin1String(Constants::S60_DEVICE_TARGET_ID); if (QtVersionManager::instance()->supportsTargetId(Constants::S60_EMULATOR_TARGET_ID)) ids << QLatin1String(Constants::S60_EMULATOR_TARGET_ID); return ids; } QString Qt4SymbianTargetFactory::displayNameForId(const QString &id) const { return Qt4SymbianTarget::defaultDisplayName(id); } QIcon Qt4SymbianTargetFactory::iconForId(const QString &id) const { if (id == QLatin1String(Constants::S60_EMULATOR_TARGET_ID)) return QIcon(":/projectexplorer/images/SymbianEmulator.png"); if (id == QLatin1String(Constants::S60_DEVICE_TARGET_ID)) return QIcon(":/projectexplorer/images/SymbianDevice.png"); return QIcon(); } bool Qt4SymbianTargetFactory::canCreate(ProjectExplorer::Project *parent, const QString &id) const { if (!qobject_cast<Qt4Project *>(parent)) return false; return supportsTargetId(id); } bool Qt4SymbianTargetFactory::canRestore(ProjectExplorer::Project *parent, const QVariantMap &map) const { return canCreate(parent, idFromMap(map)); } ProjectExplorer::Target *Qt4SymbianTargetFactory::restore(ProjectExplorer::Project *parent, const QVariantMap &map) { if (!canRestore(parent, map)) return 0; Qt4Project *qt4project = static_cast<Qt4Project *>(parent); Qt4SymbianTarget *target = new Qt4SymbianTarget(qt4project, idFromMap(map)); if (target->fromMap(map)) return target; delete target; return 0; } QString Qt4SymbianTargetFactory::defaultShadowBuildDirectory(const QString &projectLocation, const QString &id) { Q_UNUSED(projectLocation); Q_UNUSED(id); // should not be called from anywhere, since we override Qt4BaseTarget::defaultBuldDirectory() return QString(); } QList<ProjectExplorer::Task> Qt4SymbianTargetFactory::reportIssues(const QString &proFile) { QList<ProjectExplorer::Task> results; // Warn of strange characters in project name and path: const QString projectName = proFile.mid(proFile.lastIndexOf(QLatin1Char('/')) + 1); QString projectPath = proFile.left(proFile.lastIndexOf(QLatin1Char('/'))); #if defined (Q_OS_WIN) if (projectPath.at(1) == QChar(':') && projectPath.at(0).toUpper() >= QChar('A') && projectPath.at(0).toUpper() <= QChar('Z')) projectPath = projectPath.mid(2); #endif if (projectPath.contains(QLatin1Char(' '))) { results.append(Task(Task::Warning, QCoreApplication::translate("ProjectExplorer::Internal::S60ProjectChecker", "The Symbian tool chain does not handle spaces " "in the project path '%1'.").arg(projectPath), QString(), -1, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } if (projectName.contains(QRegExp("[^a-zA-Z0-9.-]"))) { results.append(Task(Task::Warning, QCoreApplication::translate("ProjectExplorer::Internal::S60ProjectChecker", "The Symbian tool chain does not handle special " "characters in the project name '%1' well.") .arg(projectName), QString(), -1, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } return results; } QList<BuildConfigurationInfo> Qt4SymbianTargetFactory::availableBuildConfigurations(const QString &id, const QString &proFilePath, const QtVersionNumber &minimumQtVersion) { QList<BuildConfigurationInfo> infos; QList<QtVersion *> knownVersions = QtVersionManager::instance()->versionsForTargetId(id, minimumQtVersion); foreach (QtVersion *version, knownVersions) { if (!version->isValid() || !version->toolChainAvailable()) continue; bool buildAll = version->defaultBuildConfig() & QtVersion::BuildAll; QtVersion::QmakeBuildConfigs config = buildAll ? QtVersion::BuildAll : QtVersion::QmakeBuildConfig(0); QString dir = QFileInfo(proFilePath).absolutePath(), id; if (id == Constants::S60_EMULATOR_TARGET_ID) { infos.append(BuildConfigurationInfo(version, config | QtVersion::DebugBuild, QString(), dir)); } else { infos.append(BuildConfigurationInfo(version, config, QString(), dir)); infos.append(BuildConfigurationInfo(version, config ^ QtVersion::DebugBuild, QString(), dir)); } } return infos; } bool Qt4SymbianTargetFactory::isMobileTarget(const QString &id) { Q_UNUSED(id) return true; } ProjectExplorer::Target *Qt4SymbianTargetFactory::create(ProjectExplorer::Project *parent, const QString &id) { if (!canCreate(parent, id)) return 0; QList<QtVersion *> knownVersions = QtVersionManager::instance()->versionsForTargetId(id); if (knownVersions.isEmpty()) return 0; QtVersion *qtVersion = knownVersions.first(); QtVersion::QmakeBuildConfigs config = qtVersion->defaultBuildConfig(); QList<BuildConfigurationInfo> infos; if (id != Constants::S60_EMULATOR_TARGET_ID) { infos.append(BuildConfigurationInfo(qtVersion, config, QString(), QString())); infos.append(BuildConfigurationInfo(qtVersion, config ^ QtVersion::DebugBuild, QString(), QString())); } else { if(config & QtVersion::DebugBuild) infos.append(BuildConfigurationInfo(qtVersion, config, QString(), QString())); else infos.append(BuildConfigurationInfo(qtVersion, config ^ QtVersion::DebugBuild, QString(), QString())); } return create(parent, id, infos); } ProjectExplorer::Target *Qt4SymbianTargetFactory::create(ProjectExplorer::Project *parent, const QString &id, const QList<BuildConfigurationInfo> &infos) { if (!canCreate(parent, id)) return 0; Qt4SymbianTarget *t = new Qt4SymbianTarget(static_cast<Qt4Project *>(parent), id); foreach (const BuildConfigurationInfo &info, infos) t->addQt4BuildConfiguration(msgBuildConfigurationName(info), info.version, info.buildConfig, info.additionalArguments, info.directory); t->addDeployConfiguration(t->deployConfigurationFactory()->create(t, ProjectExplorer::Constants::DEFAULT_DEPLOYCONFIGURATION_ID)); t->createApplicationProFiles(); if (t->runConfigurations().isEmpty()) t->addRunConfiguration(new ProjectExplorer::CustomExecutableRunConfiguration(t)); return t; } ProjectExplorer::Target *Qt4SymbianTargetFactory::create(ProjectExplorer::Project *parent, const QString &id, Qt4TargetSetupWidget *widget) { if (!widget->isTargetSelected()) return 0; Qt4DefaultTargetSetupWidget *w = static_cast<Qt4DefaultTargetSetupWidget *>(widget); return create(parent, id, w->buildConfigurationInfos()); } <commit_msg>Fix deploy configuration for symbian<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qt4symbiantargetfactory.h" #include "qt4projectmanagerconstants.h" #include "qt4project.h" #include "buildconfigurationinfo.h" #include "qt-s60/s60deployconfiguration.h" #include "qt-s60/s60devicerunconfiguration.h" #include "qt-s60/s60emulatorrunconfiguration.h" #include "qt-s60/s60createpackagestep.h" #include "qt-s60/s60deploystep.h" #include "qt-s60/qt4symbiantarget.h" #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/customexecutablerunconfiguration.h> #include <projectexplorer/toolchainmanager.h> using ProjectExplorer::idFromMap; using ProjectExplorer::Task; using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; // ------------------------------------------------------------------------- // Qt4SymbianTargetFactory // ------------------------------------------------------------------------- Qt4SymbianTargetFactory::Qt4SymbianTargetFactory(QObject *parent) : Qt4BaseTargetFactory(parent) { connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>)), this, SIGNAL(supportedTargetIdsChanged())); } Qt4SymbianTargetFactory::~Qt4SymbianTargetFactory() { } bool Qt4SymbianTargetFactory::supportsTargetId(const QString &id) const { return id == QLatin1String(Constants::S60_DEVICE_TARGET_ID) || id == QLatin1String(Constants::S60_EMULATOR_TARGET_ID); } QStringList Qt4SymbianTargetFactory::supportedTargetIds(ProjectExplorer::Project *parent) const { if (parent && !qobject_cast<Qt4Project *>(parent)) return QStringList(); QStringList ids; if (QtVersionManager::instance()->supportsTargetId(Constants::S60_DEVICE_TARGET_ID)) ids << QLatin1String(Constants::S60_DEVICE_TARGET_ID); if (QtVersionManager::instance()->supportsTargetId(Constants::S60_EMULATOR_TARGET_ID)) ids << QLatin1String(Constants::S60_EMULATOR_TARGET_ID); return ids; } QString Qt4SymbianTargetFactory::displayNameForId(const QString &id) const { return Qt4SymbianTarget::defaultDisplayName(id); } QIcon Qt4SymbianTargetFactory::iconForId(const QString &id) const { if (id == QLatin1String(Constants::S60_EMULATOR_TARGET_ID)) return QIcon(":/projectexplorer/images/SymbianEmulator.png"); if (id == QLatin1String(Constants::S60_DEVICE_TARGET_ID)) return QIcon(":/projectexplorer/images/SymbianDevice.png"); return QIcon(); } bool Qt4SymbianTargetFactory::canCreate(ProjectExplorer::Project *parent, const QString &id) const { if (!qobject_cast<Qt4Project *>(parent)) return false; return supportsTargetId(id); } bool Qt4SymbianTargetFactory::canRestore(ProjectExplorer::Project *parent, const QVariantMap &map) const { return canCreate(parent, idFromMap(map)); } ProjectExplorer::Target *Qt4SymbianTargetFactory::restore(ProjectExplorer::Project *parent, const QVariantMap &map) { if (!canRestore(parent, map)) return 0; Qt4Project *qt4project = static_cast<Qt4Project *>(parent); Qt4SymbianTarget *target = new Qt4SymbianTarget(qt4project, idFromMap(map)); if (target->fromMap(map)) return target; delete target; return 0; } QString Qt4SymbianTargetFactory::defaultShadowBuildDirectory(const QString &projectLocation, const QString &id) { Q_UNUSED(projectLocation); Q_UNUSED(id); // should not be called from anywhere, since we override Qt4BaseTarget::defaultBuldDirectory() return QString(); } QList<ProjectExplorer::Task> Qt4SymbianTargetFactory::reportIssues(const QString &proFile) { QList<ProjectExplorer::Task> results; // Warn of strange characters in project name and path: const QString projectName = proFile.mid(proFile.lastIndexOf(QLatin1Char('/')) + 1); QString projectPath = proFile.left(proFile.lastIndexOf(QLatin1Char('/'))); #if defined (Q_OS_WIN) if (projectPath.at(1) == QChar(':') && projectPath.at(0).toUpper() >= QChar('A') && projectPath.at(0).toUpper() <= QChar('Z')) projectPath = projectPath.mid(2); #endif if (projectPath.contains(QLatin1Char(' '))) { results.append(Task(Task::Warning, QCoreApplication::translate("ProjectExplorer::Internal::S60ProjectChecker", "The Symbian tool chain does not handle spaces " "in the project path '%1'.").arg(projectPath), QString(), -1, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } if (projectName.contains(QRegExp("[^a-zA-Z0-9.-]"))) { results.append(Task(Task::Warning, QCoreApplication::translate("ProjectExplorer::Internal::S60ProjectChecker", "The Symbian tool chain does not handle special " "characters in the project name '%1' well.") .arg(projectName), QString(), -1, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } return results; } QList<BuildConfigurationInfo> Qt4SymbianTargetFactory::availableBuildConfigurations(const QString &id, const QString &proFilePath, const QtVersionNumber &minimumQtVersion) { QList<BuildConfigurationInfo> infos; QList<QtVersion *> knownVersions = QtVersionManager::instance()->versionsForTargetId(id, minimumQtVersion); foreach (QtVersion *version, knownVersions) { if (!version->isValid() || !version->toolChainAvailable()) continue; bool buildAll = version->defaultBuildConfig() & QtVersion::BuildAll; QtVersion::QmakeBuildConfigs config = buildAll ? QtVersion::BuildAll : QtVersion::QmakeBuildConfig(0); QString dir = QFileInfo(proFilePath).absolutePath(), id; if (id == Constants::S60_EMULATOR_TARGET_ID) { infos.append(BuildConfigurationInfo(version, config | QtVersion::DebugBuild, QString(), dir)); } else { infos.append(BuildConfigurationInfo(version, config, QString(), dir)); infos.append(BuildConfigurationInfo(version, config ^ QtVersion::DebugBuild, QString(), dir)); } } return infos; } bool Qt4SymbianTargetFactory::isMobileTarget(const QString &id) { Q_UNUSED(id) return true; } ProjectExplorer::Target *Qt4SymbianTargetFactory::create(ProjectExplorer::Project *parent, const QString &id) { if (!canCreate(parent, id)) return 0; QList<QtVersion *> knownVersions = QtVersionManager::instance()->versionsForTargetId(id); if (knownVersions.isEmpty()) return 0; QtVersion *qtVersion = knownVersions.first(); QtVersion::QmakeBuildConfigs config = qtVersion->defaultBuildConfig(); QList<BuildConfigurationInfo> infos; if (id != Constants::S60_EMULATOR_TARGET_ID) { infos.append(BuildConfigurationInfo(qtVersion, config, QString(), QString())); infos.append(BuildConfigurationInfo(qtVersion, config ^ QtVersion::DebugBuild, QString(), QString())); } else { if(config & QtVersion::DebugBuild) infos.append(BuildConfigurationInfo(qtVersion, config, QString(), QString())); else infos.append(BuildConfigurationInfo(qtVersion, config ^ QtVersion::DebugBuild, QString(), QString())); } return create(parent, id, infos); } ProjectExplorer::Target *Qt4SymbianTargetFactory::create(ProjectExplorer::Project *parent, const QString &id, const QList<BuildConfigurationInfo> &infos) { if (!canCreate(parent, id)) return 0; Qt4SymbianTarget *t = new Qt4SymbianTarget(static_cast<Qt4Project *>(parent), id); foreach (const BuildConfigurationInfo &info, infos) t->addQt4BuildConfiguration(msgBuildConfigurationName(info), info.version, info.buildConfig, info.additionalArguments, info.directory); t->addDeployConfiguration(t->createDeployConfiguration(QLatin1String(Qt4ProjectManager::Constants::S60_DEVICE_TARGET_ID))); t->createApplicationProFiles(); if (t->runConfigurations().isEmpty()) t->addRunConfiguration(new ProjectExplorer::CustomExecutableRunConfiguration(t)); return t; } ProjectExplorer::Target *Qt4SymbianTargetFactory::create(ProjectExplorer::Project *parent, const QString &id, Qt4TargetSetupWidget *widget) { if (!widget->isTargetSelected()) return 0; Qt4DefaultTargetSetupWidget *w = static_cast<Qt4DefaultTargetSetupWidget *>(widget); return create(parent, id, w->buildConfigurationInfos()); } <|endoftext|>
<commit_before>#include <QtTest> #include <timing/calendartiming.h> class TestCalendarTiming : public QObject { Q_OBJECT private slots: void constructors() { CalendarTiming timing; QCOMPARE(timing.type(), QLatin1String("calendar")); } void nextRuns() { QTime time = QTime::currentTime(); time = QTime(time.hour(), time.minute(), time.second()); QDateTime now = QDateTime::currentDateTime(); now.setTime(time); QDateTime start = QDateTime::currentDateTime(); QDateTime end; QList<int> months = QList<int>()<<1<<2<<3<<4<<5<<6<<7<<8<<9<<10<<11<<12; QList<int> daysOfWeek = QList<int>()<<1<<2<<3<<4<<5<<6<<7; QList<int> daysOfMonth; QList<int> hours; QList<int> minutes; QList<int> seconds; for (int i = 1; i < 32; i++) { daysOfMonth<<i; } for (int i = 0; i < 24; i++) { hours<<i; } for (int i = 0; i < 60; i++) { minutes<<i; seconds<<i; } // start now CalendarTiming nowTiming(start, end, months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("start time now"); QCOMPARE(nowTiming.nextRun(), now); // start time in the future CalendarTiming futureTiming(start.addDays(1), end, months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("start time one day in the future"); QCOMPARE(futureTiming.nextRun(), now.addDays(1)); // end time already reached CalendarTiming pastTiming(start.addDays(1), start.addDays(-1), months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("end time already reached"); QCOMPARE(pastTiming.nextRun(), QDateTime()); // start tomorrow because hour already passed today (not true before 4 am) CalendarTiming tomorrowTiming(start, end, months, daysOfWeek, daysOfMonth, QList<int>()<<4, minutes, seconds); qDebug("nextRun tomorrow because hour already passed today (4 am)"); QDateTime tomorrowTime = now.addDays(1); tomorrowTime.setTime(QTime(4,0,0)); QCOMPARE(tomorrowTiming.nextRun(), tomorrowTime); // start tomorrow because hour already passed today (not true before 4 am [2]) CalendarTiming tomorrowTiming2(start, end, months, daysOfWeek, daysOfMonth, QList<int>()<<4<<5, minutes, seconds); qDebug("nextRun tomorrow because hour already passed today (4 and 5 am)"); QCOMPARE(tomorrowTiming2.nextRun(), tomorrowTime); // start next month because day already passed this month (not true on 1st of month) CalendarTiming nextMonthTiming(start, end, months, daysOfWeek, QList<int>()<<1, hours, minutes, seconds); qDebug("nextRun next month because day already passed this month (1st)"); QDateTime nextMonthTime = now.addMonths(1); nextMonthTime.setTime(QTime(0,0,0)); nextMonthTime.setDate(QDate(nextMonthTime.date().year(), nextMonthTime.date().month(), 1)); QCOMPARE(nextMonthTiming.nextRun(), nextMonthTime); // start next month because day already passed this month (not true on 1st or 2nd of month) CalendarTiming nextMonthTiming2(start, end, months, daysOfWeek, QList<int>()<<1<<2, hours, minutes, seconds); qDebug("nextRun next month because day already passed this month (1st and 2nd)"); QCOMPARE(nextMonthTiming2.nextRun(), nextMonthTime); // no nextRun because of invalid Timing (February 30th) CalendarTiming februaryTiming(start, end, QList<int>()<<2, daysOfWeek, QList<int>()<<30, hours, minutes, seconds); qDebug("no nextRun because invalid Timing (30.02)"); QCOMPARE(februaryTiming.nextRun(), QDateTime()); // start next year because day already passed this year (not true on January 1st) CalendarTiming yearTiming(start, end, QList<int>()<<1, daysOfWeek, QList<int>()<<1, hours, minutes, seconds); qDebug("nextRun on January 1st"); QCOMPARE(yearTiming.nextRun(), QDateTime(QDate(now.date().year()+1, 1, 1), QTime(0,0,0))); } }; QTEST_MAIN(TestCalendarTiming) #include "tst_calendartiming.moc" <commit_msg>Changed Timing-Unittests to work on the first two days of the month (quickfix for now)<commit_after>#include <QtTest> #include <timing/calendartiming.h> class TestCalendarTiming : public QObject { Q_OBJECT private slots: void constructors() { CalendarTiming timing; QCOMPARE(timing.type(), QLatin1String("calendar")); } void nextRuns() { QTime time = QTime::currentTime(); time = QTime(time.hour(), time.minute(), time.second()); QDateTime now = QDateTime::currentDateTime(); now.setTime(time); QDateTime start = QDateTime::currentDateTime(); QDateTime end; QList<int> months = QList<int>()<<1<<2<<3<<4<<5<<6<<7<<8<<9<<10<<11<<12; QList<int> daysOfWeek = QList<int>()<<1<<2<<3<<4<<5<<6<<7; QList<int> daysOfMonth; QList<int> hours; QList<int> minutes; QList<int> seconds; for (int i = 1; i < 32; i++) { daysOfMonth<<i; } for (int i = 0; i < 24; i++) { hours<<i; } for (int i = 0; i < 60; i++) { minutes<<i; seconds<<i; } // start now CalendarTiming nowTiming(start, end, months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("start time now"); QCOMPARE(nowTiming.nextRun(), now); // start time in the future CalendarTiming futureTiming(start.addDays(1), end, months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("start time one day in the future"); QCOMPARE(futureTiming.nextRun(), now.addDays(1)); // end time already reached CalendarTiming pastTiming(start.addDays(1), start.addDays(-1), months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("end time already reached"); QCOMPARE(pastTiming.nextRun(), QDateTime()); if (now.time().hour() > 3) { // start tomorrow because hour already passed today (not true before 4 am) CalendarTiming tomorrowTiming(start, end, months, daysOfWeek, daysOfMonth, QList<int>()<<4, minutes, seconds); qDebug("nextRun tomorrow because hour already passed today (4 am)"); QDateTime tomorrowTime = now.addDays(1); tomorrowTime.setTime(QTime(4,0,0)); QCOMPARE(tomorrowTiming.nextRun(), tomorrowTime); // start tomorrow because hour already passed today (not true before 4 am [2]) CalendarTiming tomorrowTiming2(start, end, months, daysOfWeek, daysOfMonth, QList<int>()<<4<<5, minutes, seconds); qDebug("nextRun tomorrow because hour already passed today (4 and 5 am)"); QCOMPARE(tomorrowTiming2.nextRun(), tomorrowTime); } if (now.date().day() > 1) { // start next month because day already passed this month (not true on 1st of month) CalendarTiming nextMonthTiming(start, end, months, daysOfWeek, QList<int>()<<1, hours, minutes, seconds); qDebug("nextRun next month because day already passed this month (1st)"); QDateTime nextMonthTime = now.addMonths(1); nextMonthTime.setTime(QTime(0,0,0)); nextMonthTime.setDate(QDate(nextMonthTime.date().year(), nextMonthTime.date().month(), 1)); QCOMPARE(nextMonthTiming.nextRun(), nextMonthTime); } // start next month because day already passed this month (not true on 1st or 2nd of month) if (now.date().day() > 2) { QDateTime nextMonthTime = now.addMonths(1); CalendarTiming nextMonthTiming2(start, end, months, daysOfWeek, QList<int>()<<1<<2, hours, minutes, seconds); qDebug("nextRun next month because day already passed this month (1st and 2nd)"); QCOMPARE(nextMonthTiming2.nextRun(), nextMonthTime); } // no nextRun because of invalid Timing (February 30th) CalendarTiming februaryTiming(start, end, QList<int>()<<2, daysOfWeek, QList<int>()<<30, hours, minutes, seconds); qDebug("no nextRun because invalid Timing (30.02)"); QCOMPARE(februaryTiming.nextRun(), QDateTime()); if (now.date().month() > 1 || now.date().day() > 1) { // start next year because day already passed this year (not true on January 1st) CalendarTiming yearTiming(start, end, QList<int>()<<1, daysOfWeek, QList<int>()<<1, hours, minutes, seconds); qDebug("nextRun on January 1st"); QCOMPARE(yearTiming.nextRun(), QDateTime(QDate(now.date().year()+1, 1, 1), QTime(0,0,0))); } } }; QTEST_MAIN(TestCalendarTiming) #include "tst_calendartiming.moc" <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. * * Written by James D. Berry 7/20/00 * Critical Path Software, Inc. */ /* * $Id$ */ #if !defined(URLACCESSBININPUTSTREAM_HPP) #define URLACCESSBININPUTSTREAM_HPP #include <util/XMLURL.hpp> #include <util/XMLExceptMsgs.hpp> #include <util/BinInputStream.hpp> #if defined(TARGET_API_MAC_CARBON) #include <Carbon.h> #else #include <URLAccess.h> #endif // // This class implements the BinInputStream interface specified by the XML // parser. // class XMLUTIL_EXPORT URLAccessBinInputStream : public BinInputStream { public : URLAccessBinInputStream(const XMLURL& urlSource); ~URLAccessBinInputStream(); unsigned int curPos() const; unsigned int readBytes ( XMLByte* const toFill , const unsigned int maxToRead ); private : unsigned int mBytesProcessed; URLReference mURLReference; void* mBuffer; // Current buffer from URLAccess (or NULL) char* mBufPos; // Read position in buffer Size mBufAvailable; // Bytes available }; inline unsigned int URLAccessBinInputStream::curPos() const { return mBytesProcessed; } #endif // URLACCESSBININPUTSTREAM_HPP <commit_msg>Omit include carbon.h in favor of specific include files<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. * * Written by James D. Berry 7/20/00 * Critical Path Software, Inc. */ /* * $Id$ */ #if !defined(URLACCESSBININPUTSTREAM_HPP) #define URLACCESSBININPUTSTREAM_HPP #include <util/XMLURL.hpp> #include <util/XMLExceptMsgs.hpp> #include <util/BinInputStream.hpp> #if defined(XML_MACOSX) // Framework includes from ProjectBuilder #include <URLAccess/URLAccess.h> #else // Classic includes otherwise #include <URLAccess.h> #endif // // This class implements the BinInputStream interface specified by the XML // parser. // class XMLUTIL_EXPORT URLAccessBinInputStream : public BinInputStream { public : URLAccessBinInputStream(const XMLURL& urlSource); ~URLAccessBinInputStream(); unsigned int curPos() const; unsigned int readBytes ( XMLByte* const toFill , const unsigned int maxToRead ); private : unsigned int mBytesProcessed; URLReference mURLReference; void* mBuffer; // Current buffer from URLAccess (or NULL) char* mBufPos; // Read position in buffer Size mBufAvailable; // Bytes available }; inline unsigned int URLAccessBinInputStream::curPos() const { return mBytesProcessed; } #endif // URLACCESSBININPUTSTREAM_HPP <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/FileUtils> #include <osg/Version> #include "PluginQuery.h" using namespace osgDB; FileNameList osgDB::listAllAvailablePlugins() { FileNameList pluginFiles; std::string pluginDirectoryName = std::string("osgPlugins-")+std::string(osgGetVersion()); std::string fullPath = osgDB::findLibraryFile(pluginDirectoryName); if (!fullPath.empty()) { osgDB::DirectoryContents contents = getDirectoryContents(fullPath); for(DirectoryContents::iterator itr = contents.begin(); itr != contents.end(); ++itr) { std::string::size_type pos = itr->find("osgdb_"); if (pos!=std::string::npos) { pluginFiles.push_back(fullPath + std::string("/")+*itr); } } } return pluginFiles; } bool osgDB::queryPlugin(const std::string& fileName, ReaderWriterInfoList& infoList) { if (osgDB::Registry::instance()->loadLibrary(fileName)) { const Registry::ReaderWriterList& rwList = osgDB::Registry::instance()->getReaderWriterList(); for(Registry::ReaderWriterList::const_iterator itr = rwList.begin(); itr != rwList.end(); ++itr) { const ReaderWriter* rw = itr->get(); osg::ref_ptr<ReaderWriterInfo> rwi = new ReaderWriterInfo; rwi->plugin = fileName; rwi->description = rw->className(); rwi->protocols = rw->supportedProtocols(); rwi->extensions = rw->supportedExtensions(); rwi->options = rw->supportedOptions(); infoList.push_back(rwi.get()); } osgDB::Registry::instance()->closeLibrary(fileName); return true; } else { return false; } } static std::string padwithspaces(const std::string& str, unsigned int padLength) { std::string newStr(str); while(newStr.length()<padLength) newStr.push_back(' '); return newStr; } bool osgDB::outputPluginDetails(std::ostream& out, const std::string& fileName) { osgDB::ReaderWriterInfoList infoList; if (osgDB::queryPlugin(fileName, infoList)) { out<<"Plugin "<<fileName<<std::endl; out<<"{"<<std::endl; for(osgDB::ReaderWriterInfoList::iterator rwi_itr = infoList.begin(); rwi_itr != infoList.end(); ++rwi_itr) { osgDB::ReaderWriterInfo& info = *(*rwi_itr); out<<" ReaderWriter : "<<info.description<<std::endl; out<<" {"<<std::endl; unsigned int longestOptionLength = 0; osgDB::ReaderWriter::FormatDescriptionMap::iterator fdm_itr; for(fdm_itr = info.protocols.begin(); fdm_itr != info.protocols.end(); ++fdm_itr) { if (fdm_itr->first.length()>longestOptionLength) longestOptionLength = fdm_itr->first.length(); } for(fdm_itr = info.extensions.begin(); fdm_itr != info.extensions.end(); ++fdm_itr) { if (fdm_itr->first.length()>longestOptionLength) longestOptionLength = fdm_itr->first.length(); } for(fdm_itr = info.options.begin(); fdm_itr != info.options.end(); ++fdm_itr) { if (fdm_itr->first.length()>longestOptionLength) longestOptionLength = fdm_itr->first.length(); } unsigned int padLength = longestOptionLength+4; for(fdm_itr = info.protocols.begin(); fdm_itr != info.protocols.end(); ++fdm_itr) { out<<" protocol : "<<padwithspaces(fdm_itr->first, padLength)<<fdm_itr->second<<std::endl; } for(fdm_itr = info.extensions.begin(); fdm_itr != info.extensions.end(); ++fdm_itr) { out<<" extensions : ."<<padwithspaces(fdm_itr->first, padLength-1)<<fdm_itr->second<<std::endl; } for(fdm_itr = info.options.begin(); fdm_itr != info.options.end(); ++fdm_itr) { out<<" options : "<<padwithspaces(fdm_itr->first, padLength)<<fdm_itr->second<<std::endl; } out<<" }"<<std::endl; } out<<"}"<<std::endl<<std::endl; } else { out<<"Plugin "<<fileName<<" not found."<<std::endl; } } <commit_msg>Added missing returns<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/FileUtils> #include <osg/Version> #include "PluginQuery.h" using namespace osgDB; FileNameList osgDB::listAllAvailablePlugins() { FileNameList pluginFiles; std::string pluginDirectoryName = std::string("osgPlugins-")+std::string(osgGetVersion()); std::string fullPath = osgDB::findLibraryFile(pluginDirectoryName); if (!fullPath.empty()) { osgDB::DirectoryContents contents = getDirectoryContents(fullPath); for(DirectoryContents::iterator itr = contents.begin(); itr != contents.end(); ++itr) { std::string::size_type pos = itr->find("osgdb_"); if (pos!=std::string::npos) { pluginFiles.push_back(fullPath + std::string("/")+*itr); } } } return pluginFiles; } bool osgDB::queryPlugin(const std::string& fileName, ReaderWriterInfoList& infoList) { if (osgDB::Registry::instance()->loadLibrary(fileName)) { const Registry::ReaderWriterList& rwList = osgDB::Registry::instance()->getReaderWriterList(); for(Registry::ReaderWriterList::const_iterator itr = rwList.begin(); itr != rwList.end(); ++itr) { const ReaderWriter* rw = itr->get(); osg::ref_ptr<ReaderWriterInfo> rwi = new ReaderWriterInfo; rwi->plugin = fileName; rwi->description = rw->className(); rwi->protocols = rw->supportedProtocols(); rwi->extensions = rw->supportedExtensions(); rwi->options = rw->supportedOptions(); infoList.push_back(rwi.get()); } osgDB::Registry::instance()->closeLibrary(fileName); return true; } else { return false; } } static std::string padwithspaces(const std::string& str, unsigned int padLength) { std::string newStr(str); while(newStr.length()<padLength) newStr.push_back(' '); return newStr; } bool osgDB::outputPluginDetails(std::ostream& out, const std::string& fileName) { osgDB::ReaderWriterInfoList infoList; if (osgDB::queryPlugin(fileName, infoList)) { out<<"Plugin "<<fileName<<std::endl; out<<"{"<<std::endl; for(osgDB::ReaderWriterInfoList::iterator rwi_itr = infoList.begin(); rwi_itr != infoList.end(); ++rwi_itr) { osgDB::ReaderWriterInfo& info = *(*rwi_itr); out<<" ReaderWriter : "<<info.description<<std::endl; out<<" {"<<std::endl; unsigned int longestOptionLength = 0; osgDB::ReaderWriter::FormatDescriptionMap::iterator fdm_itr; for(fdm_itr = info.protocols.begin(); fdm_itr != info.protocols.end(); ++fdm_itr) { if (fdm_itr->first.length()>longestOptionLength) longestOptionLength = fdm_itr->first.length(); } for(fdm_itr = info.extensions.begin(); fdm_itr != info.extensions.end(); ++fdm_itr) { if (fdm_itr->first.length()>longestOptionLength) longestOptionLength = fdm_itr->first.length(); } for(fdm_itr = info.options.begin(); fdm_itr != info.options.end(); ++fdm_itr) { if (fdm_itr->first.length()>longestOptionLength) longestOptionLength = fdm_itr->first.length(); } unsigned int padLength = longestOptionLength+4; for(fdm_itr = info.protocols.begin(); fdm_itr != info.protocols.end(); ++fdm_itr) { out<<" protocol : "<<padwithspaces(fdm_itr->first, padLength)<<fdm_itr->second<<std::endl; } for(fdm_itr = info.extensions.begin(); fdm_itr != info.extensions.end(); ++fdm_itr) { out<<" extensions : ."<<padwithspaces(fdm_itr->first, padLength-1)<<fdm_itr->second<<std::endl; } for(fdm_itr = info.options.begin(); fdm_itr != info.options.end(); ++fdm_itr) { out<<" options : "<<padwithspaces(fdm_itr->first, padLength)<<fdm_itr->second<<std::endl; } out<<" }"<<std::endl; } out<<"}"<<std::endl<<std::endl; return true; } else { out<<"Plugin "<<fileName<<" not found."<<std::endl; return false; } } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> #include <osg/Switch> #include <osgText/Text> #include <osgViewer/Viewer> #include <osgViewer/StatsHandler> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <iostream> class ThreadingHandler : public osgGA::GUIEventHandler { public: ThreadingHandler() {} bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa); if (!viewer) return false; switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYUP): { if (ea.getKey()=='m') { switch(viewer->getThreadingModel()) { case(osgViewer::Viewer::SingleThreaded): viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'CullDrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::CullDrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'DrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::DrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'CullThreadPerCameraDrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded); osg::notify(osg::NOTICE)<<"Threading model 'SingleThreaded' selected."<<std::endl; break; case(osgViewer::Viewer::AutomaticSelection): viewer->setThreadingModel(viewer->suggestBestThreadingModel()); osg::notify(osg::NOTICE)<<"Threading model 'AutomaticSelection' selected."<<std::endl; break; } return true; } if (ea.getKey()=='e') { switch(viewer->getEndBarrierPosition()) { case(osgViewer::Viewer::BeforeSwapBuffers): viewer->setEndBarrierPosition(osgViewer::Viewer::AfterSwapBuffers); osg::notify(osg::NOTICE)<<"Threading model 'AfterSwapBuffers' selected."<<std::endl; break; case(osgViewer::Viewer::AfterSwapBuffers): viewer->setEndBarrierPosition(osgViewer::Viewer::BeforeSwapBuffers); osg::notify(osg::NOTICE)<<"Threading model 'BeforeSwapBuffers' selected."<<std::endl; break; } return true; } } default: break; } return false; } bool _done; }; int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings."); // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } osgViewer::Viewer viewer; // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); ++keyForAnimationPath; } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new ThreadingHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); unsigned int screenNum; while (arguments.read("--screen",screenNum)) { viewer.setUpViewOnSingleScreen(screenNum); } // load the data osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); viewer.setSceneData( loadedModel.get() ); return viewer.run(); } <commit_msg>Disabled the toggling to ThreadModel CullThreadPerCameraDrawThreadPerContext<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> #include <osg/Switch> #include <osgText/Text> #include <osgViewer/Viewer> #include <osgViewer/StatsHandler> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <iostream> class ThreadingHandler : public osgGA::GUIEventHandler { public: ThreadingHandler() {} bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa); if (!viewer) return false; switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYUP): { if (ea.getKey()=='m') { #if 1 switch(viewer->getThreadingModel()) { case(osgViewer::Viewer::SingleThreaded): viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'CullDrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::CullDrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'DrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::DrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded); osg::notify(osg::NOTICE)<<"Threading model 'SingleThreaded' selected."<<std::endl; break; default: break; } #else switch(viewer->getThreadingModel()) { case(osgViewer::Viewer::SingleThreaded): viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'CullDrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::CullDrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'DrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::DrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext); osg::notify(osg::NOTICE)<<"Threading model 'CullThreadPerCameraDrawThreadPerContext' selected."<<std::endl; break; case(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext): viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded); osg::notify(osg::NOTICE)<<"Threading model 'SingleThreaded' selected."<<std::endl; break; case(osgViewer::Viewer::AutomaticSelection): viewer->setThreadingModel(viewer->suggestBestThreadingModel()); osg::notify(osg::NOTICE)<<"Threading model 'AutomaticSelection' selected."<<std::endl; break; } #endif return true; } if (ea.getKey()=='e') { switch(viewer->getEndBarrierPosition()) { case(osgViewer::Viewer::BeforeSwapBuffers): viewer->setEndBarrierPosition(osgViewer::Viewer::AfterSwapBuffers); osg::notify(osg::NOTICE)<<"Threading model 'AfterSwapBuffers' selected."<<std::endl; break; case(osgViewer::Viewer::AfterSwapBuffers): viewer->setEndBarrierPosition(osgViewer::Viewer::BeforeSwapBuffers); osg::notify(osg::NOTICE)<<"Threading model 'BeforeSwapBuffers' selected."<<std::endl; break; } return true; } } default: break; } return false; } bool _done; }; int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings."); // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } osgViewer::Viewer viewer; // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); ++keyForAnimationPath; } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new ThreadingHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); unsigned int screenNum; while (arguments.read("--screen",screenNum)) { viewer.setUpViewOnSingleScreen(screenNum); } // load the data osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); viewer.setSceneData( loadedModel.get() ); return viewer.run(); } <|endoftext|>
<commit_before>#include "sm/logging.hpp" #include <string> #include <boost/algorithm/string.hpp> // for case-insensitive string comparison /** * \brief Returns a Level enum from string */ sm::logging::Level sm::logging::levels::fromString(const std::string& l) { // enum Level // { // All, // Finest, // Verbose, // Finer, // Trace, // Fine, // Debug, // Info, // Warn, // Error, // Fatal, // // Count // }; if (boost::iequals(l, "All")) { return Level::All; } else if (boost::iequals(l, "Finest")) { return Level::Finest; } else if (boost::iequals(l, "Verbose")) { return Level::Verbose; } else if (boost::iequals(l, "Finer")) { return Level::Finer; } else if (boost::iequals(l, "Trace")) { return Level::Trace; } else if (boost::iequals(l, "Fine")) { return Level::Fine; } else if (boost::iequals(l, "Debug")) { return Level::Debug; } else if (boost::iequals(l, "Info")) { return Level::Info; } else if (boost::iequals(l, "Warn")) { return Level::Warn; } else if (boost::iequals(l, "Error")) { return Level::Error; } else if (boost::iequals(l, "Fatal")) { return Level::Fatal; } else { SM_ERROR_STREAM("Invalid logging level " << l << ", setting to Level::Info"); return Level::Info; } }<commit_msg>Update Levels.cpp<commit_after>#include "sm/logging.hpp" #include <string> #include <boost/algorithm/string.hpp> // for case-insensitive string comparison /** * \brief Returns a Level enum from string */ sm::logging::Level sm::logging::levels::fromString(const std::string& level) { if (boost::iequals(level, "All")) { return Level::All; } else if (boost::iequals(level, "Finest")) { return Level::Finest; } else if (boost::iequals(level, "Verbose")) { return Level::Verbose; } else if (boost::iequals(level, "Finer")) { return Level::Finer; } else if (boost::iequals(level, "Trace")) { return Level::Trace; } else if (boost::iequals(level, "Fine")) { return Level::Fine; } else if (boost::iequals(level, "Debug")) { return Level::Debug; } else if (boost::iequals(level, "Info")) { return Level::Info; } else if (boost::iequals(level, "Warn")) { return Level::Warn; } else if (boost::iequals(level, "Error")) { return Level::Error; } else if (boost::iequals(level, "Fatal")) { return Level::Fatal; } else { SM_ERROR_STREAM("Invalid logging level " << level << ", setting to Level::Info"); return Level::Info; } } <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; void blur_float(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func blur_x("blur_x"); blur_x(x, y, c) = (input(x, y, c) + input(x + 1, y, c) + input(x + 2, y, c)) / 3; Func result("result"); result(x, y, c) = (blur_x(x, y, c) + blur_x(x, y + 1, c) + blur_x(x, y + 2, c)) / 3; // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); result.bound(c, 0, channels); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); Expr planar = result.output_buffer().stride(0) == 1; if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); // non-specialized version is planar } else { Var yi; result .reorder(c, x, y) .unroll(c) .split(y, y, yi, 32) .parallel(y) .vectorize(x, 2); result.specialize(interleaved); result.specialize(planar); // blur_x is compute at result, so it's included in result's // specializations. blur_x.store_at(result, y) .compute_at(result, yi) .reorder(c, x, y) .unroll(c) .vectorize(x, 2); } std::vector<Argument> args; args.push_back(input8); std::string filename("generated_blur"); result.compile_to_file(filename + suffix + "_float", args); } void copy_float(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func result("result"); result(x, y, c) = input(x, y, c); result.bound(c, 0, channels); // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); } else { result.reorder(c, x, y) .parallel(y) .unroll(c) .vectorize(x, 2) .specialize(interleaved); } // non-specialized version is planar std::vector<Argument> args; args.push_back(input8); std::string filename("generated_copy"); result.compile_to_file(filename + suffix + "_float", args); } void blur_uint8(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func blur_x("blur_x"); blur_x(x, y, c) = cast<uint8_t>( (cast<uint16_t>(input(x, y, c)) + input(x + 1, y, c) + input(x + 2, y, c)) / 3); Func result("result"); result(x, y, c) = cast<uint8_t>( (cast<uint16_t>(blur_x(x, y, c)) + blur_x(x, y + 1, c) + blur_x(x, y + 2, c)) / 3); // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); result.bound(c, 0, channels); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); Expr planar = result.output_buffer().stride(0) == 1; if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); // non-specialized version is planar } else { Var yi; result .reorder(c, x, y) .unroll(c) .split(y, y, yi, 32) .parallel(y) .vectorize(x, 8); result.specialize(interleaved); result.specialize(planar); // blur_x is compute at result, so it's included in result's // specializations. blur_x.store_at(result, y) .compute_at(result, yi) .reorder(c, x, y) .unroll(c) .vectorize(x, 8); } std::vector<Argument> args; args.push_back(input8); std::string filename("generated_blur"); result.compile_to_file(filename + suffix + "_uint8", args); } void copy_uint8(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func result("result"); result(x, y, c) = input(x, y, c); result.bound(c, 0, channels); // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); } else { result.reorder(c, x, y) .parallel(y) .unroll(c) .vectorize(x, 16) .specialize(interleaved); } // non-specialized version is planar std::vector<Argument> args; args.push_back(input8); std::string filename("generated_copy"); result.compile_to_file(filename + suffix + "_uint8", args); } int main(int argc, char **argv) { const int channels = 4; ImageParam input_float(Float(32), 3, "input"); input_float.set_stride(0, Expr()); blur_float(argc > 1 ? argv[1] : "", input_float, channels); copy_float(argc > 1 ? argv[1]: "", input_float, channels); ImageParam input_uint8(UInt(8), 3, "input"); input_uint8.set_stride(0, Expr()); blur_uint8(argc > 1 ? argv[1] : "", input_uint8, channels); copy_uint8(argc > 1 ? argv[1]: "", input_uint8, channels); std::cout << "Done!" << std::endl; } <commit_msg>Adjust vectorization to match natural vector size for ARM NEON<commit_after>#include "Halide.h" using namespace Halide; void blur_float(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func blur_x("blur_x"); blur_x(x, y, c) = (input(x, y, c) + input(x + 1, y, c) + input(x + 2, y, c)) / 3; Func result("result"); result(x, y, c) = (blur_x(x, y, c) + blur_x(x, y + 1, c) + blur_x(x, y + 2, c)) / 3; // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); result.bound(c, 0, channels); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); Expr planar = result.output_buffer().stride(0) == 1; if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); // non-specialized version is planar } else { Var yi; result .reorder(c, x, y) .unroll(c) .split(y, y, yi, 32) .parallel(y) .vectorize(x, 4); result.specialize(interleaved); result.specialize(planar); // blur_x is compute at result, so it's included in result's // specializations. blur_x.store_at(result, y) .compute_at(result, yi) .reorder(c, x, y) .unroll(c) .vectorize(x, 4); } std::vector<Argument> args; args.push_back(input8); std::string filename("generated_blur"); result.compile_to_file(filename + suffix + "_float", args); } void copy_float(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func result("result"); result(x, y, c) = input(x, y, c); result.bound(c, 0, channels); // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); } else { result.reorder(c, x, y) .parallel(y) .unroll(c) .vectorize(x, 4) .specialize(interleaved); } // non-specialized version is planar std::vector<Argument> args; args.push_back(input8); std::string filename("generated_copy"); result.compile_to_file(filename + suffix + "_float", args); } void blur_uint8(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func blur_x("blur_x"); blur_x(x, y, c) = cast<uint8_t>( (cast<uint16_t>(input(x, y, c)) + input(x + 1, y, c) + input(x + 2, y, c)) / 3); Func result("result"); result(x, y, c) = cast<uint8_t>( (cast<uint16_t>(blur_x(x, y, c)) + blur_x(x, y + 1, c) + blur_x(x, y + 2, c)) / 3); // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); result.bound(c, 0, channels); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); Expr planar = result.output_buffer().stride(0) == 1; if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); // non-specialized version is planar } else { Var yi; result .reorder(c, x, y) .unroll(c) .split(y, y, yi, 32) .parallel(y) .vectorize(x, 8); result.specialize(interleaved); result.specialize(planar); // blur_x is compute at result, so it's included in result's // specializations. blur_x.store_at(result, y) .compute_at(result, yi) .reorder(c, x, y) .unroll(c) .vectorize(x, 8); } std::vector<Argument> args; args.push_back(input8); std::string filename("generated_blur"); result.compile_to_file(filename + suffix + "_uint8", args); } void copy_uint8(std::string suffix, ImageParam input8, const int channels) { Var x, y, c; Func input; input(x, y, c) = input8(clamp(x, input8.left(), input8.right()), clamp(y, input8.top(), input8.bottom()), c); Func result("result"); result(x, y, c) = input(x, y, c); result.bound(c, 0, channels); // Unset default constraints so that specialization works. result.output_buffer().set_stride(0, Expr()); Expr interleaved = (result.output_buffer().stride(0) == channels && result.output_buffer().stride(2) == 1); if (suffix == "_rs") { result.shader(x, y, c, DeviceAPI::Renderscript); result.specialize(interleaved).vectorize(c); } else { result.reorder(c, x, y) .parallel(y) .unroll(c) .vectorize(x, 16) .specialize(interleaved); } // non-specialized version is planar std::vector<Argument> args; args.push_back(input8); std::string filename("generated_copy"); result.compile_to_file(filename + suffix + "_uint8", args); } int main(int argc, char **argv) { const int channels = 4; ImageParam input_float(Float(32), 3, "input"); input_float.set_stride(0, Expr()); blur_float(argc > 1 ? argv[1] : "", input_float, channels); copy_float(argc > 1 ? argv[1]: "", input_float, channels); ImageParam input_uint8(UInt(8), 3, "input"); input_uint8.set_stride(0, Expr()); blur_uint8(argc > 1 ? argv[1] : "", input_uint8, channels); copy_uint8(argc > 1 ? argv[1]: "", input_uint8, channels); std::cout << "Done!" << std::endl; } <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <memory> #include "atom/browser/api/atom_api_cookies.h" #include "atom/browser/atom_browser_context.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace mate { template<> struct Converter<atom::api::Cookies::Error> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, atom::api::Cookies::Error val) { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else return v8::Exception::Error(StringToV8(isolate, "Setting cookie failed")); } }; template<> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); return dict.GetHandle(); } }; } // namespace mate namespace atom { namespace api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::DictionaryValue* filter, const net::CanonicalCookie& cookie) { std::string str; bool b; if (filter->GetString("name", &str) && str != cookie.Name()) return false; if (filter->GetString("path", &str) && str != cookie.Path()) return false; if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain())) return false; if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure()) return false; if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent()) return false; return true; } // Helper to returns the CookieStore. inline net::CookieStore* GetCookieStore( scoped_refptr<net::URLRequestContextGetter> getter) { return getter->GetURLRequestContext()->cookie_store(); } // Run |callback| on UI thread. void RunCallbackInUI(const base::Closure& callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(std::unique_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback, const net::CookieList& list) { net::CookieList result; for (const auto& cookie : list) { if (MatchesCookie(filter.get(), cookie)) result.push_back(cookie); } RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result)); } // Receives cookies matching |filter| in IO thread. void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, std::unique_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback) { std::string url; filter->GetString("url", &url); auto filtered_callback = base::Bind(FilterCookies, base::Passed(&filter), callback); // Empty url will match all url cookies. if (url.empty()) GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback); else GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url), filtered_callback); } // Removes cookie with |url| and |name| in IO thread. void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter, const GURL& url, const std::string& name, const base::Closure& callback) { GetCookieStore(getter)->DeleteCookieAsync( url, name, base::Bind(RunCallbackInUI, callback)); } // Callback of SetCookie. void OnSetCookie(const Cookies::SetCallback& callback, bool success) { RunCallbackInUI( base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED)); } // Sets cookie with |details| in IO thread. void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, std::unique_ptr<base::DictionaryValue> details, const Cookies::SetCallback& callback) { std::string url, name, value, domain, path; bool secure = false; bool http_only = false; double creation_date; double expiration_date; double last_access_date; details->GetString("url", &url); details->GetString("name", &name); details->GetString("value", &value); details->GetString("domain", &domain); details->GetString("path", &path); details->GetBoolean("secure", &secure); details->GetBoolean("httpOnly", &http_only); base::Time creation_time; if (details->GetDouble("creationDate", &creation_date)) { creation_time = (creation_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(creation_date); } base::Time expiration_time; if (details->GetDouble("expirationDate", &expiration_date)) { expiration_time = (expiration_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date); } base::Time last_access_time; if (details->GetDouble("lastAccessDate", &last_access_date)) { last_access_time = (last_access_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(last_access_date); } GetCookieStore(getter)->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, creation_time, expiration_time, last_access_time, secure, http_only, net::CookieSameSite::DEFAULT_MODE, false, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); } } // namespace Cookies::Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context) : request_context_getter_(browser_context->url_request_context_getter()) { Init(isolate); } Cookies::~Cookies() { } void Cookies::Get(const base::DictionaryValue& filter, const GetCallback& callback) { std::unique_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); auto getter = base::RetainedRef(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback)); } void Cookies::Remove(const GURL& url, const std::string& name, const base::Closure& callback) { auto getter = base::RetainedRef(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(RemoveCookieOnIOThread, getter, url, name, callback)); } void Cookies::Set(const base::DictionaryValue& details, const SetCallback& callback) { std::unique_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); auto getter = base::RetainedRef(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(SetCookieOnIO, getter, Passed(&copied), callback)); } // static mate::Handle<Cookies> Cookies::Create( v8::Isolate* isolate, AtomBrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static void Cookies::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(mate::StringToV8(isolate, "Cookies")); mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set); } } // namespace api } // namespace atom <commit_msg>Update SetCookieWithDetailsAsync call to match interface<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <memory> #include "atom/browser/api/atom_api_cookies.h" #include "atom/browser/atom_browser_context.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace mate { template<> struct Converter<atom::api::Cookies::Error> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, atom::api::Cookies::Error val) { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else return v8::Exception::Error(StringToV8(isolate, "Setting cookie failed")); } }; template<> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); return dict.GetHandle(); } }; } // namespace mate namespace atom { namespace api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::DictionaryValue* filter, const net::CanonicalCookie& cookie) { std::string str; bool b; if (filter->GetString("name", &str) && str != cookie.Name()) return false; if (filter->GetString("path", &str) && str != cookie.Path()) return false; if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain())) return false; if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure()) return false; if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent()) return false; return true; } // Helper to returns the CookieStore. inline net::CookieStore* GetCookieStore( scoped_refptr<net::URLRequestContextGetter> getter) { return getter->GetURLRequestContext()->cookie_store(); } // Run |callback| on UI thread. void RunCallbackInUI(const base::Closure& callback) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback); } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(std::unique_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback, const net::CookieList& list) { net::CookieList result; for (const auto& cookie : list) { if (MatchesCookie(filter.get(), cookie)) result.push_back(cookie); } RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result)); } // Receives cookies matching |filter| in IO thread. void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, std::unique_ptr<base::DictionaryValue> filter, const Cookies::GetCallback& callback) { std::string url; filter->GetString("url", &url); auto filtered_callback = base::Bind(FilterCookies, base::Passed(&filter), callback); // Empty url will match all url cookies. if (url.empty()) GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback); else GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url), filtered_callback); } // Removes cookie with |url| and |name| in IO thread. void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter, const GURL& url, const std::string& name, const base::Closure& callback) { GetCookieStore(getter)->DeleteCookieAsync( url, name, base::Bind(RunCallbackInUI, callback)); } // Callback of SetCookie. void OnSetCookie(const Cookies::SetCallback& callback, bool success) { RunCallbackInUI( base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED)); } // Sets cookie with |details| in IO thread. void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, std::unique_ptr<base::DictionaryValue> details, const Cookies::SetCallback& callback) { std::string url, name, value, domain, path; bool secure = false; bool http_only = false; double creation_date; double expiration_date; double last_access_date; details->GetString("url", &url); details->GetString("name", &name); details->GetString("value", &value); details->GetString("domain", &domain); details->GetString("path", &path); details->GetBoolean("secure", &secure); details->GetBoolean("httpOnly", &http_only); base::Time creation_time; if (details->GetDouble("creationDate", &creation_date)) { creation_time = (creation_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(creation_date); } base::Time expiration_time; if (details->GetDouble("expirationDate", &expiration_date)) { expiration_time = (expiration_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date); } base::Time last_access_time; if (details->GetDouble("lastAccessDate", &last_access_date)) { last_access_time = (last_access_date == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(last_access_date); } GetCookieStore(getter)->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, creation_time, expiration_time, last_access_time, secure, http_only, net::CookieSameSite::DEFAULT_MODE, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); } } // namespace Cookies::Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context) : request_context_getter_(browser_context->url_request_context_getter()) { Init(isolate); } Cookies::~Cookies() { } void Cookies::Get(const base::DictionaryValue& filter, const GetCallback& callback) { std::unique_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); auto getter = base::RetainedRef(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback)); } void Cookies::Remove(const GURL& url, const std::string& name, const base::Closure& callback) { auto getter = base::RetainedRef(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(RemoveCookieOnIOThread, getter, url, name, callback)); } void Cookies::Set(const base::DictionaryValue& details, const SetCallback& callback) { std::unique_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); auto getter = base::RetainedRef(request_context_getter_); content::BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(SetCookieOnIO, getter, Passed(&copied), callback)); } // static mate::Handle<Cookies> Cookies::Create( v8::Isolate* isolate, AtomBrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static void Cookies::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(mate::StringToV8(isolate, "Cookies")); mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set); } } // namespace api } // namespace atom <|endoftext|>
<commit_before>// copy of avx512bw.cpp, but use masked writes instead of explicit bit-or operations #include <cstdint> #include <immintrin.h> void jpeg_zigzag_avx512bw_masks(const uint8_t* in, uint8_t* out) { const __m512i v = _mm512_loadu_si512((const __m512i*)in); // populate lanes -- each lane represents pair of output rows const __m512i A = _mm512_permutexvar_epi32( _mm512_setr_epi32(0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3), v); const __m512i B = _mm512_permutexvar_epi32( _mm512_setr_epi32(4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7), v); const __m512i C = _mm512_permutexvar_epi32( _mm512_setr_epi32(8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11), v); const __m512i D = _mm512_permutexvar_epi32( _mm512_setr_epi32(12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15), v); // perform shuffling within lanes static const int8_t shuffle_A[64] __attribute__((aligned(64))) = { 0, 1, 8, -1, 9, 2, 3, 10, -1, -1, -1, -1, -1, 11, 4, 5, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13, 6, 7, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const int8_t shuffle_B[64] __attribute__((aligned(64))) = { -1, -1, -1, 0, -1, -1, -1, -1, 1, 8, -1, 9, 2, -1, -1, -1, -1, 3, 10, -1, -1, -1, -1, -1, 11, 4, -1, -1, -1, -1, 5, 12, -1, -1, -1, -1, -1, -1, -1, -1, 13, 6, -1, 7, 14, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const int8_t shuffle_C[64] __attribute__((aligned(64))) = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, -1, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, 3, 10, -1, -1, -1, -1, 11, 4, -1, -1, -1, -1, -1, 5, 12, -1, -1, -1, -1, 13, 6, -1, 7, 14, -1, -1, -1, -1, 15, -1, -1, -1 }; static const int8_t shuffle_D[64] __attribute__((aligned(64))) = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 10, 11, 4, -1, -1, -1, -1, -1, 5, 12, 13, 6, -1, 7, 14, 15 }; __m512i result = _mm512_shuffle_epi8(A, _mm512_load_si512((const __m512i*)shuffle_A)); result = _mm512_mask_shuffle_epi8(result, 0x00201b00c3061b08lu, B, _mm512_load_si512((const __m512i*)shuffle_B)); result = _mm512_mask_shuffle_epi8(result, 0x10d860c300d80400lu, C, _mm512_load_si512((const __m512i*)shuffle_C)); result = _mm512_mask_shuffle_epi8(result, 0xef07803c00200000lu, D, _mm512_load_si512((const __m512i*)shuffle_D)); _mm512_storeu_si512((__m512i*)out, result); } <commit_msg>AVX512 masked: use the same broadcasting code<commit_after>// copy of avx512bw.cpp, but use masked writes instead of explicit bit-or operations #include <cstdint> #include <immintrin.h> void jpeg_zigzag_avx512bw_masks(const uint8_t* in, uint8_t* out) { // populate lanes -- each lane represents pair of output rows const __m512i A = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 0 * 16))); const __m512i B = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 1 * 16))); const __m512i C = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 2 * 16))); const __m512i D = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 3 * 16))); // perform shuffling within lanes static const int8_t shuffle_A[64] __attribute__((aligned(64))) = { 0, 1, 8, -1, 9, 2, 3, 10, -1, -1, -1, -1, -1, 11, 4, 5, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13, 6, 7, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const int8_t shuffle_B[64] __attribute__((aligned(64))) = { -1, -1, -1, 0, -1, -1, -1, -1, 1, 8, -1, 9, 2, -1, -1, -1, -1, 3, 10, -1, -1, -1, -1, -1, 11, 4, -1, -1, -1, -1, 5, 12, -1, -1, -1, -1, -1, -1, -1, -1, 13, 6, -1, 7, 14, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const int8_t shuffle_C[64] __attribute__((aligned(64))) = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, -1, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, 3, 10, -1, -1, -1, -1, 11, 4, -1, -1, -1, -1, -1, 5, 12, -1, -1, -1, -1, 13, 6, -1, 7, 14, -1, -1, -1, -1, 15, -1, -1, -1 }; static const int8_t shuffle_D[64] __attribute__((aligned(64))) = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 10, 11, 4, -1, -1, -1, -1, -1, 5, 12, 13, 6, -1, 7, 14, 15 }; __m512i result = _mm512_shuffle_epi8(A, _mm512_load_si512((const __m512i*)shuffle_A)); result = _mm512_mask_shuffle_epi8(result, 0x00201b00c3061b08lu, B, _mm512_load_si512((const __m512i*)shuffle_B)); result = _mm512_mask_shuffle_epi8(result, 0x10d860c300d80400lu, C, _mm512_load_si512((const __m512i*)shuffle_C)); result = _mm512_mask_shuffle_epi8(result, 0xef07803c00200000lu, D, _mm512_load_si512((const __m512i*)shuffle_D)); _mm512_storeu_si512((__m512i*)out, result); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include "base/gfx/platform_canvas_win.h" #include "base/gfx/platform_device_win.h" #include "testing/gtest/include/gtest/gtest.h" #include "SkColor.h" namespace gfx { namespace { // Return true if the canvas is filled to canvas_color, // and contains a single rectangle filled to rect_color. bool VerifyRect(const PlatformCanvasWin& canvas, uint32_t canvas_color, uint32_t rect_color, int x, int y, int w, int h) { PlatformDeviceWin& device = canvas.getTopPlatformDevice(); const SkBitmap& bitmap = device.accessBitmap(false); SkAutoLockPixels lock(bitmap); for (int cur_y = 0; cur_y < bitmap.height(); cur_y++) { for (int cur_x = 0; cur_x < bitmap.width(); cur_x++) { if (cur_x >= x && cur_x < x + w && cur_y >= y && cur_y < y + h) { // Inside the square should be rect_color if (*bitmap.getAddr32(cur_x, cur_y) != rect_color) return false; } else { // Outside the square should be canvas_color if (*bitmap.getAddr32(cur_x, cur_y) != canvas_color) return false; } } } return true; } // Checks whether there is a white canvas with a black square at the given // location in pixels (not in the canvas coordinate system). // TODO(ericroman): rename Square to Rect bool VerifyBlackSquare(const PlatformCanvasWin& canvas, int x, int y, int w, int h) { return VerifyRect(canvas, SK_ColorWHITE, SK_ColorBLACK, x, y, w, h); } // Check that every pixel in the canvas is a single color. bool VerifyCanvasColor(const PlatformCanvasWin& canvas, uint32_t canvas_color) { return VerifyRect(canvas, canvas_color, 0, 0, 0, 0, 0); } void DrawGDIRect(PlatformCanvasWin& canvas, int x, int y, int w, int h) { HDC dc = canvas.beginPlatformPaint(); RECT inner_rc; inner_rc.left = x; inner_rc.top = y; inner_rc.right = x + w; inner_rc.bottom = y + h; FillRect(dc, &inner_rc, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH))); canvas.endPlatformPaint(); } // Clips the contents of the canvas to the given rectangle. This will be // intersected with any existing clip. void AddClip(PlatformCanvasWin& canvas, int x, int y, int w, int h) { SkRect rect; rect.set(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w), SkIntToScalar(y + h)); canvas.clipRect(rect); } class LayerSaver { public: LayerSaver(PlatformCanvasWin& canvas, int x, int y, int w, int h) : canvas_(canvas), x_(x), y_(y), w_(w), h_(h) { SkRect bounds; bounds.set(SkIntToScalar(x_), SkIntToScalar(y_), SkIntToScalar(right()), SkIntToScalar(bottom())); canvas_.saveLayer(&bounds, NULL); } ~LayerSaver() { canvas_.getTopPlatformDevice().fixupAlphaBeforeCompositing(); canvas_.restore(); } int x() const { return x_; } int y() const { return y_; } int w() const { return w_; } int h() const { return h_; } // Returns the EXCLUSIVE far bounds of the layer. int right() const { return x_ + w_; } int bottom() const { return y_ + h_; } private: PlatformCanvasWin& canvas_; int x_, y_, w_, h_; }; // Size used for making layers in many of the below tests. const int kLayerX = 2; const int kLayerY = 3; const int kLayerW = 9; const int kLayerH = 7; // Size used by some tests to draw a rectangle inside the layer. const int kInnerX = 4; const int kInnerY = 5; const int kInnerW = 2; const int kInnerH = 3; } // This just checks that our checking code is working properly, it just uses // regular skia primitives. TEST(PlatformCanvasWin, SkLayer) { // Create the canvas initialized to opaque white. PlatformCanvasWin canvas(16, 16, true); canvas.drawColor(SK_ColorWHITE); // Make a layer and fill it completely to make sure that the bounds are // correct. { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.drawColor(SK_ColorBLACK); } EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH)); } // Test the GDI clipping. TEST(PlatformCanvasWin, GDIClipRegion) { // Initialize a white canvas PlatformCanvasWin canvas(16, 16, true); canvas.drawColor(SK_ColorWHITE); EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE)); // Test that initially the canvas has no clip region, by filling it // with a black rectangle. // Note: Don't use LayerSaver, since internally it sets a clip region. DrawGDIRect(canvas, 0, 0, 16, 16); canvas.getTopPlatformDevice().fixupAlphaBeforeCompositing(); EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorBLACK)); // Test that intersecting disjoint clip rectangles sets an empty clip region canvas.drawColor(SK_ColorWHITE); EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE)); { LayerSaver layer(canvas, 0, 0, 16, 16); AddClip(canvas, 2, 3, 4, 5); AddClip(canvas, 4, 9, 10, 10); DrawGDIRect(canvas, 0, 0, 16, 16); } EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE)); } // Test the layers get filled properly by GDI. TEST(PlatformCanvasWin, GDILayer) { // Create the canvas initialized to opaque white. PlatformCanvasWin canvas(16, 16, true); // Make a layer and fill it completely to make sure that the bounds are // correct. canvas.drawColor(SK_ColorWHITE); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawGDIRect(canvas, 0, 0, 100, 100); } EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH)); // Make a layer and fill it partially to make sure the translation is correct. canvas.drawColor(SK_ColorWHITE); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawGDIRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH); } EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH)); // Add a clip on the layer and fill to make sure clip is correct. canvas.drawColor(SK_ColorWHITE); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.save(); AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH); DrawGDIRect(canvas, 0, 0, 100, 100); canvas.restore(); } EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH)); // Add a clip and then make the layer to make sure the clip is correct. canvas.drawColor(SK_ColorWHITE); canvas.save(); AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawGDIRect(canvas, 0, 0, 100, 100); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH)); } // Test that translation + make layer works properly. TEST(PlatformCanvasWin, GDITranslateLayer) { // Create the canvas initialized to opaque white. PlatformCanvasWin canvas(16, 16, true); // Make a layer and fill it completely to make sure that the bounds are // correct. canvas.drawColor(SK_ColorWHITE); canvas.save(); canvas.translate(1, 1); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawGDIRect(canvas, 0, 0, 100, 100); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX + 1, kLayerY + 1, kLayerW, kLayerH)); // Translate then make the layer. canvas.drawColor(SK_ColorWHITE); canvas.save(); canvas.translate(1, 1); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawGDIRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1, kInnerW, kInnerH)); // Make the layer then translate. canvas.drawColor(SK_ColorWHITE); canvas.save(); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.translate(1, 1); DrawGDIRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1, kInnerW, kInnerH)); // Translate both before and after, and have a clip. canvas.drawColor(SK_ColorWHITE); canvas.save(); canvas.translate(1, 1); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.translate(1, 1); AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH); DrawGDIRect(canvas, 0, 0, 100, 100); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 2, kInnerY + 2, kInnerW, kInnerH)); } } // namespace <commit_msg>Update file that got committed under the wrong name, causing the change to get missed. Review URL: http://codereview.chromium.org/1862<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #else #include <unistd.h> #endif #include "base/gfx/platform_canvas.h" #include "base/gfx/platform_device.h" #include "testing/gtest/include/gtest/gtest.h" #include "SkColor.h" namespace gfx { namespace { // Return true if the canvas is filled to canvas_color, // and contains a single rectangle filled to rect_color. bool VerifyRect(const PlatformCanvas& canvas, uint32_t canvas_color, uint32_t rect_color, int x, int y, int w, int h) { PlatformDevice& device = canvas.getTopPlatformDevice(); const SkBitmap& bitmap = device.accessBitmap(false); SkAutoLockPixels lock(bitmap); for (int cur_y = 0; cur_y < bitmap.height(); cur_y++) { for (int cur_x = 0; cur_x < bitmap.width(); cur_x++) { if (cur_x >= x && cur_x < x + w && cur_y >= y && cur_y < y + h) { // Inside the square should be rect_color if (*bitmap.getAddr32(cur_x, cur_y) != rect_color) return false; } else { // Outside the square should be canvas_color if (*bitmap.getAddr32(cur_x, cur_y) != canvas_color) return false; } } } return true; } // Checks whether there is a white canvas with a black square at the given // location in pixels (not in the canvas coordinate system). // TODO(ericroman): rename Square to Rect bool VerifyBlackSquare(const PlatformCanvas& canvas, int x, int y, int w, int h) { return VerifyRect(canvas, SK_ColorWHITE, SK_ColorBLACK, x, y, w, h); } // Check that every pixel in the canvas is a single color. bool VerifyCanvasColor(const PlatformCanvas& canvas, uint32_t canvas_color) { return VerifyRect(canvas, canvas_color, 0, 0, 0, 0, 0); } #if defined(OS_WIN) void DrawNativeRect(const PlatformCanvas& canvas, int x, int y, int w, int h) { HDC dc = canvas.beginPlatformPaint(); RECT inner_rc; inner_rc.left = x; inner_rc.top = y; inner_rc.right = x + w; inner_rc.bottom = y + h; FillRect(dc, &inner_rc, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH))); canvas.endPlatformPaint(); } #elif defined(OS_MACOSX) void DrawNativeRect(const PlatformCanvas& canvas, int x, int y, int w, int h) { CGContextRef context = canvas.beginPlatformPaint(); CGRect inner_rc = CGRectMake(x, y, w, h); CGFloat black[] = { 0.0, 0.0, 0.0, 1.0 }; // RGBA opaque black CGContextSetFillColor(context, black); CGContextFillRect(context, inner_rc); canvas.endPlatformPaint(); } #else void DrawNativeRect(const PlatformCanvas& canvas, int x, int y, int w, int h) { NOTIMPLEMENTED(); } #endif // Clips the contents of the canvas to the given rectangle. This will be // intersected with any existing clip. void AddClip(const PlatformCanvas& canvas, int x, int y, int w, int h) { SkRect rect; rect.set(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w), SkIntToScalar(y + h)); canvas.clipRect(rect); } class LayerSaver { public: LayerSaver(const PlatformCanvas& canvas, int x, int y, int w, int h) : canvas_(canvas), x_(x), y_(y), w_(w), h_(h) { SkRect bounds; bounds.set(SkIntToScalar(x_), SkIntToScalar(y_), SkIntToScalar(right()), SkIntToScalar(bottom())); canvas_.saveLayer(&bounds, NULL); } ~LayerSaver() { canvas_.getTopPlatformDevice().fixupAlphaBeforeCompositing(); canvas_.restore(); } int x() const { return x_; } int y() const { return y_; } int w() const { return w_; } int h() const { return h_; } // Returns the EXCLUSIVE far bounds of the layer. int right() const { return x_ + w_; } int bottom() const { return y_ + h_; } private: const PlatformCanvas& canvas_; int x_, y_, w_, h_; }; // Size used for making layers in many of the below tests. const int kLayerX = 2; const int kLayerY = 3; const int kLayerW = 9; const int kLayerH = 7; // Size used by some tests to draw a rectangle inside the layer. const int kInnerX = 4; const int kInnerY = 5; const int kInnerW = 2; const int kInnerH = 3; } // This just checks that our checking code is working properly, it just uses // regular skia primitives. TEST(PlatformCanvas, SkLayer) { // Create the canvas initialized to opaque white. PlatformCanvas canvas(16, 16, true); canvas.drawColor(SK_ColorWHITE); // Make a layer and fill it completely to make sure that the bounds are // correct. { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.drawColor(SK_ColorBLACK); } EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH)); } // Test native clipping. TEST(PlatformCanvas, ClipRegion) { // Initialize a white canvas PlatformCanvas canvas(16, 16, true); canvas.drawColor(SK_ColorWHITE); EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE)); // Test that initially the canvas has no clip region, by filling it // with a black rectangle. // Note: Don't use LayerSaver, since internally it sets a clip region. DrawNativeRect(canvas, 0, 0, 16, 16); canvas.getTopPlatformDevice().fixupAlphaBeforeCompositing(); EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorBLACK)); // Test that intersecting disjoint clip rectangles sets an empty clip region canvas.drawColor(SK_ColorWHITE); EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE)); { LayerSaver layer(canvas, 0, 0, 16, 16); AddClip(canvas, 2, 3, 4, 5); AddClip(canvas, 4, 9, 10, 10); DrawNativeRect(canvas, 0, 0, 16, 16); } EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE)); } // Test the layers get filled properly by native rendering. TEST(PlatformCanvas, FillLayer) { // Create the canvas initialized to opaque white. PlatformCanvas canvas(16, 16, true); // Make a layer and fill it completely to make sure that the bounds are // correct. canvas.drawColor(SK_ColorWHITE); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawNativeRect(canvas, 0, 0, 100, 100); } EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH)); // Make a layer and fill it partially to make sure the translation is correct. canvas.drawColor(SK_ColorWHITE); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawNativeRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH); } EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH)); // Add a clip on the layer and fill to make sure clip is correct. canvas.drawColor(SK_ColorWHITE); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.save(); AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH); DrawNativeRect(canvas, 0, 0, 100, 100); canvas.restore(); } EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH)); // Add a clip and then make the layer to make sure the clip is correct. canvas.drawColor(SK_ColorWHITE); canvas.save(); AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawNativeRect(canvas, 0, 0, 100, 100); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH)); } // Test that translation + make layer works properly. TEST(PlatformCanvas, TranslateLayer) { // Create the canvas initialized to opaque white. PlatformCanvas canvas(16, 16, true); // Make a layer and fill it completely to make sure that the bounds are // correct. canvas.drawColor(SK_ColorWHITE); canvas.save(); canvas.translate(1, 1); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawNativeRect(canvas, 0, 0, 100, 100); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX + 1, kLayerY + 1, kLayerW, kLayerH)); // Translate then make the layer. canvas.drawColor(SK_ColorWHITE); canvas.save(); canvas.translate(1, 1); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); DrawNativeRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1, kInnerW, kInnerH)); // Make the layer then translate. canvas.drawColor(SK_ColorWHITE); canvas.save(); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.translate(1, 1); DrawNativeRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1, kInnerW, kInnerH)); // Translate both before and after, and have a clip. canvas.drawColor(SK_ColorWHITE); canvas.save(); canvas.translate(1, 1); { LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH); canvas.translate(1, 1); AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH); DrawNativeRect(canvas, 0, 0, 100, 100); } canvas.restore(); EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 2, kInnerY + 2, kInnerW, kInnerH)); } } // namespace <|endoftext|>
<commit_before>/******************************************************************************* * benchmarks/word_count/word_count.cpp * * Runner program for WordCount example. See thrill/examples/word_count.hpp for * the source to the example. * * Part of Project Thrill. * * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <thrill/api/dia.hpp> #include <thrill/thrill.hpp> #include <thrill/common/cmdline_parser.hpp> #include <thrill/common/logger.hpp> using WordCountPair = std::pair<std::string, size_t>; using namespace thrill; // NOLINT int main(int argc, char* argv[]) { common::CmdlineParser clp; clp.SetVerboseProcess(false); std::string input; clp.AddParamString("input", input, "input file pattern"); std::string output; clp.AddParamString("output", output, "output file pattern"); if (!clp.Process(argc, argv)) { return -1; } clp.PrintResult(); auto start_func = [&input, &output](api::Context& ctx) { auto input_dia = ReadLines(ctx, input); std::string word; word.reserve(1024); auto word_pairs = input_dia.template FlatMap<WordCountPair>( [&word](const std::string& line, auto emit) -> void { /* map lambda: emit each word */ word.clear(); for (auto it = line.begin(); it != line.end(); it++) { if(*it == ' ') { emit(WordCountPair(word, 1)); word.clear(); } else { if(*it != ',' && *it != '.') { word.push_back(*it); } } } emit(WordCountPair(word, 1)); }).ReduceBy( [](const WordCountPair& in) -> std::string { /* reduction key: the word string */ return in.first; }, [](const WordCountPair& a, const WordCountPair& b) -> WordCountPair { /* associative reduction operator: add counters */ return WordCountPair(a.first, a.second + b.second); }); word_pairs.Sort([](const WordCountPair& wc1, const WordCountPair& wc2) { return wc1 < wc2; }).Map( [](const WordCountPair& wc) { return wc.first + ": " + std::to_string(wc.second); }).WriteLinesMany(output); }; return api::Run(start_func); } /******************************************************************************/ <commit_msg>sort by word count and not by lexicographical order<commit_after>/******************************************************************************* * benchmarks/word_count/word_count.cpp * * Runner program for WordCount example. See thrill/examples/word_count.hpp for * the source to the example. * * Part of Project Thrill. * * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <thrill/api/dia.hpp> #include <thrill/thrill.hpp> #include <thrill/common/cmdline_parser.hpp> #include <thrill/common/logger.hpp> using WordCountPair = std::pair<std::string, size_t>; using namespace thrill; // NOLINT int main(int argc, char* argv[]) { common::CmdlineParser clp; clp.SetVerboseProcess(false); std::string input; clp.AddParamString("input", input, "input file pattern"); std::string output; clp.AddParamString("output", output, "output file pattern"); if (!clp.Process(argc, argv)) { return -1; } clp.PrintResult(); auto start_func = [&input, &output](api::Context& ctx) { auto input_dia = ReadLines(ctx, input); std::string word; word.reserve(1024); auto word_pairs = input_dia.template FlatMap<WordCountPair>( [&word](const std::string& line, auto emit) -> void { /* map lambda: emit each word */ word.clear(); for (auto it = line.begin(); it != line.end(); it++) { if(*it == ' ') { emit(WordCountPair(word, 1)); word.clear(); } else { if(*it != ',' && *it != '.') { word.push_back(*it); } } } emit(WordCountPair(word, 1)); }).ReduceBy( [](const WordCountPair& in) -> std::string { /* reduction key: the word string */ return in.first; }, [](const WordCountPair& a, const WordCountPair& b) -> WordCountPair { /* associative reduction operator: add counters */ return WordCountPair(a.first, a.second + b.second); }); word_pairs.Sort([](const WordCountPair& wc1, const WordCountPair& wc2) { return wc1.second < wc2.second; }).Map( [](const WordCountPair& wc) { return wc.first + ": " + std::to_string(wc.second); }).WriteLinesMany(output); }; return api::Run(start_func); } /******************************************************************************/ <|endoftext|>
<commit_before>/* mainwindow.cpp * code for the main application window, actions, etc. */ #include <QDesktopServices> #include <QDesktopWidget> #include <QFileDialog> #include <QInputDialog> #include <QMdiArea> #include <QMdiSubWindow> #include <QMessageBox> #include <QPainter> #include <QPrintDialog> #include <QPrinter> #include <QScrollBar> #include <QSignalMapper> #include <QSize> #include <QTabWidget> #include <QThread> #include <QtCore> #include "mainwindow.h" #include "settingsdialog.h" #include "settingsmanager.h" #include "editor.h" #include "ui_mainwindow.h" #include "ui_about.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { /* set the menu bar to work natively for systems with global bars */ menuBar()->setNativeMenuBar(true); /* set up the ui elements for the window */ ui->setupUi(this); /* set the title and icon */ setWindowTitle(tr("Tetra [*]")); setWindowIcon(QIcon(":/icons/resources/icons/logo.svg")); /* set up the key shortcuts for the program */ setupShortcuts(); /* set up the thread and file runner for running programs */ tetraThread = new QThread; fileRunner = new FileRunner(this); mainValue = 0; /* set up the status bar */ statusBar()->showMessage("Ready."); coords = new QLabel(""); statusBar()->addPermanentWidget(coords); updateCoordinates(); /* set the tab bar in "document mode" and give the tab no name */ ui->tabBar->setDocumentMode(true); ui->tabBar->setTabText(0, "Unsaved"); /* set these as disabled (they are enabled dynamically */ ui->actionCut->setEnabled(false); ui->actionCopy->setEnabled(false); ui->actionRedo->setEnabled(false); ui->actionUndo->setEnabled(false); /* set up connections of signals with the current editor */ currentEditor()->setUpConnections(this); qRegisterMetaType<QTextBlock>("QTextBlock"); qRegisterMetaType<QTextCursor>("QTextCursor"); /* set up running so we know when we are done */ connect(fileRunner, SIGNAL(finished()), this, SLOT(exitRunMode())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setupShortcuts() { ui->actionNew->setShortcuts(QKeySequence::New); ui->actionOpen->setShortcuts(QKeySequence::Open); ui->actionSave->setShortcuts(QKeySequence::Save); ui->actionSave_As->setShortcuts(QKeySequence::SaveAs); ui->actionPrint->setShortcuts(QKeySequence::Print); ui->actionClose->setShortcuts(QKeySequence::Close); ui->actionQuit->setShortcuts(QKeySequence::Quit); ui->actionFind->setShortcuts(QKeySequence::Find); ui->actionReplace->setShortcuts(QKeySequence::Replace); ui->actionCut->setShortcuts(QKeySequence::Cut); ui->actionCopy->setShortcuts(QKeySequence::Copy); ui->actionPaste->setShortcuts(QKeySequence::Paste); ui->actionRedo->setShortcuts(QKeySequence::Redo); ui->actionUndo->setShortcuts(QKeySequence::Undo); ui->actionDocumentation->setShortcuts(QKeySequence::HelpContents); } void MainWindow::closeEvent(QCloseEvent* event) { event->ignore(); on_actionQuit_triggered(); } QString MainWindow::getOpenFile() { return currentEditor()->getOpenFile(); } // gives stripped name of file (removes file path) QString MainWindow::strippedName(const QString& fullFileName) { return QFileInfo(fullFileName).fileName(); } /* load an initial file e.g. as an open file */ void MainWindow::doOpen(QString fname) { Editor* newEditor = new Editor; newEditor->setUpConnections(this); if (newEditor->open(fname)) { /* if there is one tab which is empty and not modified, close it first */ if (ui->tabBar->count() == 1 && currentEditor()->isEmpty()) { currentEditor()->close(); ui->tabBar->removeTab(ui->tabBar->currentIndex()); } QFileInfo info(fname); ui->tabBar->addTab(newEditor, info.fileName()); ui->tabBar->setCurrentWidget(newEditor); updateTitle(); } else { QMessageBox warning; warning.setText("Could not open file '" + fname + "'"); warning.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-warning.svg")); warning.exec(); } } void MainWindow::documentWasModified() { if (ui->tabBar->count() == 1) { setWindowModified(currentEditor()->document()->isModified()); } else { updateTitle(); } } void MainWindow::updateCoordinates() { coords->setText(currentEditor()->getCoordinates()); currentEditor()->ensureCursorVisible(); } void MainWindow::on_actionNew_triggered() { Editor* newEditor = new Editor; newEditor->setUpConnections(this); ui->tabBar->addTab(newEditor, "Unsaved"); ui->tabBar->setCurrentWidget(newEditor); updateTitle(); } void MainWindow::on_actionClose_triggered() { if (currentEditor()->document()->isModified()) { QMessageBox msgBox; msgBox.setText("The file has been modified."); msgBox.setInformativeText("Do you want to save your changes?"); msgBox.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-question.svg")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { case QMessageBox::Save: /* try to save, if something goes wrong, bail */ if (!currentEditor()->save()) { return; } break; case QMessageBox::Discard: /* don't save! */ break; case QMessageBox::Cancel: /* bail! */ return; } } /* actually close the editor and tab */ currentEditor()->close(); ui->tabBar->removeTab(ui->tabBar->currentIndex()); /* if that was the last tab, time to leave */ if (ui->tabBar->count() == 0) { QApplication::quit(); } else { updateTitle(); } } void MainWindow::updateTitle() { QString full = currentEditor()->getOpenFile(); QFileInfo info(full); if (full != "") { QString name = info.fileName(); if (currentEditor()->document()->isModified()) { name += "*"; } ui->tabBar->setTabText(ui->tabBar->currentIndex(), name); } if (ui->tabBar->count() == 1) { if (full != "") { setWindowTitle(info.fileName() + " [*]"); } else { setWindowTitle("Tetra [*]"); } setWindowModified(currentEditor()->document()->isModified()); } else { setWindowTitle("Tetra [*]"); } } void MainWindow::on_actionSave_triggered() { if (currentEditor()->save()) { updateTitle(); } } void MainWindow::on_actionSave_As_triggered() { if (currentEditor()->saveas()) { updateTitle(); } } void MainWindow::on_actionOpen_triggered() { QString fname = QFileDialog::getOpenFileName(this, tr("Open File"), "", "Tetra (*.ttr)"); if (fname == "") { return; } doOpen(fname); } int MainWindow::on_actionPrint_triggered() { QPrinter printer; QPrintDialog* dialog = new QPrintDialog(&printer); dialog->setWindowTitle("Print Document"); if (dialog->exec() != QDialog::Accepted) { return -1; } QPainter painter; painter.begin(&printer); QFont f = SettingsManager::font(); painter.setFont(f); painter.drawText(100, 100, 500, 500, Qt::AlignLeft | Qt::AlignTop, currentEditor()->toPlainText()); painter.end(); return 0; } Editor* MainWindow::currentEditor() { return (Editor*)ui->tabBar->currentWidget(); } void MainWindow::on_actionCut_triggered() { currentEditor()->cut(); } void MainWindow::on_actionUndo_triggered() { currentEditor()->undo(); } void MainWindow::on_actionQuit_triggered() { /* if there is one tab only, do a close */ if (ui->tabBar->count() == 1) { on_actionClose_triggered(); } /* check if there are unsaved tabs */ int mod_count = 0; Editor* unsaved = NULL; for (int i = 0; i < ui->tabBar->count(); i++) { Editor* ed = (Editor*) ui->tabBar->widget(i); if (ed->document()->isModified()) { unsaved = ed; mod_count++; } } if (mod_count == 1) { QMessageBox msgBox; msgBox.setText("The file has been modified."); msgBox.setInformativeText("Do you want to save your changes?"); msgBox.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-question.svg")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { case QMessageBox::Save: /* try to save, if something goes wrong, bail */ if (!unsaved->save()) { return; } break; case QMessageBox::Discard: /* don't save! */ break; case QMessageBox::Cancel: /* bail! */ return; } } else if (mod_count > 1) { QMessageBox msgBox; msgBox.setText("Files have been modified."); msgBox.setInformativeText("Do you want to save all changes?"); msgBox.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-question.svg")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { case QMessageBox::Save: for (int i = 0; i < ui->tabBar->count(); i++) { Editor* ed = (Editor*) ui->tabBar->widget(i); if (!ed->save()) { return; } break; } case QMessageBox::Discard: /* don't save! */ break; case QMessageBox::Cancel: /* bail! */ return; } } QApplication::quit(); } void MainWindow::on_actionRedo_triggered() { currentEditor()->redo(); } void MainWindow::on_actionCopy_triggered() { currentEditor()->copy(); } void MainWindow::on_actionPaste_triggered() { currentEditor()->paste(); } void MainWindow::on_actionFind_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } /* help and about functions */ void MainWindow::on_actionAbout_Tetra_triggered() { QDialog* about = new QDialog(0, 0); Ui_About about_ui; about_ui.setupUi(about); about->show(); } void MainWindow::on_actionSettings_triggered() { SettingsDialog* prefs = new SettingsDialog(this); prefs->exec(); /* update the settings of all open editors */ for (int i = 0; i < ui->tabBar->count(); i++) { Editor* ed = (Editor*) ui->tabBar->widget(i); ed->updateSettings(); } /* update the settings for the console */ ui->console->updateSettings(); } void MainWindow::on_actionDocumentation_triggered() { QDesktopServices::openUrl(QUrl("http://tetra-lang.org/ide-reference")); } /* run and debug functions */ void MainWindow::on_actionDebug_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::receiveOutput(QString text) { ui->console->write(text); } void MainWindow::on_actionRun_triggered() { /* if it's not saved, we can't run */ if (currentEditor()->save()) { updateTitle(); } else { return; } /* make sure the bottom dock is shown */ ui->dock->show(); ui->console->document()->setPlainText(""); /* disable run again */ ui->actionRun->setDisabled(true); statusBar()->showMessage("Running."); /* start the worker thread which runs the programs */ fileRunner->moveToThread(tetraThread); tetraThread->start(); QMetaObject::invokeMethod(fileRunner, "runFile", Qt::QueuedConnection, Q_ARG(bool,false)); } /* we were requested to get input from the running program */ void MainWindow::getInput() { bool ok; QString text; do { text = QInputDialog::getText(this, tr("Enter Input"), tr("Enter Input"), QLineEdit::Normal, "", &ok); } while (!ok); qDebug() << "main sees input as " << text << "\n"; fileRunner->receiveInput(text); } /* finish running this */ void MainWindow::exitRunMode(){ tetraThread->wait(); ui->actionRun->setEnabled(true); statusBar()->showMessage("Ready."); } /* debugger functions */ void MainWindow::on_actionStep_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::on_actionContinue_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::on_actionNext_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::on_actionStop_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } <commit_msg>[IDE] squelch ugly debug message<commit_after>/* mainwindow.cpp * code for the main application window, actions, etc. */ #include <QDesktopServices> #include <QDesktopWidget> #include <QFileDialog> #include <QInputDialog> #include <QMdiArea> #include <QMdiSubWindow> #include <QMessageBox> #include <QPainter> #include <QPrintDialog> #include <QPrinter> #include <QScrollBar> #include <QSignalMapper> #include <QSize> #include <QTabWidget> #include <QThread> #include <QtCore> #include "mainwindow.h" #include "settingsdialog.h" #include "settingsmanager.h" #include "editor.h" #include "ui_mainwindow.h" #include "ui_about.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { /* set the menu bar to work natively for systems with global bars */ menuBar()->setNativeMenuBar(true); /* set up the ui elements for the window */ ui->setupUi(this); /* set the title and icon */ setWindowTitle(tr("Tetra [*]")); setWindowIcon(QIcon(":/icons/resources/icons/logo.svg")); /* set up the key shortcuts for the program */ setupShortcuts(); /* set up the thread and file runner for running programs */ tetraThread = new QThread; fileRunner = new FileRunner(this); mainValue = 0; /* set up the status bar */ statusBar()->showMessage("Ready."); coords = new QLabel(""); statusBar()->addPermanentWidget(coords); updateCoordinates(); /* set the tab bar in "document mode" and give the tab no name */ ui->tabBar->setDocumentMode(true); ui->tabBar->setTabText(0, "Unsaved"); /* set these as disabled (they are enabled dynamically */ ui->actionCut->setEnabled(false); ui->actionCopy->setEnabled(false); ui->actionRedo->setEnabled(false); ui->actionUndo->setEnabled(false); /* set up connections of signals with the current editor */ currentEditor()->setUpConnections(this); qRegisterMetaType<QTextBlock>("QTextBlock"); qRegisterMetaType<QTextCursor>("QTextCursor"); /* set up running so we know when we are done */ connect(fileRunner, SIGNAL(finished()), this, SLOT(exitRunMode())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setupShortcuts() { ui->actionNew->setShortcuts(QKeySequence::New); ui->actionOpen->setShortcuts(QKeySequence::Open); ui->actionSave->setShortcuts(QKeySequence::Save); ui->actionSave_As->setShortcuts(QKeySequence::SaveAs); ui->actionPrint->setShortcuts(QKeySequence::Print); ui->actionClose->setShortcuts(QKeySequence::Close); ui->actionQuit->setShortcuts(QKeySequence::Quit); ui->actionFind->setShortcuts(QKeySequence::Find); ui->actionReplace->setShortcuts(QKeySequence::Replace); ui->actionCut->setShortcuts(QKeySequence::Cut); ui->actionCopy->setShortcuts(QKeySequence::Copy); ui->actionPaste->setShortcuts(QKeySequence::Paste); ui->actionRedo->setShortcuts(QKeySequence::Redo); ui->actionUndo->setShortcuts(QKeySequence::Undo); ui->actionDocumentation->setShortcuts(QKeySequence::HelpContents); } void MainWindow::closeEvent(QCloseEvent* event) { event->ignore(); on_actionQuit_triggered(); } QString MainWindow::getOpenFile() { return currentEditor()->getOpenFile(); } // gives stripped name of file (removes file path) QString MainWindow::strippedName(const QString& fullFileName) { return QFileInfo(fullFileName).fileName(); } /* load an initial file e.g. as an open file */ void MainWindow::doOpen(QString fname) { Editor* newEditor = new Editor; newEditor->setUpConnections(this); if (newEditor->open(fname)) { /* if there is one tab which is empty and not modified, close it first */ if (ui->tabBar->count() == 1 && currentEditor()->isEmpty()) { currentEditor()->close(); ui->tabBar->removeTab(ui->tabBar->currentIndex()); } QFileInfo info(fname); ui->tabBar->addTab(newEditor, info.fileName()); ui->tabBar->setCurrentWidget(newEditor); updateTitle(); } else { QMessageBox warning; warning.setText("Could not open file '" + fname + "'"); warning.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-warning.svg")); warning.exec(); } } void MainWindow::documentWasModified() { if (ui->tabBar->count() == 1) { setWindowModified(currentEditor()->document()->isModified()); } else { updateTitle(); } } void MainWindow::updateCoordinates() { coords->setText(currentEditor()->getCoordinates()); currentEditor()->ensureCursorVisible(); } void MainWindow::on_actionNew_triggered() { Editor* newEditor = new Editor; newEditor->setUpConnections(this); ui->tabBar->addTab(newEditor, "Unsaved"); ui->tabBar->setCurrentWidget(newEditor); updateTitle(); } void MainWindow::on_actionClose_triggered() { if (currentEditor()->document()->isModified()) { QMessageBox msgBox; msgBox.setText("The file has been modified."); msgBox.setInformativeText("Do you want to save your changes?"); msgBox.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-question.svg")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { case QMessageBox::Save: /* try to save, if something goes wrong, bail */ if (!currentEditor()->save()) { return; } break; case QMessageBox::Discard: /* don't save! */ break; case QMessageBox::Cancel: /* bail! */ return; } } /* actually close the editor and tab */ currentEditor()->close(); ui->tabBar->removeTab(ui->tabBar->currentIndex()); /* if that was the last tab, time to leave */ if (ui->tabBar->count() == 0) { QApplication::quit(); } else { updateTitle(); } } void MainWindow::updateTitle() { QString full = currentEditor()->getOpenFile(); QFileInfo info(full); if (full != "") { QString name = info.fileName(); if (currentEditor()->document()->isModified()) { name += "*"; } ui->tabBar->setTabText(ui->tabBar->currentIndex(), name); } if (ui->tabBar->count() == 1) { if (full != "") { setWindowTitle(info.fileName() + " [*]"); } else { setWindowTitle("Tetra [*]"); } setWindowModified(currentEditor()->document()->isModified()); } else { setWindowTitle("Tetra [*]"); } } void MainWindow::on_actionSave_triggered() { if (currentEditor()->save()) { updateTitle(); } } void MainWindow::on_actionSave_As_triggered() { if (currentEditor()->saveas()) { updateTitle(); } } void MainWindow::on_actionOpen_triggered() { QString fname = QFileDialog::getOpenFileName(this, tr("Open File"), "", "Tetra (*.ttr)"); if (fname == "") { return; } doOpen(fname); } int MainWindow::on_actionPrint_triggered() { QPrinter printer; QPrintDialog* dialog = new QPrintDialog(&printer); dialog->setWindowTitle("Print Document"); if (dialog->exec() != QDialog::Accepted) { return -1; } QPainter painter; painter.begin(&printer); QFont f = SettingsManager::font(); painter.setFont(f); painter.drawText(100, 100, 500, 500, Qt::AlignLeft | Qt::AlignTop, currentEditor()->toPlainText()); painter.end(); return 0; } Editor* MainWindow::currentEditor() { return (Editor*)ui->tabBar->currentWidget(); } void MainWindow::on_actionCut_triggered() { currentEditor()->cut(); } void MainWindow::on_actionUndo_triggered() { currentEditor()->undo(); } void MainWindow::on_actionQuit_triggered() { /* if there is one tab only, do a close */ if (ui->tabBar->count() == 1) { on_actionClose_triggered(); } /* check if there are unsaved tabs */ int mod_count = 0; Editor* unsaved = NULL; for (int i = 0; i < ui->tabBar->count(); i++) { Editor* ed = (Editor*) ui->tabBar->widget(i); if (ed->document()->isModified()) { unsaved = ed; mod_count++; } } if (mod_count == 1) { QMessageBox msgBox; msgBox.setText("The file has been modified."); msgBox.setInformativeText("Do you want to save your changes?"); msgBox.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-question.svg")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { case QMessageBox::Save: /* try to save, if something goes wrong, bail */ if (!unsaved->save()) { return; } break; case QMessageBox::Discard: /* don't save! */ break; case QMessageBox::Cancel: /* bail! */ return; } } else if (mod_count > 1) { QMessageBox msgBox; msgBox.setText("Files have been modified."); msgBox.setInformativeText("Do you want to save all changes?"); msgBox.setIconPixmap(QPixmap(":/icons/resources/icons/dialog-question.svg")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { case QMessageBox::Save: for (int i = 0; i < ui->tabBar->count(); i++) { Editor* ed = (Editor*) ui->tabBar->widget(i); if (!ed->save()) { return; } break; } case QMessageBox::Discard: /* don't save! */ break; case QMessageBox::Cancel: /* bail! */ return; } } QApplication::quit(); } void MainWindow::on_actionRedo_triggered() { currentEditor()->redo(); } void MainWindow::on_actionCopy_triggered() { currentEditor()->copy(); } void MainWindow::on_actionPaste_triggered() { currentEditor()->paste(); } void MainWindow::on_actionFind_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } /* help and about functions */ void MainWindow::on_actionAbout_Tetra_triggered() { QDialog* about = new QDialog(0, 0); Ui_About about_ui; about_ui.setupUi(about); about->show(); } void MainWindow::on_actionSettings_triggered() { SettingsDialog* prefs = new SettingsDialog(this); prefs->exec(); /* update the settings of all open editors */ for (int i = 0; i < ui->tabBar->count(); i++) { Editor* ed = (Editor*) ui->tabBar->widget(i); ed->updateSettings(); } /* update the settings for the console */ ui->console->updateSettings(); } void MainWindow::on_actionDocumentation_triggered() { QDesktopServices::openUrl(QUrl("http://tetra-lang.org/ide-reference")); } /* run and debug functions */ void MainWindow::on_actionDebug_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::receiveOutput(QString text) { ui->console->write(text); } void MainWindow::on_actionRun_triggered() { /* if it's not saved, we can't run */ if (currentEditor()->save()) { updateTitle(); } else { return; } /* make sure the bottom dock is shown */ ui->dock->show(); ui->console->document()->setPlainText(""); /* disable run again */ ui->actionRun->setDisabled(true); statusBar()->showMessage("Running."); /* start the worker thread which runs the programs */ fileRunner->moveToThread(tetraThread); tetraThread->start(); QMetaObject::invokeMethod(fileRunner, "runFile", Qt::QueuedConnection, Q_ARG(bool,false)); } /* we were requested to get input from the running program */ void MainWindow::getInput() { bool ok; QString text; do { text = QInputDialog::getText(this, tr("Enter Input"), tr("Enter Input"), QLineEdit::Normal, "", &ok); } while (!ok); fileRunner->receiveInput(text); } /* finish running this */ void MainWindow::exitRunMode(){ tetraThread->wait(); ui->actionRun->setEnabled(true); statusBar()->showMessage("Ready."); } /* debugger functions */ void MainWindow::on_actionStep_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::on_actionContinue_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::on_actionNext_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } void MainWindow::on_actionStop_triggered() { QMessageBox msgBox; msgBox.setText("TODO"); msgBox.exec(); } <|endoftext|>
<commit_before>// Copyright (c) 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cassert> #include <sstream> #include "source/spirv_reducer_options.h" #include "reducer.h" #include "reduction_pass.h" namespace spvtools { namespace reduce { struct Reducer::Impl { explicit Impl(spv_target_env env) : target_env(env) {} bool ReachedStepLimit(uint32_t current_step, spv_const_reducer_options options); const spv_target_env target_env; // Target environment. MessageConsumer consumer; // Message consumer. InterestingnessFunction interestingness_function; std::vector<std::unique_ptr<ReductionPass>> passes; }; Reducer::Reducer(spv_target_env env) : impl_(MakeUnique<Impl>(env)) {} Reducer::~Reducer() = default; void Reducer::SetMessageConsumer(MessageConsumer c) { for (auto& pass : impl_->passes) { pass->SetMessageConsumer(c); } impl_->consumer = std::move(c); } void Reducer::SetInterestingnessFunction( Reducer::InterestingnessFunction interestingness_function) { impl_->interestingness_function = std::move(interestingness_function); } Reducer::ReductionResultStatus Reducer::Run( std::vector<uint32_t>&& binary_in, std::vector<uint32_t>* binary_out, spv_const_reducer_options options) const { std::vector<uint32_t> current_binary = binary_in; // Keeps track of how many reduction attempts have been tried. Reduction // bails out if this reaches a given limit. uint32_t reductions_applied = 0; // Initial state should be interesting. if (!impl_->interestingness_function(current_binary, reductions_applied)) { impl_->consumer(SPV_MSG_INFO, nullptr, {}, "Initial state was not interesting; stopping."); return Reducer::ReductionResultStatus::kInitialStateNotInteresting; } // Determines whether, on completing one round of reduction passes, it is // worthwhile trying a further round. bool another_round_worthwhile = true; // Apply round after round of reduction passes until we hit the reduction // step limit, or deem that another round is not going to be worthwhile. while (!impl_->ReachedStepLimit(reductions_applied, options) && another_round_worthwhile) { // At the start of a round of reduction passes, assume another round will // not be worthwhile unless we find evidence to the contrary. another_round_worthwhile = false; // Iterate through the available passes for (auto& pass : impl_->passes) { // Keep applying this pass at its current granularity until it stops // working or we hit the reduction step limit. impl_->consumer(SPV_MSG_INFO, nullptr, {}, ("Trying pass " + pass->GetName() + ".").c_str()); do { auto maybe_result = pass->TryApplyReduction(current_binary); if (maybe_result.empty()) { // This pass did not have any impact, so move on to the next pass. // If this pass hasn't reached its minimum granularity then it's // worth eventually doing another round of reductions, in order to // try this pass at a finer granularity. impl_->consumer( SPV_MSG_INFO, nullptr, {}, ("Pass " + pass->GetName() + " did not make a reduction step.") .c_str()); another_round_worthwhile |= !pass->ReachedMinimumGranularity(); break; } std::stringstream stringstream; reductions_applied++; stringstream << "Pass " << pass->GetName() << " made reduction step " << reductions_applied << "."; impl_->consumer(SPV_MSG_INFO, nullptr, {}, (stringstream.str().c_str())); if (impl_->interestingness_function(maybe_result, reductions_applied)) { // Success! The binary produced by this reduction step is // interesting, so make it the binary of interest henceforth, and // note that it's worth doing another round of reduction passes. impl_->consumer(SPV_MSG_INFO, nullptr, {}, "Reduction step succeeded."); current_binary = std::move(maybe_result); another_round_worthwhile = true; } // Bail out if the reduction step limit has been reached. } while (!impl_->ReachedStepLimit(reductions_applied, options)); } } *binary_out = std::move(current_binary); // Report whether reduction completed, or bailed out early due to reaching // the step limit. if (impl_->ReachedStepLimit(reductions_applied, options)) { impl_->consumer(SPV_MSG_INFO, nullptr, {}, "Reached reduction step limit; stopping."); return Reducer::ReductionResultStatus::kReachedStepLimit; } impl_->consumer(SPV_MSG_INFO, nullptr, {}, "No more to reduce; stopping."); return Reducer::ReductionResultStatus::kComplete; } void Reducer::AddReductionPass( std::unique_ptr<ReductionPass>&& reduction_pass) { impl_->passes.push_back(std::move(reduction_pass)); } bool Reducer::Impl::ReachedStepLimit(uint32_t current_step, spv_const_reducer_options options) { return current_step >= options->step_limit; } } // namespace reduce } // namespace spvtools<commit_msg>Add newline at end of file (#2098)<commit_after>// Copyright (c) 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cassert> #include <sstream> #include "source/spirv_reducer_options.h" #include "reducer.h" #include "reduction_pass.h" namespace spvtools { namespace reduce { struct Reducer::Impl { explicit Impl(spv_target_env env) : target_env(env) {} bool ReachedStepLimit(uint32_t current_step, spv_const_reducer_options options); const spv_target_env target_env; // Target environment. MessageConsumer consumer; // Message consumer. InterestingnessFunction interestingness_function; std::vector<std::unique_ptr<ReductionPass>> passes; }; Reducer::Reducer(spv_target_env env) : impl_(MakeUnique<Impl>(env)) {} Reducer::~Reducer() = default; void Reducer::SetMessageConsumer(MessageConsumer c) { for (auto& pass : impl_->passes) { pass->SetMessageConsumer(c); } impl_->consumer = std::move(c); } void Reducer::SetInterestingnessFunction( Reducer::InterestingnessFunction interestingness_function) { impl_->interestingness_function = std::move(interestingness_function); } Reducer::ReductionResultStatus Reducer::Run( std::vector<uint32_t>&& binary_in, std::vector<uint32_t>* binary_out, spv_const_reducer_options options) const { std::vector<uint32_t> current_binary = binary_in; // Keeps track of how many reduction attempts have been tried. Reduction // bails out if this reaches a given limit. uint32_t reductions_applied = 0; // Initial state should be interesting. if (!impl_->interestingness_function(current_binary, reductions_applied)) { impl_->consumer(SPV_MSG_INFO, nullptr, {}, "Initial state was not interesting; stopping."); return Reducer::ReductionResultStatus::kInitialStateNotInteresting; } // Determines whether, on completing one round of reduction passes, it is // worthwhile trying a further round. bool another_round_worthwhile = true; // Apply round after round of reduction passes until we hit the reduction // step limit, or deem that another round is not going to be worthwhile. while (!impl_->ReachedStepLimit(reductions_applied, options) && another_round_worthwhile) { // At the start of a round of reduction passes, assume another round will // not be worthwhile unless we find evidence to the contrary. another_round_worthwhile = false; // Iterate through the available passes for (auto& pass : impl_->passes) { // Keep applying this pass at its current granularity until it stops // working or we hit the reduction step limit. impl_->consumer(SPV_MSG_INFO, nullptr, {}, ("Trying pass " + pass->GetName() + ".").c_str()); do { auto maybe_result = pass->TryApplyReduction(current_binary); if (maybe_result.empty()) { // This pass did not have any impact, so move on to the next pass. // If this pass hasn't reached its minimum granularity then it's // worth eventually doing another round of reductions, in order to // try this pass at a finer granularity. impl_->consumer( SPV_MSG_INFO, nullptr, {}, ("Pass " + pass->GetName() + " did not make a reduction step.") .c_str()); another_round_worthwhile |= !pass->ReachedMinimumGranularity(); break; } std::stringstream stringstream; reductions_applied++; stringstream << "Pass " << pass->GetName() << " made reduction step " << reductions_applied << "."; impl_->consumer(SPV_MSG_INFO, nullptr, {}, (stringstream.str().c_str())); if (impl_->interestingness_function(maybe_result, reductions_applied)) { // Success! The binary produced by this reduction step is // interesting, so make it the binary of interest henceforth, and // note that it's worth doing another round of reduction passes. impl_->consumer(SPV_MSG_INFO, nullptr, {}, "Reduction step succeeded."); current_binary = std::move(maybe_result); another_round_worthwhile = true; } // Bail out if the reduction step limit has been reached. } while (!impl_->ReachedStepLimit(reductions_applied, options)); } } *binary_out = std::move(current_binary); // Report whether reduction completed, or bailed out early due to reaching // the step limit. if (impl_->ReachedStepLimit(reductions_applied, options)) { impl_->consumer(SPV_MSG_INFO, nullptr, {}, "Reached reduction step limit; stopping."); return Reducer::ReductionResultStatus::kReachedStepLimit; } impl_->consumer(SPV_MSG_INFO, nullptr, {}, "No more to reduce; stopping."); return Reducer::ReductionResultStatus::kComplete; } void Reducer::AddReductionPass( std::unique_ptr<ReductionPass>&& reduction_pass) { impl_->passes.push_back(std::move(reduction_pass)); } bool Reducer::Impl::ReachedStepLimit(uint32_t current_step, spv_const_reducer_options options) { return current_step >= options->step_limit; } } // namespace reduce } // namespace spvtools <|endoftext|>
<commit_before>#include "syntaxanalyzer.h" #include "lexicalanalyzer.h" #include <QMetaType> SyntaxAnalyzer::SyntaxAnalyzer(QObject *parent) : QObject(parent), m_lexicalAnalyzer(new LexicalAnalyzer(this)), m_exprCalculator(new ExprCalculator(this)) { } SyntaxAnalyzer::~SyntaxAnalyzer() { } QString SyntaxAnalyzer::process(const QString &input) { // perform lexical analyzis m_lexicalAnalyzer->parse(input); if (m_lexicalAnalyzer->lexeme().type == LexemeEol) { throw Exception(tr("Input is empty")); } // Process the command: const declaration, const function or expression return command(); } // Command = ConstDeclaration | Expression | FuncDeclaration QString SyntaxAnalyzer::command() { QString result; // const declaration if (m_lexicalAnalyzer->lexeme().type == LexemeConst) { result = constDeclaration(); // result here is just a notification ensureNoMoreLexemes(); } // func declaration else if (m_lexicalAnalyzer->lexeme().type == LexemeFunc) { result = functionDeclaration(); // result here is a notification too ensureNoMoreLexemes(); } // expression else { RpnCodeThread codeThread = expression(); // convert expression to RPN ensureNoMoreLexemes(); result = QString::number(m_exprCalculator->calculate(codeThread), 'f', 15); // calculate } return result; } // ConstDeclaration = 'const' Identifier '=' {Unary Op} Number QString SyntaxAnalyzer::constDeclaration() { // 'const' if (m_lexicalAnalyzer->lexeme().type != LexemeConst) { throw Exception(tr("Illegal constant declaration beginning")); } m_lexicalAnalyzer->nextLexeme(); // Identifier if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Identifier after ‘const’ expected")); } QString constName = m_lexicalAnalyzer->lexeme().value; m_lexicalAnalyzer->nextLexeme(); // '=' if (m_lexicalAnalyzer->lexeme().type != LexemeEqual) { throw Exception(tr("Sign ‘=’ expected after identifier")); } m_lexicalAnalyzer->nextLexeme(); // {UnaryOp} int signMultiplyer = 1; while (CheckLexeme::isUnaryOperation(m_lexicalAnalyzer->lexeme())) { if (m_lexicalAnalyzer->lexeme().type == LexemeMinus) { signMultiplyer *= -1; } m_lexicalAnalyzer->nextLexeme(); } // Number if (m_lexicalAnalyzer->lexeme().type != LexemeNumber) { throw Exception(tr("Number after ‘=’ expected")); } Number constValue = number(); m_lexicalAnalyzer->nextLexeme(); // add constant to list m_exprCalculator->addConstant(constName, constValue); // return notification return tr("Constant ‘%1’ now means ‘%2’").arg(constName).arg(constValue); } // FunctionDeclaration = 'func' Indenifier '(' FormalArgument // { ',' FormalArgument} ')' '=' Expression QString SyntaxAnalyzer::functionDeclaration() { /* Get function name */ // 'func' if (m_lexicalAnalyzer->lexeme().type != LexemeFunc) { throw Exception(tr("Illegal function declaration beginning")); } m_lexicalAnalyzer->nextLexeme(); // identifier if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Identifier after ‘func’ expected")); } QString functionName = m_lexicalAnalyzer->lexeme().value; m_lexicalAnalyzer->nextLexeme(); /* Get formal arguments and save them to list */ if (m_lexicalAnalyzer->lexeme().type != LexemeOpeningBracket) { throw Exception(tr("Opening bracket expected after function name")); } do { m_lexicalAnalyzer->nextLexeme(); extractFormalArgument(); } while (m_lexicalAnalyzer->lexeme().type == LexemeComma); if (m_lexicalAnalyzer->lexeme().type != LexemeClosingBracket) { throw Exception(tr("Closing bracket expected after formal arguments list")); } m_lexicalAnalyzer->nextLexeme(); if (m_lexicalAnalyzer->lexeme().type != LexemeEqual) { throw Exception(tr("Equal sign expected after closing bracket")); } m_lexicalAnalyzer->nextLexeme(); /* Parse the function body and save it */ RpnFunction function; function.argumentsCount = m_workingParams.count(); function.codeThread = expression(); m_workingParams.clear(); m_exprCalculator->addFunction(functionName, function); return tr("Function ‘%1’ is declared").arg(functionName); } // Expression = Summand {SummOperator Summand} RpnCodeThread SyntaxAnalyzer::expression() { /* Note, that exception will be thrown in factor(), multOperation(), etc if something's wrong. */ RpnCodeThread result; // first obligatory summand RpnCodeThread operand = summand(); result << operand; // {SummOperator Summand} section while (CheckLexeme::isSummOperation(m_lexicalAnalyzer->lexeme())) { RpnElement operation = summOperation(); operand = summand(); result << operand << operation; } return result; } // Function = Identifier'(' ActualArgument{ ',' ActualArgument}')' RpnCodeThread SyntaxAnalyzer::function() { RpnCodeThread result; // Get function name and ensure it is built in or user defined if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Function name expected")); } QString functionName = m_lexicalAnalyzer->lexeme().value; int formalArgumentsCount; if (m_exprCalculator->isFunction(functionName)) { formalArgumentsCount = m_exprCalculator->functionArgumentsCount(functionName); } else { throw Exception(tr("Undeclared function ‘%1’ call").arg(functionName)); } m_lexicalAnalyzer->nextLexeme(); if (m_lexicalAnalyzer->lexeme().type != LexemeOpeningBracket) { throw Exception(tr("Opening bracket expected")); } // Parse actual arguments and add them to tread. // Ensure their count equals formal arguments count int actualArgumentsCount = 0; do { m_lexicalAnalyzer->nextLexeme(); result << expression(); actualArgumentsCount++; if (actualArgumentsCount > formalArgumentsCount) { throw Exception(tr("Too many arguments in ‘%1’ function call").arg(functionName)); } } while (m_lexicalAnalyzer->lexeme().type == LexemeComma); if (actualArgumentsCount != formalArgumentsCount) { throw Exception(tr("Not enough arguments in ‘%1’ function call").arg(functionName)); } if (m_lexicalAnalyzer->lexeme().type != LexemeClosingBracket) { throw Exception(tr("Closing bracket expected")); } m_lexicalAnalyzer->nextLexeme(); // Add to thread a function call element RpnElement functionCall; functionCall.type = RpnElementFunction; functionCall.value = functionName; result << functionCall; return result; } // Factor = (UnaryOp Factor) | (PowerBase ['^' Factor]) RpnCodeThread SyntaxAnalyzer::factor() { RpnCodeThread result; // UnaryOp Factor if (CheckLexeme::isUnaryOperation(m_lexicalAnalyzer->lexeme())) { if (m_lexicalAnalyzer->lexeme().type == LexemeMinus) { m_lexicalAnalyzer->nextLexeme(); // -A = (-1) * A RpnElement minusOne = {RpnElementOperand, -1}; RpnElement multiply = {RpnElementFunction, QVariant::fromValue(RpnFunctionMultiply)}; RpnCodeThread rightOperand = factor(); result << minusOne << rightOperand << multiply; } else if (m_lexicalAnalyzer->lexeme().type == LexemePlus) { m_lexicalAnalyzer->nextLexeme(); result = factor(); } else { throw Exception(tr("Unsupported unary operation")); } } else { RpnCodeThread base = powerBase(); result << base; // ['^' Factor] if (m_lexicalAnalyzer->lexeme().type == LexemePower) { RpnElement power = {RpnElementFunction, QVariant::fromValue(RpnFunctionPower)}; m_lexicalAnalyzer->nextLexeme(); RpnCodeThread exponent = factor(); result << exponent << power; } } return result; } // PowerBase = Number | Constant | Function | '('Expression')' RpnCodeThread SyntaxAnalyzer::powerBase() { RpnCodeThread result; // Number if (m_lexicalAnalyzer->lexeme().type == LexemeNumber) { Number value = number(); RpnElement element = {RpnElementOperand, value}; result << element; } // Constant | Function else if (m_lexicalAnalyzer->lexeme().type == LexemeIdentifier) { // Constant m_lexicalAnalyzer->nextLexeme(); if (m_lexicalAnalyzer->lexeme().type != LexemeOpeningBracket) { m_lexicalAnalyzer->previousLexeme(); RpnElement element = constant(); result << element; } // Function else { m_lexicalAnalyzer->previousLexeme(); RpnCodeThread thread = function(); result << thread; } } // '('Expression')' else if (m_lexicalAnalyzer->lexeme().type == LexemeOpeningBracket) { m_lexicalAnalyzer->nextLexeme(); result = expression(); if (m_lexicalAnalyzer->lexeme().type != LexemeClosingBracket) { throw Exception(tr("Closing bracket expected")); } m_lexicalAnalyzer->nextLexeme(); } else { throw Exception(tr("Number or expression in brackets expected")); } return result; } // MultOperation = '*' | '/' RpnElement SyntaxAnalyzer::multOperation() { RpnElement result; result.type = RpnElementFunction; if (m_lexicalAnalyzer->lexeme().type == LexemeMultiply) { result.value.setValue(RpnFunctionMultiply); } else if(m_lexicalAnalyzer->lexeme().type == LexemeDivide) { result.value.setValue(RpnFunctionDivide); } else { throw Exception(tr("Multiplication operator expected")); } m_lexicalAnalyzer->nextLexeme(); return result; } // Summand = Factor {MultOperator Factor} RpnCodeThread SyntaxAnalyzer::summand() { RpnCodeThread result; // first obligatory factor RpnCodeThread operand = factor(); result << operand; // {MultOperation Factor} section while (CheckLexeme::isMultOperation(m_lexicalAnalyzer->lexeme())) { RpnElement operation = multOperation(); operand = factor(); result << operand << operation; } return result; } // SummOperation = '+' | '-' RpnElement SyntaxAnalyzer::summOperation() { RpnElement result; result.type = RpnElementFunction; if (m_lexicalAnalyzer->lexeme().type == LexemePlus) { result.value.setValue(RpnFunctionPlus); } else if(m_lexicalAnalyzer->lexeme().type == LexemeMinus) { result.value.setValue(RpnFunctionMinus); } else { throw Exception(tr("Summation operator expected")); } m_lexicalAnalyzer->nextLexeme(); return result; } Number SyntaxAnalyzer::number() { bool ok = false; Number result = m_lexicalAnalyzer->lexeme().value.toDouble(&ok); if (!ok) { throw Exception(tr("Cannot convert ‘%1’ to a number").arg(m_lexicalAnalyzer->lexeme().value)); } m_lexicalAnalyzer->nextLexeme(); return result; } // Constant = Identifier (formal arguments are processed here as well) RpnElement SyntaxAnalyzer::constant() { RpnElement result; QString constName = m_lexicalAnalyzer->lexeme().value; if (m_workingParams.contains(constName)) { // it is an argument result.type = RpnElementParam; result.value = m_workingParams.indexOf(constName); } else if (m_exprCalculator->isConstant(constName)) { result.type = RpnElementConstant; result.value = constName; } else { throw Exception(tr("Undeclared identifier ‘%1’").arg(constName)); } m_lexicalAnalyzer->nextLexeme(); return result; } // FormalArgument = Identifier void SyntaxAnalyzer::extractFormalArgument() { if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Identifier expected if argument list")); } QString argumentName = m_lexicalAnalyzer->lexeme().value; if (m_workingParams.contains(argumentName)) { throw Exception(tr("Argument ‘%1’ is already in the list").arg(argumentName)); } m_workingParams.append(argumentName); m_lexicalAnalyzer->nextLexeme(); } void SyntaxAnalyzer::ensureNoMoreLexemes() { if (m_lexicalAnalyzer->lexeme().type != LexemeEol) { throw Exception(tr("End of file expected")); } } bool CheckLexeme::isMultOperation(Lexeme lexeme) { return ((lexeme.type == LexemeMultiply) || (lexeme.type == LexemeDivide)); } bool CheckLexeme::isSummOperation(Lexeme lexeme) { return ((lexeme.type == LexemePlus) || (lexeme.type == LexemeMinus)); } bool CheckLexeme::isUnaryOperation(Lexeme lexeme) { return ((lexeme.type == LexemePlus) || (lexeme.type == LexemeMinus)); } <commit_msg>Constant expression can be now assigned to a constant, not just a number. In this way a constant can be even redeclared in such a way: const smth = smth/pi + 4. Certainly we assume that 'smth' was declared before.<commit_after>#include "syntaxanalyzer.h" #include "lexicalanalyzer.h" #include <QMetaType> SyntaxAnalyzer::SyntaxAnalyzer(QObject *parent) : QObject(parent), m_lexicalAnalyzer(new LexicalAnalyzer(this)), m_exprCalculator(new ExprCalculator(this)) { } SyntaxAnalyzer::~SyntaxAnalyzer() { } QString SyntaxAnalyzer::process(const QString &input) { // perform lexical analyzis m_lexicalAnalyzer->parse(input); if (m_lexicalAnalyzer->lexeme().type == LexemeEol) { throw Exception(tr("Input is empty")); } // Process the command: const declaration, const function or expression return command(); } // Command = ConstDeclaration | Expression | FuncDeclaration QString SyntaxAnalyzer::command() { QString result; // const declaration if (m_lexicalAnalyzer->lexeme().type == LexemeConst) { result = constDeclaration(); // result here is just a notification ensureNoMoreLexemes(); } // func declaration else if (m_lexicalAnalyzer->lexeme().type == LexemeFunc) { result = functionDeclaration(); // result here is a notification too ensureNoMoreLexemes(); } // expression else { RpnCodeThread codeThread = expression(); // convert expression to RPN ensureNoMoreLexemes(); result = QString::number(m_exprCalculator->calculate(codeThread), 'f', 15); // calculate } return result; } // ConstDeclaration = 'const' Identifier '=' Expression QString SyntaxAnalyzer::constDeclaration() { // 'const' if (m_lexicalAnalyzer->lexeme().type != LexemeConst) { throw Exception(tr("Illegal constant declaration beginning")); } m_lexicalAnalyzer->nextLexeme(); // Identifier if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Identifier after ‘const’ expected")); } QString constName = m_lexicalAnalyzer->lexeme().value; m_lexicalAnalyzer->nextLexeme(); // '=' if (m_lexicalAnalyzer->lexeme().type != LexemeEqual) { throw Exception(tr("Sign ‘=’ expected after identifier")); } m_lexicalAnalyzer->nextLexeme(); // Expression RpnCodeThread constThread = expression(); Number constValue = m_exprCalculator->calculate(constThread); m_lexicalAnalyzer->nextLexeme(); // add constant to list m_exprCalculator->addConstant(constName, constValue); // return notification return tr("Constant ‘%1’ now means ‘%2’").arg(constName).arg(constValue); } // FunctionDeclaration = 'func' Indenifier '(' FormalArgument // { ',' FormalArgument} ')' '=' Expression QString SyntaxAnalyzer::functionDeclaration() { /* Get function name */ // 'func' if (m_lexicalAnalyzer->lexeme().type != LexemeFunc) { throw Exception(tr("Illegal function declaration beginning")); } m_lexicalAnalyzer->nextLexeme(); // identifier if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Identifier after ‘func’ expected")); } QString functionName = m_lexicalAnalyzer->lexeme().value; m_lexicalAnalyzer->nextLexeme(); /* Get formal arguments and save them to list */ if (m_lexicalAnalyzer->lexeme().type != LexemeOpeningBracket) { throw Exception(tr("Opening bracket expected after function name")); } do { m_lexicalAnalyzer->nextLexeme(); extractFormalArgument(); } while (m_lexicalAnalyzer->lexeme().type == LexemeComma); if (m_lexicalAnalyzer->lexeme().type != LexemeClosingBracket) { throw Exception(tr("Closing bracket expected after formal arguments list")); } m_lexicalAnalyzer->nextLexeme(); if (m_lexicalAnalyzer->lexeme().type != LexemeEqual) { throw Exception(tr("Equal sign expected after closing bracket")); } m_lexicalAnalyzer->nextLexeme(); /* Parse the function body and save it */ RpnFunction function; function.argumentsCount = m_workingParams.count(); function.codeThread = expression(); m_workingParams.clear(); m_exprCalculator->addFunction(functionName, function); return tr("Function ‘%1’ is declared").arg(functionName); } // Expression = Summand {SummOperator Summand} RpnCodeThread SyntaxAnalyzer::expression() { /* Note, that exception will be thrown in factor(), multOperation(), etc if something's wrong. */ RpnCodeThread result; // first obligatory summand RpnCodeThread operand = summand(); result << operand; // {SummOperator Summand} section while (CheckLexeme::isSummOperation(m_lexicalAnalyzer->lexeme())) { RpnElement operation = summOperation(); operand = summand(); result << operand << operation; } return result; } // Function = Identifier'(' ActualArgument{ ',' ActualArgument}')' RpnCodeThread SyntaxAnalyzer::function() { RpnCodeThread result; // Get function name and ensure it is built in or user defined if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Function name expected")); } QString functionName = m_lexicalAnalyzer->lexeme().value; int formalArgumentsCount; if (m_exprCalculator->isFunction(functionName)) { formalArgumentsCount = m_exprCalculator->functionArgumentsCount(functionName); } else { throw Exception(tr("Undeclared function ‘%1’ call").arg(functionName)); } m_lexicalAnalyzer->nextLexeme(); if (m_lexicalAnalyzer->lexeme().type != LexemeOpeningBracket) { throw Exception(tr("Opening bracket expected")); } // Parse actual arguments and add them to tread. // Ensure their count equals formal arguments count int actualArgumentsCount = 0; do { m_lexicalAnalyzer->nextLexeme(); result << expression(); actualArgumentsCount++; if (actualArgumentsCount > formalArgumentsCount) { throw Exception(tr("Too many arguments in ‘%1’ function call").arg(functionName)); } } while (m_lexicalAnalyzer->lexeme().type == LexemeComma); if (actualArgumentsCount != formalArgumentsCount) { throw Exception(tr("Not enough arguments in ‘%1’ function call").arg(functionName)); } if (m_lexicalAnalyzer->lexeme().type != LexemeClosingBracket) { throw Exception(tr("Closing bracket expected")); } m_lexicalAnalyzer->nextLexeme(); // Add to thread a function call element RpnElement functionCall; functionCall.type = RpnElementFunction; functionCall.value = functionName; result << functionCall; return result; } // Factor = (UnaryOp Factor) | (PowerBase ['^' Factor]) RpnCodeThread SyntaxAnalyzer::factor() { RpnCodeThread result; // UnaryOp Factor if (CheckLexeme::isUnaryOperation(m_lexicalAnalyzer->lexeme())) { if (m_lexicalAnalyzer->lexeme().type == LexemeMinus) { m_lexicalAnalyzer->nextLexeme(); // -A = (-1) * A RpnElement minusOne = {RpnElementOperand, -1}; RpnElement multiply = {RpnElementFunction, QVariant::fromValue(RpnFunctionMultiply)}; RpnCodeThread rightOperand = factor(); result << minusOne << rightOperand << multiply; } else if (m_lexicalAnalyzer->lexeme().type == LexemePlus) { m_lexicalAnalyzer->nextLexeme(); result = factor(); } else { throw Exception(tr("Unsupported unary operation")); } } else { RpnCodeThread base = powerBase(); result << base; // ['^' Factor] if (m_lexicalAnalyzer->lexeme().type == LexemePower) { RpnElement power = {RpnElementFunction, QVariant::fromValue(RpnFunctionPower)}; m_lexicalAnalyzer->nextLexeme(); RpnCodeThread exponent = factor(); result << exponent << power; } } return result; } // PowerBase = Number | Constant | Function | '('Expression')' RpnCodeThread SyntaxAnalyzer::powerBase() { RpnCodeThread result; // Number if (m_lexicalAnalyzer->lexeme().type == LexemeNumber) { Number value = number(); RpnElement element = {RpnElementOperand, value}; result << element; } // Constant | Function else if (m_lexicalAnalyzer->lexeme().type == LexemeIdentifier) { // Constant m_lexicalAnalyzer->nextLexeme(); if (m_lexicalAnalyzer->lexeme().type != LexemeOpeningBracket) { m_lexicalAnalyzer->previousLexeme(); RpnElement element = constant(); result << element; } // Function else { m_lexicalAnalyzer->previousLexeme(); RpnCodeThread thread = function(); result << thread; } } // '('Expression')' else if (m_lexicalAnalyzer->lexeme().type == LexemeOpeningBracket) { m_lexicalAnalyzer->nextLexeme(); result = expression(); if (m_lexicalAnalyzer->lexeme().type != LexemeClosingBracket) { throw Exception(tr("Closing bracket expected")); } m_lexicalAnalyzer->nextLexeme(); } else { throw Exception(tr("Number or expression in brackets expected")); } return result; } // MultOperation = '*' | '/' RpnElement SyntaxAnalyzer::multOperation() { RpnElement result; result.type = RpnElementFunction; if (m_lexicalAnalyzer->lexeme().type == LexemeMultiply) { result.value.setValue(RpnFunctionMultiply); } else if(m_lexicalAnalyzer->lexeme().type == LexemeDivide) { result.value.setValue(RpnFunctionDivide); } else { throw Exception(tr("Multiplication operator expected")); } m_lexicalAnalyzer->nextLexeme(); return result; } // Summand = Factor {MultOperator Factor} RpnCodeThread SyntaxAnalyzer::summand() { RpnCodeThread result; // first obligatory factor RpnCodeThread operand = factor(); result << operand; // {MultOperation Factor} section while (CheckLexeme::isMultOperation(m_lexicalAnalyzer->lexeme())) { RpnElement operation = multOperation(); operand = factor(); result << operand << operation; } return result; } // SummOperation = '+' | '-' RpnElement SyntaxAnalyzer::summOperation() { RpnElement result; result.type = RpnElementFunction; if (m_lexicalAnalyzer->lexeme().type == LexemePlus) { result.value.setValue(RpnFunctionPlus); } else if(m_lexicalAnalyzer->lexeme().type == LexemeMinus) { result.value.setValue(RpnFunctionMinus); } else { throw Exception(tr("Summation operator expected")); } m_lexicalAnalyzer->nextLexeme(); return result; } Number SyntaxAnalyzer::number() { bool ok = false; Number result = m_lexicalAnalyzer->lexeme().value.toDouble(&ok); if (!ok) { throw Exception(tr("Cannot convert ‘%1’ to a number").arg(m_lexicalAnalyzer->lexeme().value)); } m_lexicalAnalyzer->nextLexeme(); return result; } // Constant = Identifier (formal arguments are processed here as well) RpnElement SyntaxAnalyzer::constant() { RpnElement result; QString constName = m_lexicalAnalyzer->lexeme().value; // it is a formal argument if (m_workingParams.contains(constName)) { result.type = RpnElementParam; result.value = m_workingParams.indexOf(constName); } // it is a constant else if (m_exprCalculator->isConstant(constName)) { result.type = RpnElementConstant; result.value = constName; } else { throw Exception(tr("Undeclared identifier ‘%1’").arg(constName)); } m_lexicalAnalyzer->nextLexeme(); return result; } // FormalArgument = Identifier void SyntaxAnalyzer::extractFormalArgument() { if (m_lexicalAnalyzer->lexeme().type != LexemeIdentifier) { throw Exception(tr("Identifier expected if argument list")); } QString argumentName = m_lexicalAnalyzer->lexeme().value; if (m_workingParams.contains(argumentName)) { throw Exception(tr("Argument ‘%1’ is already in the list").arg(argumentName)); } m_workingParams.append(argumentName); m_lexicalAnalyzer->nextLexeme(); } void SyntaxAnalyzer::ensureNoMoreLexemes() { if (m_lexicalAnalyzer->lexeme().type != LexemeEol) { throw Exception(tr("End of file expected")); } } bool CheckLexeme::isMultOperation(Lexeme lexeme) { return ((lexeme.type == LexemeMultiply) || (lexeme.type == LexemeDivide)); } bool CheckLexeme::isSummOperation(Lexeme lexeme) { return ((lexeme.type == LexemePlus) || (lexeme.type == LexemeMinus)); } bool CheckLexeme::isUnaryOperation(Lexeme lexeme) { return ((lexeme.type == LexemePlus) || (lexeme.type == LexemeMinus)); } <|endoftext|>
<commit_before>// stdafx.cpp : source file that includes just the standard includes // Scrub Cup Work.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file <commit_msg>Delete stdafx.cpp<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "XMLIndexBibliographyEntryContext.hxx" #include "XMLIndexTemplateContext.hxx" #include <xmloff/xmlictxt.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/txtimp.hxx> #include <xmloff/nmspmap.hxx> #include "xmloff/xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmluconv.hxx> #include <com/sun/star/text/BibliographyDataField.hpp> using namespace ::com::sun::star::text; using namespace ::xmloff::token; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; const sal_Char sAPI_TokenType[] = "TokenType"; const sal_Char sAPI_CharacterStyleName[] = "CharacterStyleName"; TYPEINIT1( XMLIndexBibliographyEntryContext, XMLIndexSimpleEntryContext); XMLIndexBibliographyEntryContext::XMLIndexBibliographyEntryContext( SvXMLImport& rImport, XMLIndexTemplateContext& rTemplate, sal_uInt16 nPrfx, const OUString& rLocalName ) : XMLIndexSimpleEntryContext(rImport, rTemplate.sTokenBibliographyDataField, rTemplate, nPrfx, rLocalName), nBibliographyInfo(BibliographyDataField::IDENTIFIER), bBibliographyInfoOK(sal_False) { } XMLIndexBibliographyEntryContext::~XMLIndexBibliographyEntryContext() { } const SvXMLEnumMapEntry aBibliographyDataFieldMap[] = { { XML_ADDRESS, BibliographyDataField::ADDRESS }, { XML_ANNOTE, BibliographyDataField::ANNOTE }, { XML_AUTHOR, BibliographyDataField::AUTHOR }, { XML_BIBLIOGRAPHY_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, // #96658#: also read old documents (bib*i*liographic...) { XML_BIBILIOGRAPHIC_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, { XML_BOOKTITLE, BibliographyDataField::BOOKTITLE }, { XML_CHAPTER, BibliographyDataField::CHAPTER }, { XML_CUSTOM1, BibliographyDataField::CUSTOM1 }, { XML_CUSTOM2, BibliographyDataField::CUSTOM2 }, { XML_CUSTOM3, BibliographyDataField::CUSTOM3 }, { XML_CUSTOM4, BibliographyDataField::CUSTOM4 }, { XML_CUSTOM5, BibliographyDataField::CUSTOM5 }, { XML_EDITION, BibliographyDataField::EDITION }, { XML_EDITOR, BibliographyDataField::EDITOR }, { XML_HOWPUBLISHED, BibliographyDataField::HOWPUBLISHED }, { XML_IDENTIFIER, BibliographyDataField::IDENTIFIER }, { XML_INSTITUTION, BibliographyDataField::INSTITUTION }, { XML_ISBN, BibliographyDataField::ISBN }, { XML_JOURNAL, BibliographyDataField::JOURNAL }, { XML_MONTH, BibliographyDataField::MONTH }, { XML_NOTE, BibliographyDataField::NOTE }, { XML_NUMBER, BibliographyDataField::NUMBER }, { XML_ORGANIZATIONS, BibliographyDataField::ORGANIZATIONS }, { XML_PAGES, BibliographyDataField::PAGES }, { XML_PUBLISHER, BibliographyDataField::PUBLISHER }, { XML_REPORT_TYPE, BibliographyDataField::REPORT_TYPE }, { XML_SCHOOL, BibliographyDataField::SCHOOL }, { XML_SERIES, BibliographyDataField::SERIES }, { XML_TITLE, BibliographyDataField::TITLE }, { XML_URL, BibliographyDataField::URL }, { XML_VOLUME, BibliographyDataField::VOLUME }, { XML_YEAR, BibliographyDataField::YEAR }, { XML_TOKEN_INVALID, 0 } }; void XMLIndexBibliographyEntryContext::StartElement( const Reference<XAttributeList> & xAttrList) { // handle both, style name and bibliography info sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (XML_NAMESPACE_TEXT == nPrefix) { if ( IsXMLToken( sLocalName, XML_STYLE_NAME ) ) { sCharStyleName = xAttrList->getValueByIndex(nAttr); bCharStyleNameOK = sal_True; } else if ( IsXMLToken( sLocalName, XML_BIBLIOGRAPHY_DATA_FIELD ) ) { sal_uInt16 nTmp; if (SvXMLUnitConverter::convertEnum( nTmp, xAttrList->getValueByIndex(nAttr), aBibliographyDataFieldMap)) { nBibliographyInfo = nTmp; bBibliographyInfoOK = sal_True; } } } } // if we have a style name, set it! if (bCharStyleNameOK) { nValues++; } // always bibliography; else element is not valid nValues++; } void XMLIndexBibliographyEntryContext::EndElement() { // only valid, if we have bibliography info if (bBibliographyInfoOK) { XMLIndexSimpleEntryContext::EndElement(); } } void XMLIndexBibliographyEntryContext::FillPropertyValues( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rValues) { // entry name and (optionally) style name in parent class XMLIndexSimpleEntryContext::FillPropertyValues(rValues); // bibliography data field sal_Int32 nIndex = bCharStyleNameOK ? 2 : 1; rValues[nIndex].Name = rTemplateContext.sBibliographyDataField; Any aAny; aAny <<= nBibliographyInfo; rValues[nIndex].Value = aAny; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>-Werror,-Wunused-const-variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "XMLIndexBibliographyEntryContext.hxx" #include "XMLIndexTemplateContext.hxx" #include <xmloff/xmlictxt.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/txtimp.hxx> #include <xmloff/nmspmap.hxx> #include "xmloff/xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmluconv.hxx> #include <com/sun/star/text/BibliographyDataField.hpp> using namespace ::com::sun::star::text; using namespace ::xmloff::token; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; TYPEINIT1( XMLIndexBibliographyEntryContext, XMLIndexSimpleEntryContext); XMLIndexBibliographyEntryContext::XMLIndexBibliographyEntryContext( SvXMLImport& rImport, XMLIndexTemplateContext& rTemplate, sal_uInt16 nPrfx, const OUString& rLocalName ) : XMLIndexSimpleEntryContext(rImport, rTemplate.sTokenBibliographyDataField, rTemplate, nPrfx, rLocalName), nBibliographyInfo(BibliographyDataField::IDENTIFIER), bBibliographyInfoOK(sal_False) { } XMLIndexBibliographyEntryContext::~XMLIndexBibliographyEntryContext() { } const SvXMLEnumMapEntry aBibliographyDataFieldMap[] = { { XML_ADDRESS, BibliographyDataField::ADDRESS }, { XML_ANNOTE, BibliographyDataField::ANNOTE }, { XML_AUTHOR, BibliographyDataField::AUTHOR }, { XML_BIBLIOGRAPHY_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, // #96658#: also read old documents (bib*i*liographic...) { XML_BIBILIOGRAPHIC_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, { XML_BOOKTITLE, BibliographyDataField::BOOKTITLE }, { XML_CHAPTER, BibliographyDataField::CHAPTER }, { XML_CUSTOM1, BibliographyDataField::CUSTOM1 }, { XML_CUSTOM2, BibliographyDataField::CUSTOM2 }, { XML_CUSTOM3, BibliographyDataField::CUSTOM3 }, { XML_CUSTOM4, BibliographyDataField::CUSTOM4 }, { XML_CUSTOM5, BibliographyDataField::CUSTOM5 }, { XML_EDITION, BibliographyDataField::EDITION }, { XML_EDITOR, BibliographyDataField::EDITOR }, { XML_HOWPUBLISHED, BibliographyDataField::HOWPUBLISHED }, { XML_IDENTIFIER, BibliographyDataField::IDENTIFIER }, { XML_INSTITUTION, BibliographyDataField::INSTITUTION }, { XML_ISBN, BibliographyDataField::ISBN }, { XML_JOURNAL, BibliographyDataField::JOURNAL }, { XML_MONTH, BibliographyDataField::MONTH }, { XML_NOTE, BibliographyDataField::NOTE }, { XML_NUMBER, BibliographyDataField::NUMBER }, { XML_ORGANIZATIONS, BibliographyDataField::ORGANIZATIONS }, { XML_PAGES, BibliographyDataField::PAGES }, { XML_PUBLISHER, BibliographyDataField::PUBLISHER }, { XML_REPORT_TYPE, BibliographyDataField::REPORT_TYPE }, { XML_SCHOOL, BibliographyDataField::SCHOOL }, { XML_SERIES, BibliographyDataField::SERIES }, { XML_TITLE, BibliographyDataField::TITLE }, { XML_URL, BibliographyDataField::URL }, { XML_VOLUME, BibliographyDataField::VOLUME }, { XML_YEAR, BibliographyDataField::YEAR }, { XML_TOKEN_INVALID, 0 } }; void XMLIndexBibliographyEntryContext::StartElement( const Reference<XAttributeList> & xAttrList) { // handle both, style name and bibliography info sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (XML_NAMESPACE_TEXT == nPrefix) { if ( IsXMLToken( sLocalName, XML_STYLE_NAME ) ) { sCharStyleName = xAttrList->getValueByIndex(nAttr); bCharStyleNameOK = sal_True; } else if ( IsXMLToken( sLocalName, XML_BIBLIOGRAPHY_DATA_FIELD ) ) { sal_uInt16 nTmp; if (SvXMLUnitConverter::convertEnum( nTmp, xAttrList->getValueByIndex(nAttr), aBibliographyDataFieldMap)) { nBibliographyInfo = nTmp; bBibliographyInfoOK = sal_True; } } } } // if we have a style name, set it! if (bCharStyleNameOK) { nValues++; } // always bibliography; else element is not valid nValues++; } void XMLIndexBibliographyEntryContext::EndElement() { // only valid, if we have bibliography info if (bBibliographyInfoOK) { XMLIndexSimpleEntryContext::EndElement(); } } void XMLIndexBibliographyEntryContext::FillPropertyValues( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue> & rValues) { // entry name and (optionally) style name in parent class XMLIndexSimpleEntryContext::FillPropertyValues(rValues); // bibliography data field sal_Int32 nIndex = bCharStyleNameOK ? 2 : 1; rValues[nIndex].Name = rTemplateContext.sBibliographyDataField; Any aAny; aAny <<= nBibliographyInfo; rValues[nIndex].Value = aAny; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <sstream> #include "util.hpp" #include "range.hpp" #include "grid.hpp" #include "hint.hpp" #include "hintconsumer.hpp" #include "singlehint.hpp" #include "hiddendouble.hpp" #include "forcingchain.hpp" #include "pointing.hpp" #include "boxlinereduction.hpp" #include "xwing.hpp" int main(int argc, char *argv[]) { #if 0 std::string s = ".....39483.9..85....4.....25..9.......7.1.6.......7..16.....1....87..2.91753....."; #endif #if 0 std::string s = "59.8.2.67.........6..7.3..1..9...1.....186.....7...3..8..4.5..2.........32.6.8.45"; #endif #if 0 std::string s = "..........9.7.6.2..3..1..5...2.6.3..76.5.1.49..9.4.8...2..7..3..5.9.4.8.........."; #endif #if 0 std::string s = "385694..21465729832973814566148.3..97531.96.8829.6...147193826553...6.9796......4"; #endif #if 1 std::string s = "9..6.2..4.7.9.428...43789..4..5.9..2.9.....4.56.4.1.98..9145637735896421146...859"; #endif std::istringstream in(s); Grid grid; std::vector<HintProducer *> hintproducers; hintproducers.push_back(new SingleHintProducer()); hintproducers.push_back(new HiddenDoubleHintProducer()); hintproducers.push_back(new PointingHintProducer()); hintproducers.push_back(new BoxLineReductionHintProducer()); hintproducers.push_back(new XWingHintProducer()); hintproducers.push_back(new ForcingChainHintProducer()); grid.load(in); grid.print(std::cout); grid.print_choices(std::cout); grid.print_status(std::cout); std::cout << std::endl; int iteration = 0; while (true) { ++iteration; SingleHintConsumer consumer; for (std::vector<HintProducer *>::const_iterator i = hintproducers.begin(); i != hintproducers.end(); ++i) { (*i)->find_hints(grid, consumer); if (consumer.has_hints()) break; } if (!consumer.has_hints()) break; #if 0 for (ListHintConsumer::iterator i = consumer.begin(); i != consumer.end(); ++i) { (*i)->print_description(std::cout); std::cout << std::endl; (*i)->apply(); } #endif std::cout << "iteration: " << iteration << std::endl; grid.print_choices(std::cout); grid.print_status(std::cout); std::cout << std::endl; } std::cout << "result: " << std::endl; grid.print_choices(std::cout); grid.print_status(std::cout); std::cout << std::endl; // std::for_each(hintproducers.begin(), hintproducers.end(), destroy<HintProducer *>()); return 0; } <commit_msg>segfault in xwing<commit_after>#include <iostream> #include <string> #include <vector> #include <sstream> #include "util.hpp" #include "range.hpp" #include "grid.hpp" #include "hint.hpp" #include "hintconsumer.hpp" #include "singlehint.hpp" #include "hiddendouble.hpp" #include "forcingchain.hpp" #include "pointing.hpp" #include "boxlinereduction.hpp" #include "xwing.hpp" int main(int argc, char *argv[]) { #if 0 std::string s = ".....39483.9..85....4.....25..9.......7.1.6.......7..16.....1....87..2.91753....."; #endif #if 0 std::string s = "59.8.2.67.........6..7.3..1..9...1.....186.....7...3..8..4.5..2.........32.6.8.45"; #endif #if 0 std::string s = "..........9.7.6.2..3..1..5...2.6.3..76.5.1.49..9.4.8...2..7..3..5.9.4.8.........."; #endif #if 0 std::string s = "385694..21465729832973814566148.3..97531.96.8829.6...147193826553...6.9796......4"; #endif #if 1 std::string s = "9..6.2..4.7.9.428...43789..4..5.9..2.9.....4.56.4.1.98..9145637735896421146...859"; #endif std::istringstream in(s); Grid grid; std::vector<HintProducer *> hintproducers; hintproducers.push_back(new SingleHintProducer()); hintproducers.push_back(new HiddenDoubleHintProducer()); hintproducers.push_back(new PointingHintProducer()); hintproducers.push_back(new BoxLineReductionHintProducer()); hintproducers.push_back(new XWingHintProducer()); hintproducers.push_back(new ForcingChainHintProducer()); grid.load(in); grid.print(std::cout); grid.print_choices(std::cout); grid.print_status(std::cout); std::cout << std::endl; int iteration = 0; while (true) { ++iteration; SingleHintConsumer consumer; for (std::vector<HintProducer *>::const_iterator i = hintproducers.begin(); i != hintproducers.end(); ++i) { (*i)->find_hints(grid, consumer); if (consumer.has_hints()) break; } if (!consumer.has_hints()) break; #if 0 for (ListHintConsumer::iterator i = consumer.begin(); i != consumer.end(); ++i) { (*i)->print_description(std::cout); std::cout << std::endl; (*i)->apply(); } #endif std::cout << "iteration: " << iteration << std::endl; grid.print_choices(std::cout); grid.print_status(std::cout); std::cout << std::endl; } std::cout << "result: " << std::endl; grid.print_choices(std::cout); grid.print_status(std::cout); std::cout << std::endl; std::for_each(hintproducers.begin(), hintproducers.end(), destroy< HintProducer *> ()); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Cisco and/or its affiliates. * 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 <sstream> #include <vom/route_api_types.hpp> #include <vom/route_cmds.hpp> namespace VOM { namespace route { namespace ip_route_cmds { update_cmd::update_cmd(HW::item<bool>& item, table_id_t id, const prefix_t& prefix, const path& path) : rpc_cmd(item) , m_id(id) , m_prefix(prefix) , m_path(path) { } bool update_cmd::operator==(const update_cmd& other) const { return ((m_prefix == other.m_prefix) && (m_id == other.m_id) && (m_path == other.m_path)); } rc_t update_cmd::issue(connection& con) { msg_t req(con.ctx(), 0, std::ref(*this)); auto& payload = req.get_request().get_payload(); payload.table_id = m_id; payload.is_add = 1; payload.is_multipath = 0; m_prefix.to_vpp(&payload.is_ipv6, payload.dst_address, &payload.dst_address_length); to_vpp(m_path, payload); VAPI_CALL(req.execute()); return (wait()); } std::string update_cmd::to_string() const { std::ostringstream s; s << "ip-route-create: " << m_hw_item.to_string() << " table-id:" << m_id << " prefix:" << m_prefix.to_string() << " paths:" << m_path.to_string(); return (s.str()); } delete_cmd::delete_cmd(HW::item<bool>& item, table_id_t id, const prefix_t& prefix, const path& path) : rpc_cmd(item) , m_id(id) , m_prefix(prefix) , m_path(path) { } bool delete_cmd::operator==(const delete_cmd& other) const { return ((m_prefix == other.m_prefix) && (m_id == other.m_id) && (m_path == other.m_path)); } rc_t delete_cmd::issue(connection& con) { msg_t req(con.ctx(), 0, std::ref(*this)); auto& payload = req.get_request().get_payload(); payload.table_id = m_id; payload.is_add = 0; m_prefix.to_vpp(&payload.is_ipv6, payload.dst_address, &payload.dst_address_length); to_vpp(m_path, payload); VAPI_CALL(req.execute()); wait(); m_hw_item.set(rc_t::NOOP); return rc_t::OK; } std::string delete_cmd::to_string() const { std::ostringstream s; s << "ip-route-delete: " << m_hw_item.to_string() << " id:" << m_id << " prefix:" << m_prefix.to_string() << " paths:" << m_path.to_string(); return (s.str()); } dump_v4_cmd::dump_v4_cmd() { } bool dump_v4_cmd::operator==(const dump_v4_cmd& other) const { return (true); } rc_t dump_v4_cmd::issue(connection& con) { m_dump.reset(new msg_t(con.ctx(), std::ref(*this))); VAPI_CALL(m_dump->execute()); wait(); return rc_t::OK; } std::string dump_v4_cmd::to_string() const { return ("ip-route-v4-dump"); } dump_v6_cmd::dump_v6_cmd() { } bool dump_v6_cmd::operator==(const dump_v6_cmd& other) const { return (true); } rc_t dump_v6_cmd::issue(connection& con) { m_dump.reset(new msg_t(con.ctx(), std::ref(*this))); VAPI_CALL(m_dump->execute()); wait(); return rc_t::OK; } std::string dump_v6_cmd::to_string() const { return ("ip-route-v6-dump"); } } // namespace ip_route_cmds } // namespace route } // namespace vom /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "mozilla") * End: */ <commit_msg>VOM: routes support multipath so set is_multipath in route update<commit_after>/* * Copyright (c) 2017 Cisco and/or its affiliates. * 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 <sstream> #include <vom/route_api_types.hpp> #include <vom/route_cmds.hpp> namespace VOM { namespace route { namespace ip_route_cmds { update_cmd::update_cmd(HW::item<bool>& item, table_id_t id, const prefix_t& prefix, const path& path) : rpc_cmd(item) , m_id(id) , m_prefix(prefix) , m_path(path) { } bool update_cmd::operator==(const update_cmd& other) const { return ((m_prefix == other.m_prefix) && (m_id == other.m_id) && (m_path == other.m_path)); } rc_t update_cmd::issue(connection& con) { msg_t req(con.ctx(), 0, std::ref(*this)); auto& payload = req.get_request().get_payload(); payload.table_id = m_id; payload.is_add = 1; payload.is_multipath = 1; m_prefix.to_vpp(&payload.is_ipv6, payload.dst_address, &payload.dst_address_length); to_vpp(m_path, payload); VAPI_CALL(req.execute()); return (wait()); } std::string update_cmd::to_string() const { std::ostringstream s; s << "ip-route-create: " << m_hw_item.to_string() << " table-id:" << m_id << " prefix:" << m_prefix.to_string() << " paths:" << m_path.to_string(); return (s.str()); } delete_cmd::delete_cmd(HW::item<bool>& item, table_id_t id, const prefix_t& prefix, const path& path) : rpc_cmd(item) , m_id(id) , m_prefix(prefix) , m_path(path) { } bool delete_cmd::operator==(const delete_cmd& other) const { return ((m_prefix == other.m_prefix) && (m_id == other.m_id) && (m_path == other.m_path)); } rc_t delete_cmd::issue(connection& con) { msg_t req(con.ctx(), 0, std::ref(*this)); auto& payload = req.get_request().get_payload(); payload.table_id = m_id; payload.is_add = 0; m_prefix.to_vpp(&payload.is_ipv6, payload.dst_address, &payload.dst_address_length); to_vpp(m_path, payload); VAPI_CALL(req.execute()); wait(); m_hw_item.set(rc_t::NOOP); return rc_t::OK; } std::string delete_cmd::to_string() const { std::ostringstream s; s << "ip-route-delete: " << m_hw_item.to_string() << " id:" << m_id << " prefix:" << m_prefix.to_string() << " paths:" << m_path.to_string(); return (s.str()); } dump_v4_cmd::dump_v4_cmd() { } bool dump_v4_cmd::operator==(const dump_v4_cmd& other) const { return (true); } rc_t dump_v4_cmd::issue(connection& con) { m_dump.reset(new msg_t(con.ctx(), std::ref(*this))); VAPI_CALL(m_dump->execute()); wait(); return rc_t::OK; } std::string dump_v4_cmd::to_string() const { return ("ip-route-v4-dump"); } dump_v6_cmd::dump_v6_cmd() { } bool dump_v6_cmd::operator==(const dump_v6_cmd& other) const { return (true); } rc_t dump_v6_cmd::issue(connection& con) { m_dump.reset(new msg_t(con.ctx(), std::ref(*this))); VAPI_CALL(m_dump->execute()); wait(); return rc_t::OK; } std::string dump_v6_cmd::to_string() const { return ("ip-route-v6-dump"); } } // namespace ip_route_cmds } // namespace route } // namespace vom /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "mozilla") * End: */ <|endoftext|>
<commit_before><commit_msg>Tweaking the window settings to improve performance by not drawing an additional system background<commit_after><|endoftext|>
<commit_before>#include "pcsclite.h" #include "cardreader.h" using namespace v8; using namespace node; void init_all(Local<Object> target) { PCSCLite::init(target); CardReader::init(target); } NODE_MODULE(pcsclite, init_all) <commit_msg>src: make the module Context aware<commit_after>#include "pcsclite.h" #include "cardreader.h" using namespace v8; using namespace node; void init_all(Local<Object> target) { PCSCLite::init(target); CardReader::init(target); } #if NODE_MAJOR_VERSION >= 10 NAN_MODULE_WORKER_ENABLED(pcsclite, init_all) #else NODE_MODULE(pcsclite, init_all) #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Monteverdi Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // // Configuration include. //// Included at first position before any other ones. #include "ConfigureMonteverdi.h" /*****************************************************************************/ /* INCLUDE SECTION */ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. #include <QPixmap> #include <QSplashScreen> #define USE_SPLASH_SCREEN 0 // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // #include "itksys/SystemTools.hxx" // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdApplication.h" #include "mvdMainWindow.h" enum ERROR_CODE { ERROR_CODE_I18N = -1, ERROR_CODE_CACHE_DIR = -2, ERROR_CODE_DATABASE = -3, ERROR_CODE_GL_VERSION = -4, ERROR_CODE_USAGE = -5, }; /*****************************************************************************/ /* FUNCTIONS DECLARATION */ /*****************************************************************************/ /* MAIN */ int main( int argc, char* argv[] ) { QApplication qtApp( argc, argv ); // // 0. Splash-screen. #if !defined( _DEBUG ) && USE_SPLASH_SCREEN QPixmap pixmap(QLatin1String( ":/images/application_splash" )); QSplashScreen splash(pixmap); splash.show(); qtApp.processEvents();//This is used to accept a click on the screen so that user can cancel the screen #endif // // 0bis. Parse pre-initialization command-line arguments. QStringList args( qtApp.arguments() ); { for( QStringList::iterator it( args.begin() ); it!=args.end(); ) if( it->compare( "-h" )==0 || it->compare( "--help" )==0 ) { std::cout << mvd::ToStdString( QCoreApplication::translate( PROJECT_NAME, "Usage: %1 [-h|--help] [-a|--applications] [<filename>...]\n" " -h, --help display this help message.\n" " -a, --applications load OTB-applications from OTB_APPLICATIONS_PATH." ) .arg( basename( argv[ 0 ] ) ) ) << std::endl; return ERROR_CODE_USAGE; } else { ++ it; } } // // 1. Initialize application and sync settings. // // Coverity-14835 // { mvd::Application * application = NULL; try { application = new mvd::Application( &qtApp ); assert( application!=NULL ); application->Initialize(); } catch( std::exception & exc ) { QMessageBox::StandardButton button = QMessageBox::question( NULL, QCoreApplication::translate( PROJECT_NAME, "Question!" ), QCoreApplication::translate( PROJECT_NAME, "The following exception has been caught while initializing the software:\n\n" "%1\n\n" "The application may not function as expected. Do you want to continue?" ) .arg( exc.what() ), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if( button==QMessageBox::No ) return ERROR_CODE_I18N; } // } // Coverity-14835 // // 2. Initialize main-window (UI). mvd::MainWindow mainWindow; mainWindow.Initialize(); // // 3. Show window. #if defined( _DEBUG ) // Usefull when developping/debugging to avoid overlapping other windows. mainWindow.show(); #else // _DEBUG #if USE_SPLASH_SCREEN splash.finish( &mainWindow ); #endif // USE_SPLASH_SCREEN // TODO: Correctly manage main-window state via application settings. mainWindow.showMaximized(); #endif // _DEBUG // // 4. Check OpenGL capabilities if( !mainWindow.CheckGLCapabilities() ) return ERROR_CODE_GL_VERSION; // // 5. Parse command-line filenames. args.pop_front(); { bool otbApplications = false; for( QStringList::iterator it( args.begin() ); it!=args.end(); ) if( it->compare( "-a" )==0 || it->compare( "--applications" )==0 ) { if( !otbApplications ) { #if USE_OTB_APPS mainWindow.SetupOTBApplications(); #else // USE_OTB_APPS qWarning() << "OTB-applications support is not included in this build."; #endif // USE_OTB_APPS it = args.erase( it ); } } else { ++ it; } } mainWindow.ImportImages( args ); // // 6. Let's go: run the application and return exit code. int result = QCoreApplication::instance()->exec(); /* application->CloseDatabase(); */ // Coverity-14835 // { delete application; application = NULL; // } // Coverity-14835 return result; } /*****************************************************************************/ /* FUNCTIONS IMPLEMENTATION */ /*****************************************************************************/ <commit_msg>COMP: Fixed call to basename() not available on Windows.<commit_after>/*========================================================================= Program: Monteverdi Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // // Configuration include. //// Included at first position before any other ones. #include "ConfigureMonteverdi.h" /*****************************************************************************/ /* INCLUDE SECTION */ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. #include <QPixmap> #include <QSplashScreen> #define USE_SPLASH_SCREEN 0 // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // #include "itksys/SystemTools.hxx" // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdApplication.h" #include "mvdMainWindow.h" enum ERROR_CODE { ERROR_CODE_I18N = -1, ERROR_CODE_CACHE_DIR = -2, ERROR_CODE_DATABASE = -3, ERROR_CODE_GL_VERSION = -4, ERROR_CODE_USAGE = -5, }; /*****************************************************************************/ /* FUNCTIONS DECLARATION */ /*****************************************************************************/ /* MAIN */ int main( int argc, char* argv[] ) { QApplication qtApp( argc, argv ); // // 0. Splash-screen. #if !defined( _DEBUG ) && USE_SPLASH_SCREEN QPixmap pixmap(QLatin1String( ":/images/application_splash" )); QSplashScreen splash(pixmap); splash.show(); qtApp.processEvents();//This is used to accept a click on the screen so that user can cancel the screen #endif // // 0bis. Parse pre-initialization command-line arguments. QStringList args( qtApp.arguments() ); { for( QStringList::iterator it( args.begin() ); it!=args.end(); ) if( it->compare( "-h" )==0 || it->compare( "--help" )==0 ) { std::cout << mvd::ToStdString( QCoreApplication::translate( PROJECT_NAME, "Usage: %1 [-h|--help] [-a|--applications] [<filename>...]\n" " -h, --help display this help message.\n" " -a, --applications load OTB-applications from OTB_APPLICATIONS_PATH." ) .arg( QFileInfo( argv[ 0 ] ).baseName() ) ) << std::endl; return ERROR_CODE_USAGE; } else { ++ it; } } // // 1. Initialize application and sync settings. // // Coverity-14835 // { mvd::Application * application = NULL; try { application = new mvd::Application( &qtApp ); assert( application!=NULL ); application->Initialize(); } catch( std::exception & exc ) { QMessageBox::StandardButton button = QMessageBox::question( NULL, QCoreApplication::translate( PROJECT_NAME, "Question!" ), QCoreApplication::translate( PROJECT_NAME, "The following exception has been caught while initializing the software:\n\n" "%1\n\n" "The application may not function as expected. Do you want to continue?" ) .arg( exc.what() ), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if( button==QMessageBox::No ) return ERROR_CODE_I18N; } // } // Coverity-14835 // // 2. Initialize main-window (UI). mvd::MainWindow mainWindow; mainWindow.Initialize(); // // 3. Show window. #if defined( _DEBUG ) // Usefull when developping/debugging to avoid overlapping other windows. mainWindow.show(); #else // _DEBUG #if USE_SPLASH_SCREEN splash.finish( &mainWindow ); #endif // USE_SPLASH_SCREEN // TODO: Correctly manage main-window state via application settings. mainWindow.showMaximized(); #endif // _DEBUG // // 4. Check OpenGL capabilities if( !mainWindow.CheckGLCapabilities() ) return ERROR_CODE_GL_VERSION; // // 5. Parse command-line filenames. args.pop_front(); { bool otbApplications = false; for( QStringList::iterator it( args.begin() ); it!=args.end(); ) if( it->compare( "-a" )==0 || it->compare( "--applications" )==0 ) { if( !otbApplications ) { #if USE_OTB_APPS mainWindow.SetupOTBApplications(); #else // USE_OTB_APPS qWarning() << "OTB-applications support is not included in this build."; #endif // USE_OTB_APPS it = args.erase( it ); } } else { ++ it; } } mainWindow.ImportImages( args ); // // 6. Let's go: run the application and return exit code. int result = QCoreApplication::instance()->exec(); /* application->CloseDatabase(); */ // Coverity-14835 // { delete application; application = NULL; // } // Coverity-14835 return result; } /*****************************************************************************/ /* FUNCTIONS IMPLEMENTATION */ /*****************************************************************************/ <|endoftext|>
<commit_before>#include "ics3/angle.hpp" #define _USE_MATH_DEFINES #include <cmath> ics::Angle ics::Angle::newDegree() noexcept { static const double limit = 130; static const Angle DEGREE(-limit, limit, 800.0 / 27.0); return DEGREE; } ics::Angle ics::Angle::newRadian() noexcept { static const double limit = 130 * M_PI / 180; static const Angle RADIAN(-limit, limit, 16000.0 / 3.0 / M_PI); return RADIAN; } double ics::Angle::get() const noexcept { return data; } void ics::Angle::set(double angle) throw(std::invalid_argument) { if (angle < min) throw std::invalid_argument("Too small angle"); if (max < angle) throw std::invalid_argument("Too big angle"); data = angle; } uint16_t ics::Angle::getRaw() const noexcept { return static_cast<uint16_t>(data * rawCalibration + 7500); } void ics::Angle::setRaw(uint16_t raw) throw(std::invalid_argument) { try { set((raw - 7500) / rawCalibration); } catch (std::invalid_argument &e) { throw; } } ics::Angle::Angle(double min, double max, double calibration) noexcept : min(min), max(max), rawCalibration(calibration), data(0) {} <commit_msg>Refactor place of reference operator<commit_after>#include "ics3/angle.hpp" #define _USE_MATH_DEFINES #include <cmath> ics::Angle ics::Angle::newDegree() noexcept { static const double limit = 130; static const Angle DEGREE(-limit, limit, 800.0 / 27.0); return DEGREE; } ics::Angle ics::Angle::newRadian() noexcept { static const double limit = 130 * M_PI / 180; static const Angle RADIAN(-limit, limit, 16000.0 / 3.0 / M_PI); return RADIAN; } double ics::Angle::get() const noexcept { return data; } void ics::Angle::set(double angle) throw(std::invalid_argument) { if (angle < min) throw std::invalid_argument("Too small angle"); if (max < angle) throw std::invalid_argument("Too big angle"); data = angle; } uint16_t ics::Angle::getRaw() const noexcept { return static_cast<uint16_t>(data * rawCalibration + 7500); } void ics::Angle::setRaw(uint16_t raw) throw(std::invalid_argument) { try { set((raw - 7500) / rawCalibration); } catch (std::invalid_argument& e) { throw; } } ics::Angle::Angle(double min, double max, double calibration) noexcept : min(min), max(max), rawCalibration(calibration), data(0) {} <|endoftext|>
<commit_before>/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/common.h> #include <pistache/errors.h> #include <pistache/listener.h> #include <pistache/os.h> #include <pistache/peer.h> #include <pistache/transport.h> #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/timerfd.h> #include <sys/types.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> #ifdef PISTACHE_USE_SSL #include <openssl/err.h> #include <openssl/ssl.h> #endif /* PISTACHE_USE_SSL */ namespace Pistache { namespace Tcp { void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))); } if (options.hasFlag(Options::ReusePort)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof(opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof(hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof(one))); } } Listener::Listener() : addr_(), listen_fd(-1), backlog_(Const::MaxBacklog), shutdownFd(), poller(), options_(), workers_(Const::DefaultWorkers), workersName_(), reactor_(), transportKey(), useSSL_(false), ssl_ctx_(nullptr) {} Listener::Listener(const Address &address) : addr_(address), listen_fd(-1), backlog_(Const::MaxBacklog), shutdownFd(), poller(), options_(), workers_(Const::DefaultWorkers), workersName_(), reactor_(), transportKey(), useSSL_(false), ssl_ctx_(nullptr) {} Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); if (listen_fd >= 0) { close(listen_fd); listen_fd = -1; } #ifdef PISTACHE_USE_SSL if (this->useSSL_) { SSL_CTX_free((SSL_CTX *)this->ssl_ctx_); EVP_cleanup(); } #endif /* PISTACHE_USE_SSL */ } void Listener::init(size_t workers, Flags<Options> options, const std::string &workersName, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; useSSL_ = false; workers_ = workers; workersName_ = workersName; } void Listener::setHandler(const std::shared_ptr<Handler> &handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet &set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } void Listener::bind() { bind(addr_); } void Listener::bind(const Address &address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto &host = addr_.host(); const auto &port = addr_.port().toString(); AddrInfo addr_info; TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints)); int fd = -1; const addrinfo *addr = nullptr; for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it // is the case, the previous loop would have exited naturally and addr will be // null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Flags<Polling::NotifyOn>(Polling::NotifyOn::Read), Polling::Tag(fd)); listen_fd = fd; auto transport = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_, workersName_)); transportKey = reactor_.addHandler(transport); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr *>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { shutdownFd.bind(poller); reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events); if (ready_fds == -1) { throw Error::system("Polling"); } for (const auto &event : events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError &ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError &ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load &old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto &handler : handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)) .then( [=](const std::vector<rusage> &usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto &usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; int client_fd = acceptConnection(peer_addr); #ifdef PISTACHE_USE_SSL SSL *ssl = nullptr; if (this->useSSL_) { ssl = SSL_new((SSL_CTX *)this->ssl_ctx_); if (ssl == NULL) { close(client_fd); throw std::runtime_error("Cannot create SSL connection"); } SSL_set_fd(ssl, client_fd); SSL_set_accept_state(ssl); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); SSL_free(ssl); close(client_fd); return; } } #endif /* PISTACHE_USE_SSL */ make_non_blocking(client_fd); std::shared_ptr<Peer> peer; if (this->useSSL_) { peer = Peer::CreateSSL(client_fd, Address::fromUnix(&peer_addr), ssl); } else { peer = Peer::Create(client_fd, Address::fromUnix(&peer_addr)); } dispatchPeer(peer); } int Listener::acceptConnection(struct sockaddr_in &peer_addr) const { socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } return client_fd; } void Listener::dispatchPeer(const std::shared_ptr<Peer> &peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } #ifdef PISTACHE_USE_SSL static SSL_CTX *ssl_create_context(const std::string &cert, const std::string &key, bool use_compression) { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot setup SSL context"); } if (!use_compression) { /* Disable compression to prevent BREACH and CRIME vulnerabilities. */ if (!SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot disable compression"); } } /* Function introduced in 1.0.2 */ #if OPENSSL_VERSION_NUMBER >= 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif /* OPENSSL_VERSION_NUMBER */ if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL certificate"); } if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL private key"); } if (!SSL_CTX_check_private_key(ctx)) { ERR_print_errors_fp(stderr); throw std::runtime_error( "Private key does not match public key in the certificate"); } return ctx; } void Listener::setupSSLAuth(const std::string &ca_file, const std::string &ca_path, int (*cb)(int, void *) = NULL) { const char *__ca_file = NULL; const char *__ca_path = NULL; if (this->ssl_ctx_ == NULL) throw std::runtime_error("SSL Context is not initialized"); if (!ca_file.empty()) __ca_file = ca_file.c_str(); if (!ca_path.empty()) __ca_path = ca_path.c_str(); if (SSL_CTX_load_verify_locations((SSL_CTX *)this->ssl_ctx_, __ca_file, __ca_path) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot verify SSL locations"); } SSL_CTX_set_verify((SSL_CTX *)this->ssl_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, /* Callback type did change in 1.0.1 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L (int (*)(int, X509_STORE_CTX *))cb #else (SSL_verify_cb)cb #endif /* OPENSSL_VERSION_NUMBER */ ); } void Listener::setupSSL(const std::string &cert_path, const std::string &key_path, bool use_compression) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); this->ssl_ctx_ = ssl_create_context(cert_path, key_path, use_compression); this->useSSL_ = true; } #endif /* PISTACHE_USE_SSL */ } // namespace Tcp } // namespace Pistache <commit_msg>Issue #700: fix build<commit_after>/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/common.h> #include <pistache/errors.h> #include <pistache/listener.h> #include <pistache/os.h> #include <pistache/peer.h> #include <pistache/transport.h> #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/timerfd.h> #include <sys/types.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> #ifdef PISTACHE_USE_SSL #include <openssl/err.h> #include <openssl/ssl.h> #endif /* PISTACHE_USE_SSL */ namespace Pistache { namespace Tcp { void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))); } if (options.hasFlag(Options::ReusePort)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof(opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof(hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof(one))); } } Listener::Listener() : addr_(), listen_fd(-1), backlog_(Const::MaxBacklog), shutdownFd(), poller(), options_(), workers_(Const::DefaultWorkers), workersName_(), reactor_(), transportKey(), useSSL_(false), ssl_ctx_(nullptr) {} Listener::Listener(const Address &address) : addr_(address), listen_fd(-1), backlog_(Const::MaxBacklog), shutdownFd(), poller(), options_(), workers_(Const::DefaultWorkers), workersName_(), reactor_(), transportKey(), useSSL_(false), ssl_ctx_(nullptr) {} Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); if (listen_fd >= 0) { close(listen_fd); listen_fd = -1; } #ifdef PISTACHE_USE_SSL if (this->useSSL_) { SSL_CTX_free((SSL_CTX *)this->ssl_ctx_); EVP_cleanup(); } #endif /* PISTACHE_USE_SSL */ } void Listener::init(size_t workers, Flags<Options> options, const std::string &workersName, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; useSSL_ = false; workers_ = workers; workersName_ = workersName; } void Listener::setHandler(const std::shared_ptr<Handler> &handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet &set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } void Listener::bind() { bind(addr_); } void Listener::bind(const Address &address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto &host = addr_.host(); const auto &port = addr_.port().toString(); AddrInfo addr_info; TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints)); int fd = -1; const addrinfo *addr = nullptr; for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it // is the case, the previous loop would have exited naturally and addr will be // null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Flags<Polling::NotifyOn>(Polling::NotifyOn::Read), Polling::Tag(fd)); listen_fd = fd; auto transport = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_, workersName_)); transportKey = reactor_.addHandler(transport); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr *>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { shutdownFd.bind(poller); reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events); if (ready_fds == -1) { throw Error::system("Polling"); } for (const auto &event : events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError &ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError &ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load &old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto &handler : handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)) .then( [=](const std::vector<rusage> &usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto &usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; int client_fd = acceptConnection(peer_addr); void *ssl = nullptr; #ifdef PISTACHE_USE_SSL if (this->useSSL_) { ssl = SSL_new((SSL_CTX *)this->ssl_ctx_); if (ssl == NULL) { close(client_fd); throw std::runtime_error("Cannot create SSL connection"); } SSL_set_fd(ssl, client_fd); SSL_set_accept_state(ssl); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); SSL_free(ssl); close(client_fd); return; } } #endif /* PISTACHE_USE_SSL */ make_non_blocking(client_fd); std::shared_ptr<Peer> peer; if (this->useSSL_) { peer = Peer::CreateSSL(client_fd, Address::fromUnix(&peer_addr), ssl); } else { peer = Peer::Create(client_fd, Address::fromUnix(&peer_addr)); } dispatchPeer(peer); } int Listener::acceptConnection(struct sockaddr_in &peer_addr) const { socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } return client_fd; } void Listener::dispatchPeer(const std::shared_ptr<Peer> &peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } #ifdef PISTACHE_USE_SSL static SSL_CTX *ssl_create_context(const std::string &cert, const std::string &key, bool use_compression) { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot setup SSL context"); } if (!use_compression) { /* Disable compression to prevent BREACH and CRIME vulnerabilities. */ if (!SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot disable compression"); } } /* Function introduced in 1.0.2 */ #if OPENSSL_VERSION_NUMBER >= 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif /* OPENSSL_VERSION_NUMBER */ if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL certificate"); } if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL private key"); } if (!SSL_CTX_check_private_key(ctx)) { ERR_print_errors_fp(stderr); throw std::runtime_error( "Private key does not match public key in the certificate"); } return ctx; } void Listener::setupSSLAuth(const std::string &ca_file, const std::string &ca_path, int (*cb)(int, void *) = NULL) { const char *__ca_file = NULL; const char *__ca_path = NULL; if (this->ssl_ctx_ == NULL) throw std::runtime_error("SSL Context is not initialized"); if (!ca_file.empty()) __ca_file = ca_file.c_str(); if (!ca_path.empty()) __ca_path = ca_path.c_str(); if (SSL_CTX_load_verify_locations((SSL_CTX *)this->ssl_ctx_, __ca_file, __ca_path) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot verify SSL locations"); } SSL_CTX_set_verify((SSL_CTX *)this->ssl_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, /* Callback type did change in 1.0.1 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L (int (*)(int, X509_STORE_CTX *))cb #else (SSL_verify_cb)cb #endif /* OPENSSL_VERSION_NUMBER */ ); } void Listener::setupSSL(const std::string &cert_path, const std::string &key_path, bool use_compression) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); this->ssl_ctx_ = ssl_create_context(cert_path, key_path, use_compression); this->useSSL_ = true; } #endif /* PISTACHE_USE_SSL */ } // namespace Tcp } // namespace Pistache <|endoftext|>
<commit_before>/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/listener.h> #include <pistache/peer.h> #include <pistache/common.h> #include <pistache/os.h> #include <pistache/transport.h> #include <pistache/errors.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/types.h> #include <netdb.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> #ifdef PISTACHE_USE_SSL #include <openssl/ssl.h> #include <openssl/err.h> #endif /* PISTACHE_USE_SSL */ namespace Pistache { namespace Tcp { void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one))); } } Listener::Listener() : addr_() , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::Listener(const Address& address) : addr_(address) , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); #ifdef PISTACHE_USE_SSL if (this->useSSL_) { SSL_CTX_free((SSL_CTX *)this->ssl_ctx_); EVP_cleanup(); } #endif /* PISTACHE_USE_SSL */ } void Listener::init( size_t workers, Flags<Options> options, std::string workersName, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; useSSL_ = false; workers_ = workers; workersName_ = workersName; } void Listener::setHandler(const std::shared_ptr<Handler>& handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet& set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } void Listener::bind() { bind(addr_); } void Listener::bind(const Address& address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto& host = addr_.host(); const auto& port = addr_.port().toString(); AddrInfo addr_info; TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints)); int fd = -1; const addrinfo * addr = nullptr; for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous // loop would have exited naturally and addr will be null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd)); listen_fd = fd; auto transport = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_, workersName_)); transportKey = reactor_.addHandler(transport); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { shutdownFd.bind(poller); reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events); if (ready_fds == -1) { throw Error::system("Polling"); } for (const auto& event: events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError& ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError& ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load& old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto& handler: handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto& usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; int client_fd = acceptConnection(peer_addr); #ifdef PISTACHE_USE_SSL SSL *ssl = nullptr; if (this->useSSL_) { ssl = SSL_new((SSL_CTX *)this->ssl_ctx_); if (ssl == NULL) throw std::runtime_error("Cannot create SSL connection"); SSL_set_fd(ssl, client_fd); SSL_set_accept_state(ssl); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); SSL_free(ssl); close(client_fd); return ; } } #endif /* PISTACHE_USE_SSL */ make_non_blocking(client_fd); auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr)); peer->associateFd(client_fd); #ifdef PISTACHE_USE_SSL if (this->useSSL_) peer->associateSSL(ssl); #endif /* PISTACHE_USE_SSL */ dispatchPeer(peer); } int Listener::acceptConnection(struct sockaddr_in& peer_addr) const { socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } return client_fd; } void Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } #ifdef PISTACHE_USE_SSL static SSL_CTX *ssl_create_context(const std::string &cert, const std::string &key, bool use_compression) { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot setup SSL context"); } if (!use_compression) { /* Disable compression to prevent BREACH and CRIME vulnerabilities. */ if (!SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot disable compression"); } } /* Function introduced in 1.0.2 */ #if OPENSSL_VERSION_NUMBER >= 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif /* OPENSSL_VERSION_NUMBER */ if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL certificate"); } if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL private key"); } if (!SSL_CTX_check_private_key(ctx)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Private key does not match public key in the certificate"); } return ctx; } void Listener::setupSSLAuth(const std::string &ca_file, const std::string &ca_path, int (*cb)(int, void *) = NULL) { const char *__ca_file = NULL; const char *__ca_path = NULL; if (this->ssl_ctx_ == NULL) throw std::runtime_error("SSL Context is not initialized"); if (!ca_file.empty()) __ca_file = ca_file.c_str(); if (!ca_path.empty()) __ca_path = ca_path.c_str(); if (SSL_CTX_load_verify_locations((SSL_CTX *)this->ssl_ctx_, __ca_file, __ca_path) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot verify SSL locations"); } SSL_CTX_set_verify((SSL_CTX *)this->ssl_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, /* Callback type did change in 1.0.1 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L (int (*)(int, X509_STORE_CTX *))cb #else (SSL_verify_cb)cb #endif /* OPENSSL_VERSION_NUMBER */ ); } void Listener::setupSSL(const std::string &cert_path, const std::string &key_path, bool use_compression) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); this->ssl_ctx_ = ssl_create_context(cert_path, key_path, use_compression); this->useSSL_ = true; } #endif /* PISTACHE_USE_SSL */ } // namespace Tcp } // namespace Pistache <commit_msg>Update listener.cc<commit_after>/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/listener.h> #include <pistache/peer.h> #include <pistache/common.h> #include <pistache/os.h> #include <pistache/transport.h> #include <pistache/errors.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/types.h> #include <netdb.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> #ifdef PISTACHE_USE_SSL #include <openssl/ssl.h> #include <openssl/err.h> #endif /* PISTACHE_USE_SSL */ namespace Pistache { namespace Tcp { void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one))); } } Listener::Listener() : addr_() , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::Listener(const Address& address) : addr_(address) , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); #ifdef PISTACHE_USE_SSL if (this->useSSL_) { SSL_CTX_free((SSL_CTX *)this->ssl_ctx_); EVP_cleanup(); } #endif /* PISTACHE_USE_SSL */ } void Listener::init( size_t workers, Flags<Options> options, const std::string& workersName, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; useSSL_ = false; workers_ = workers; workersName_ = workersName; } void Listener::setHandler(const std::shared_ptr<Handler>& handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet& set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } void Listener::bind() { bind(addr_); } void Listener::bind(const Address& address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto& host = addr_.host(); const auto& port = addr_.port().toString(); AddrInfo addr_info; TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints)); int fd = -1; const addrinfo * addr = nullptr; for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous // loop would have exited naturally and addr will be null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd)); listen_fd = fd; auto transport = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_, workersName_)); transportKey = reactor_.addHandler(transport); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { shutdownFd.bind(poller); reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events); if (ready_fds == -1) { throw Error::system("Polling"); } for (const auto& event: events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError& ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError& ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load& old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto& handler: handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto& usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; int client_fd = acceptConnection(peer_addr); #ifdef PISTACHE_USE_SSL SSL *ssl = nullptr; if (this->useSSL_) { ssl = SSL_new((SSL_CTX *)this->ssl_ctx_); if (ssl == NULL) throw std::runtime_error("Cannot create SSL connection"); SSL_set_fd(ssl, client_fd); SSL_set_accept_state(ssl); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); SSL_free(ssl); close(client_fd); return ; } } #endif /* PISTACHE_USE_SSL */ make_non_blocking(client_fd); auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr)); peer->associateFd(client_fd); #ifdef PISTACHE_USE_SSL if (this->useSSL_) peer->associateSSL(ssl); #endif /* PISTACHE_USE_SSL */ dispatchPeer(peer); } int Listener::acceptConnection(struct sockaddr_in& peer_addr) const { socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } return client_fd; } void Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } #ifdef PISTACHE_USE_SSL static SSL_CTX *ssl_create_context(const std::string &cert, const std::string &key, bool use_compression) { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot setup SSL context"); } if (!use_compression) { /* Disable compression to prevent BREACH and CRIME vulnerabilities. */ if (!SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot disable compression"); } } /* Function introduced in 1.0.2 */ #if OPENSSL_VERSION_NUMBER >= 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif /* OPENSSL_VERSION_NUMBER */ if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL certificate"); } if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL private key"); } if (!SSL_CTX_check_private_key(ctx)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Private key does not match public key in the certificate"); } return ctx; } void Listener::setupSSLAuth(const std::string &ca_file, const std::string &ca_path, int (*cb)(int, void *) = NULL) { const char *__ca_file = NULL; const char *__ca_path = NULL; if (this->ssl_ctx_ == NULL) throw std::runtime_error("SSL Context is not initialized"); if (!ca_file.empty()) __ca_file = ca_file.c_str(); if (!ca_path.empty()) __ca_path = ca_path.c_str(); if (SSL_CTX_load_verify_locations((SSL_CTX *)this->ssl_ctx_, __ca_file, __ca_path) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot verify SSL locations"); } SSL_CTX_set_verify((SSL_CTX *)this->ssl_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, /* Callback type did change in 1.0.1 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L (int (*)(int, X509_STORE_CTX *))cb #else (SSL_verify_cb)cb #endif /* OPENSSL_VERSION_NUMBER */ ); } void Listener::setupSSL(const std::string &cert_path, const std::string &key_path, bool use_compression) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); this->ssl_ctx_ = ssl_create_context(cert_path, key_path, use_compression); this->useSSL_ = true; } #endif /* PISTACHE_USE_SSL */ } // namespace Tcp } // namespace Pistache <|endoftext|>