text
stringlengths
54
60.6k
<commit_before>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Matthew Hoyt (mhoyt@ca.ibm.com) */ #if !defined(XALANDEQUE_HEADER_GUARD_1357924680) #define XALANDEQUE_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <xalanc/Include/XalanVector.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class Value> struct XalanDequeIteratorTraits { typedef Value value_type; typedef Value& reference; typedef Value* pointer; typedef const Value& const_reference; }; template <class Value> struct XalanDequeConstIteratorTraits { typedef Value value_type; typedef const Value& reference; typedef const Value* pointer; typedef const Value& const_reference; }; template <class XalanDequeTraits, class XalanDeque> struct XalanDequeIterator { typedef size_t size_type; typedef typename XalanDequeTraits::value_type value_type; typedef typename XalanDequeTraits::reference reference; typedef typename XalanDequeTraits::pointer pointer; typedef typename XalanDequeTraits::const_reference const_reference; typedef ptrdiff_t difference_type; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator; typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category; XalanDequeIterator(XalanDeque* deque, size_type pos) : m_deque(deque), m_pos(pos) { } XalanDequeIterator(const Iterator & iterator) : m_deque(iterator.m_deque), m_pos(iterator.m_pos) { } XalanDequeIterator& operator=(const Iterator & iterator) { m_deque = iterator.m_deque; m_pos = iterator.m_pos; return *this; } XalanDequeIterator& operator++() { ++m_pos; return *this; } XalanDequeIterator operator++(int) { XalanDequeIterator temp = *this; ++m_pos; return temp; } XalanDequeIterator& operator--() { --m_pos; return *this; } pointer operator->() { return &(*m_deque[m_pos]); } reference operator*() { return (*m_deque)[m_pos]; } const_reference operator*() const { return (*m_deque)[m_pos]; } XalanDequeIterator operator+(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos + difference); } XalanDequeIterator operator-(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos - difference); } difference_type operator-(const XalanDequeIterator &theRhs) const { return m_pos - theRhs.m_pos; } bool operator==(const XalanDequeIterator & theRhs) const { return (theRhs.m_deque == m_deque) && theRhs.m_pos == m_pos; } bool operator!=(const XalanDequeIterator & theRhs) const { return !(theRhs == *this); } XalanDeque* m_deque; size_type m_pos; }; /** * Xalan implementation of deque */ template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> > class XalanDeque { public: typedef size_t size_type; typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef XalanVector<Type, ConstructionTraits> BlockType; typedef XalanVector<BlockType*> BlockIndexType; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> iterator; typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, XalanDeque> const_iterator; #if defined(XALAN_HAS_STD_ITERATORS) typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_; #elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC) typedef XALAN_STD_QUALIFIER reverse_iterator< iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator< const_iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, const value_type> const_reverse_iterator_; #else typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator_; #endif typedef reverse_iterator_ reverse_iterator; typedef const_reverse_iterator_ const_reverse_iterator; XalanDeque( MemoryManagerType& memoryManager, size_type initialSize = 0, size_type blockSize = 10) : m_memoryManager(&memoryManager), m_blockSize(blockSize), m_blockIndex(memoryManager, initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value); } XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) : m_memoryManager(&memoryManager), m_blockSize(theRhs.m_blockSize), m_blockIndex(*theRhs.m_memoryManager, theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); } static XalanDeque* create( MemoryManagerType& theManager, size_type initialSize = 0, size_type blockSize = 10) { typedef XalanDeque ThisType; XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType))); ThisType* theResult = theGuard.get(); new (theResult) ThisType(theManager, initialSize, blockSize); theGuard.release(); return theResult; } ~XalanDeque() { clear(); typename BlockIndexType::iterator iter = m_freeBlockVector.begin(); while (iter != m_freeBlockVector.end()) { (*iter)->~XalanVector<Type, ConstructionTraits>(); deallocate(*iter); ++iter; } } iterator begin() { return iterator(this, 0); } const_iterator begin() const { return const_iterator(const_cast<XalanDeque*>(this), 0); } iterator end() { return iterator(this, size()); } const_iterator end() const { return const_iterator(const_cast<XalanDeque*>(this), size()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return m_blockIndex.empty(); } size_type size() const { if (m_blockIndex.empty()) { return 0; } else { return (m_blockIndex.size() - 1) * m_blockSize + m_blockIndex.back()->size(); } } value_type& back() { return m_blockIndex.back()->back(); } value_type& operator[](size_type index) { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } const value_type& operator[](size_type index) const { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } void clear() { typename BlockIndexType::iterator iter = m_blockIndex.begin(); m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size()); while (iter != m_blockIndex.end()) { (*iter)->clear(); m_freeBlockVector.push_back(*iter); ++iter; } m_blockIndex.clear(); } void push_back(const value_type & value) { if (m_blockIndex.empty() || m_blockIndex.back()->size() >= m_blockSize) { m_blockIndex.push_back(getNewBlock()); } m_blockIndex.back()->push_back(value); } void pop_back() { BlockType & lastBlock = *(m_blockIndex.back()); lastBlock.pop_back(); if (lastBlock.empty()) { m_freeBlockVector.push_back(&lastBlock); m_blockIndex.pop_back(); } } void resize(size_type newSize) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); if (newSize > size()) { for (size_type i = 0; i < newSize - size(); ++i) { push_back(defaultValue.value); } } else { for (size_type i = 0; i < size() - newSize; ++i) { pop_back(); } } } void swap(XalanDeque& theRhs) { MemoryManagerType* tempMemoryManager = m_memoryManager; m_memoryManager = theRhs.m_memoryManager; theRhs.m_memoryManager = tempMemoryManager; theRhs.m_blockIndex.swap(m_blockIndex); theRhs.m_freeBlockVector.swap(m_freeBlockVector); } XalanDeque & operator=(const XalanDeque & theRhs) { clear(); XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); return *this; } MemoryManagerType& getMemoryManager() { assert (m_memoryManager != 0); return *m_memoryManager; } protected: BlockType* getNewBlock() { BlockType * newBlock; if (m_freeBlockVector.empty()) { newBlock = allocate(1); new (&*newBlock) BlockType(*m_memoryManager, m_blockSize); } else { newBlock = m_freeBlockVector.back(); m_freeBlockVector.pop_back(); } assert (newBlock != 0); return newBlock; } BlockType* allocate(size_type size) { const size_type theBytesNeeded = size * sizeof(BlockType); BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded); assert(pointer != 0); return pointer; } void deallocate(BlockType* pointer) { m_memoryManager->deallocate(pointer); } MemoryManagerType* m_memoryManager; const size_type m_blockSize; BlockIndexType m_blockIndex; BlockIndexType m_freeBlockVector; private: // Not implemented XalanDeque(); XalanDeque(const XalanDeque&); }; XALAN_CPP_NAMESPACE_END #endif // XALANDEQUE_HEADER_GUARD_1357924680 <commit_msg>Fix to enable build on BC++B6<commit_after>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Matthew Hoyt (mhoyt@ca.ibm.com) */ #if !defined(XALANDEQUE_HEADER_GUARD_1357924680) #define XALANDEQUE_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <xalanc/Include/XalanVector.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class Value> struct XalanDequeIteratorTraits { typedef Value value_type; typedef Value& reference; typedef Value* pointer; typedef const Value& const_reference; }; template <class Value> struct XalanDequeConstIteratorTraits { typedef Value value_type; typedef const Value& reference; typedef const Value* pointer; typedef const Value& const_reference; }; template <class XalanDequeTraits, class XalanDeque> struct XalanDequeIterator { typedef size_t size_type; typedef typename XalanDequeTraits::value_type value_type; typedef typename XalanDequeTraits::reference reference; typedef typename XalanDequeTraits::pointer pointer; typedef typename XalanDequeTraits::const_reference const_reference; typedef ptrdiff_t difference_type; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator; typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category; XalanDequeIterator(XalanDeque* deque, size_type pos) : m_deque(deque), m_pos(pos) { } XalanDequeIterator(const Iterator & iterator) : m_deque(iterator.m_deque), m_pos(iterator.m_pos) { } XalanDequeIterator& operator=(const Iterator & iterator) { m_deque = iterator.m_deque; m_pos = iterator.m_pos; return *this; } XalanDequeIterator& operator++() { ++m_pos; return *this; } XalanDequeIterator operator++(int) { XalanDequeIterator temp = *this; ++m_pos; return temp; } XalanDequeIterator& operator--() { --m_pos; return *this; } pointer operator->() { return &(*m_deque[m_pos]); } reference operator*() { return (*m_deque)[m_pos]; } const_reference operator*() const { return (*m_deque)[m_pos]; } XalanDequeIterator operator+(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos + difference); } XalanDequeIterator operator-(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos - difference); } difference_type operator-(const XalanDequeIterator &theRhs) const { return m_pos - theRhs.m_pos; } bool operator==(const XalanDequeIterator & theRhs) const { return (theRhs.m_deque == m_deque) && theRhs.m_pos == m_pos; } bool operator!=(const XalanDequeIterator & theRhs) const { return !(theRhs == *this); } XalanDeque* m_deque; size_type m_pos; }; /** * Xalan implementation of deque */ template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> > class XalanDeque { public: typedef size_t size_type; typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef XalanVector<Type, ConstructionTraits> BlockType; typedef XalanVector<BlockType*> BlockIndexType; typedef XalanDeque<Type, ConstructionTraits> ThisType; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> iterator; typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> const_iterator; #if defined(XALAN_HAS_STD_ITERATORS) typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_; #elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC) typedef XALAN_STD_QUALIFIER reverse_iterator< iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator< const_iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, const value_type> const_reverse_iterator_; #else typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator_; #endif typedef reverse_iterator_ reverse_iterator; typedef const_reverse_iterator_ const_reverse_iterator; XalanDeque( MemoryManagerType& memoryManager, size_type initialSize = 0, size_type blockSize = 10) : m_memoryManager(&memoryManager), m_blockSize(blockSize), m_blockIndex(memoryManager, initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value); } XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) : m_memoryManager(&memoryManager), m_blockSize(theRhs.m_blockSize), m_blockIndex(*theRhs.m_memoryManager, theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); } static XalanDeque* create( MemoryManagerType& theManager, size_type initialSize = 0, size_type blockSize = 10) { typedef XalanDeque ThisType; XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType))); ThisType* theResult = theGuard.get(); new (theResult) ThisType(theManager, initialSize, blockSize); theGuard.release(); return theResult; } ~XalanDeque() { clear(); typename BlockIndexType::iterator iter = m_freeBlockVector.begin(); while (iter != m_freeBlockVector.end()) { (*iter)->~XalanVector<Type, ConstructionTraits>(); deallocate(*iter); ++iter; } } iterator begin() { return iterator(this, 0); } const_iterator begin() const { return const_iterator(const_cast<XalanDeque*>(this), 0); } iterator end() { return iterator(this, size()); } const_iterator end() const { return const_iterator(const_cast<XalanDeque*>(this), size()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return m_blockIndex.empty(); } size_type size() const { if (m_blockIndex.empty()) { return 0; } else { return (m_blockIndex.size() - 1) * m_blockSize + m_blockIndex.back()->size(); } } value_type& back() { return m_blockIndex.back()->back(); } value_type& operator[](size_type index) { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } const value_type& operator[](size_type index) const { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } void clear() { typename BlockIndexType::iterator iter = m_blockIndex.begin(); m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size()); while (iter != m_blockIndex.end()) { (*iter)->clear(); m_freeBlockVector.push_back(*iter); ++iter; } m_blockIndex.clear(); } void push_back(const value_type & value) { if (m_blockIndex.empty() || m_blockIndex.back()->size() >= m_blockSize) { m_blockIndex.push_back(getNewBlock()); } m_blockIndex.back()->push_back(value); } void pop_back() { BlockType & lastBlock = *(m_blockIndex.back()); lastBlock.pop_back(); if (lastBlock.empty()) { m_freeBlockVector.push_back(&lastBlock); m_blockIndex.pop_back(); } } void resize(size_type newSize) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); if (newSize > size()) { for (size_type i = 0; i < newSize - size(); ++i) { push_back(defaultValue.value); } } else { for (size_type i = 0; i < size() - newSize; ++i) { pop_back(); } } } void swap(XalanDeque& theRhs) { MemoryManagerType* tempMemoryManager = m_memoryManager; m_memoryManager = theRhs.m_memoryManager; theRhs.m_memoryManager = tempMemoryManager; theRhs.m_blockIndex.swap(m_blockIndex); theRhs.m_freeBlockVector.swap(m_freeBlockVector); } XalanDeque & operator=(const XalanDeque & theRhs) { clear(); XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); return *this; } MemoryManagerType& getMemoryManager() { assert (m_memoryManager != 0); return *m_memoryManager; } protected: BlockType* getNewBlock() { BlockType * newBlock; if (m_freeBlockVector.empty()) { newBlock = allocate(1); new (&*newBlock) BlockType(*m_memoryManager, m_blockSize); } else { newBlock = m_freeBlockVector.back(); m_freeBlockVector.pop_back(); } assert (newBlock != 0); return newBlock; } BlockType* allocate(size_type size) { const size_type theBytesNeeded = size * sizeof(BlockType); BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded); assert(pointer != 0); return pointer; } void deallocate(BlockType* pointer) { m_memoryManager->deallocate(pointer); } MemoryManagerType* m_memoryManager; const size_type m_blockSize; BlockIndexType m_blockIndex; BlockIndexType m_freeBlockVector; private: // Not implemented XalanDeque(); XalanDeque(const XalanDeque&); }; XALAN_CPP_NAMESPACE_END #endif // XALANDEQUE_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/* * Copyright 2009 Utkin Dmitry * * 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. */ /* * This file is part of the WSF Staff project. * Please, visit http://code.google.com/p/staff for more information. */ #include <axiom.h> #include <axis2_util.h> #include <axiom_soap.h> #include <map> #include <rise/common/ExceptionTemplate.h> #include <rise/common/exmacros.h> #include "Runtime.h" namespace staff { class Runtime::RuntimeImpl { public: RuntimeImpl(): m_pEnv(axutil_env_create_all("staff.log", GetAxis2LogLevel())) { } ~RuntimeImpl() { if (m_mEnv.size() != 0) { for (AxutilEnvMap::iterator itEnv = m_mEnv.begin(); itEnv != m_mEnv.end(); ++itEnv) { if (itEnv->second.pEnv) { axutil_env_free(itEnv->second.pEnv); } } m_mEnv.clear(); } axutil_env_free(m_pEnv); } static axutil_log_levels_t GetAxis2LogLevel() { static axutil_log_levels_t eLogLevel = static_cast<axutil_log_levels_t>(-1); if (eLogLevel == static_cast<axutil_log_levels_t>(-1)) { const char* szAxis2LogEnv = getenv("STAFF_AXIS2C_LOG_LEVEL"); if (szAxis2LogEnv) { std::string sAxis2LogEnv(szAxis2LogEnv); if (sAxis2LogEnv == "CRITICAL") { eLogLevel = AXIS2_LOG_LEVEL_CRITICAL; } else if (sAxis2LogEnv == "WARNING") { eLogLevel = AXIS2_LOG_LEVEL_WARNING; } else if (sAxis2LogEnv == "INFO") { eLogLevel = AXIS2_LOG_LEVEL_INFO; } else if (sAxis2LogEnv == "DEBUG") { eLogLevel = AXIS2_LOG_LEVEL_DEBUG; } else if (sAxis2LogEnv == "USER") { eLogLevel = AXIS2_LOG_LEVEL_USER; } else if (sAxis2LogEnv == "TRACE") { eLogLevel = AXIS2_LOG_LEVEL_TRACE; } else { eLogLevel = AXIS2_LOG_LEVEL_WARNING; } } else { eLogLevel = AXIS2_LOG_LEVEL_WARNING; } } return eLogLevel; } public: struct AxutilEnvCounted { int nCounter; axutil_env_t* pEnv; AxutilEnvCounted(): nCounter(1), pEnv(NULL) { } }; typedef std::map<std::string, AxutilEnvCounted> AxutilEnvMap; public: AxutilEnvMap m_mEnv; axutil_env_t* m_pEnv; }; Runtime::Runtime(): m_pImpl(new RuntimeImpl) { } Runtime::~Runtime() { delete m_pImpl; } Runtime& Runtime::Inst() { static Runtime tInst; return tInst; } axutil_env_t* Runtime::GetAxis2Env() { return m_pImpl->m_pEnv; } axutil_env_t* Runtime::GetAxis2Env(const std::string& sEnvComponent) { if (sEnvComponent == "staff") { return m_pImpl->m_pEnv; } RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent); if (itEnv == m_pImpl->m_mEnv.end()) { axutil_env_t* pEnv = axutil_env_create_all((sEnvComponent + ".log").c_str(), RuntimeImpl::GetAxis2LogLevel()); m_pImpl->m_mEnv[sEnvComponent].pEnv = pEnv; return pEnv; } ++itEnv->second.nCounter; return itEnv->second.pEnv; } void Runtime::FreeAxis2Env(const std::string& sEnvComponent) { RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent); if (itEnv != m_pImpl->m_mEnv.end()) { --itEnv->second.nCounter; if (itEnv->second.nCounter == 0) { axutil_env_free(itEnv->second.pEnv); m_pImpl->m_mEnv.erase(itEnv); } } } std::string Runtime::GetEnv(const std::string& rEnvVariable) const { const char* szEnv = getenv(rEnvVariable.c_str()); RISE_ASSERTES(szEnv, rise::CLogicNoItemException, "Environment variable " + rEnvVariable + " not found"); return szEnv; } std::string Runtime::GetAxis2Home() const { return GetEnv("AXIS2C_HOME"); } std::string Runtime::GetStaffHome() const { return GetEnv("STAFF_HOME"); } std::string Runtime::GetComponentsHome() const { return GetStaffHome() + RISE_PATH_SEPARATOR + std::string("components"); } std::string Runtime::GetComponentHome(const std::string& sComponent) const { return GetComponentsHome() + RISE_PATH_SEPARATOR + sComponent; } } <commit_msg>core: Runtime: fixed thread unsafety while concurent calling of GetAxis2Env and FreeAxis2Env functions<commit_after>/* * Copyright 2009 Utkin Dmitry * * 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. */ /* * This file is part of the WSF Staff project. * Please, visit http://code.google.com/p/staff for more information. */ #include <axiom.h> #include <axis2_util.h> #include <axiom_soap.h> #include <map> #include <rise/common/ExceptionTemplate.h> #include <rise/common/exmacros.h> #include <rise/threading/CriticalSection.h> #include "Runtime.h" namespace staff { class Runtime::RuntimeImpl { public: RuntimeImpl(): m_pEnv(axutil_env_create_all("staff.log", GetAxis2LogLevel())) { } ~RuntimeImpl() { if (m_mEnv.size() != 0) { for (AxutilEnvMap::iterator itEnv = m_mEnv.begin(); itEnv != m_mEnv.end(); ++itEnv) { if (itEnv->second.pEnv) { axutil_env_free(itEnv->second.pEnv); } } m_mEnv.clear(); } axutil_env_free(m_pEnv); } static axutil_log_levels_t GetAxis2LogLevel() { static axutil_log_levels_t eLogLevel = static_cast<axutil_log_levels_t>(-1); if (eLogLevel == static_cast<axutil_log_levels_t>(-1)) { const char* szAxis2LogEnv = getenv("STAFF_AXIS2C_LOG_LEVEL"); if (szAxis2LogEnv) { std::string sAxis2LogEnv(szAxis2LogEnv); if (sAxis2LogEnv == "CRITICAL") { eLogLevel = AXIS2_LOG_LEVEL_CRITICAL; } else if (sAxis2LogEnv == "WARNING") { eLogLevel = AXIS2_LOG_LEVEL_WARNING; } else if (sAxis2LogEnv == "INFO") { eLogLevel = AXIS2_LOG_LEVEL_INFO; } else if (sAxis2LogEnv == "DEBUG") { eLogLevel = AXIS2_LOG_LEVEL_DEBUG; } else if (sAxis2LogEnv == "USER") { eLogLevel = AXIS2_LOG_LEVEL_USER; } else if (sAxis2LogEnv == "TRACE") { eLogLevel = AXIS2_LOG_LEVEL_TRACE; } else { eLogLevel = AXIS2_LOG_LEVEL_WARNING; } } else { eLogLevel = AXIS2_LOG_LEVEL_WARNING; } } return eLogLevel; } public: struct AxutilEnvCounted { int nCounter; axutil_env_t* pEnv; AxutilEnvCounted(): nCounter(1), pEnv(NULL) { } }; typedef std::map<std::string, AxutilEnvCounted> AxutilEnvMap; public: AxutilEnvMap m_mEnv; axutil_env_t* m_pEnv; rise::threading::CCriticalSection m_tLock; }; Runtime::Runtime(): m_pImpl(new RuntimeImpl) { } Runtime::~Runtime() { delete m_pImpl; } Runtime& Runtime::Inst() { static Runtime tInst; return tInst; } axutil_env_t* Runtime::GetAxis2Env() { return m_pImpl->m_pEnv; } axutil_env_t* Runtime::GetAxis2Env(const std::string& sEnvComponent) { if (sEnvComponent == "staff") { return m_pImpl->m_pEnv; } { rise::threading::CScopedCriticalSection tScopedLock(m_pImpl->m_tLock); RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent); if (itEnv == m_pImpl->m_mEnv.end()) { axutil_env_t* pEnv = axutil_env_create_all((sEnvComponent + ".log").c_str(), RuntimeImpl::GetAxis2LogLevel()); m_pImpl->m_mEnv[sEnvComponent].pEnv = pEnv; return pEnv; } ++itEnv->second.nCounter; return itEnv->second.pEnv; } } void Runtime::FreeAxis2Env(const std::string& sEnvComponent) { rise::threading::CScopedCriticalSection tScopedLock(m_pImpl->m_tLock); RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent); if (itEnv != m_pImpl->m_mEnv.end()) { --itEnv->second.nCounter; if (itEnv->second.nCounter == 0) { axutil_env_free(itEnv->second.pEnv); m_pImpl->m_mEnv.erase(itEnv); } } } std::string Runtime::GetEnv(const std::string& rEnvVariable) const { const char* szEnv = getenv(rEnvVariable.c_str()); RISE_ASSERTES(szEnv, rise::CLogicNoItemException, "Environment variable " + rEnvVariable + " not found"); return szEnv; } std::string Runtime::GetAxis2Home() const { return GetEnv("AXIS2C_HOME"); } std::string Runtime::GetStaffHome() const { return GetEnv("STAFF_HOME"); } std::string Runtime::GetComponentsHome() const { return GetStaffHome() + RISE_PATH_SEPARATOR + std::string("components"); } std::string Runtime::GetComponentHome(const std::string& sComponent) const { return GetComponentsHome() + RISE_PATH_SEPARATOR + sComponent; } } <|endoftext|>
<commit_before>/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2014, Christian Rose * Team Hector, * Technische Universität Darmstadt * 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 Technische Universität Darmstadt nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ #include <hector_small_arm_ros_control/hector_small_arm_control.hpp> #include <controller_manager/controller_manager.h> namespace hector_small_arm_control { Hector_Small_Arm_Control::Hector_Small_Arm_Control() { joint_name_vector_.push_back("joint_0"); joint_name_vector_.push_back("joint_1"); joint_name_vector_.push_back("joint_2"); joint_name_vector_.push_back("joint_3"); joint_name_vector_.push_back("joint_4"); joint_name_vector_.push_back("joint_5"); joint_offset["joint_0"] = 0.14317154020265985; joint_offset["joint_1"] = -1.1351457830353746; joint_offset["joint_2"] = 1.5033011721279284; joint_offset["joint_3"] = 0.6749515466696822; joint_offset["joint_4"] = 0.32213596545598466; joint_offset["joint_5"] = 0; for(unsigned int i=0; i<joint_name_vector_.size(); i++) { joint_positions_[joint_name_vector_[i]] = 0.0; joint_velocitys_[joint_name_vector_[i]] = 0.0; joint_efforts_[joint_name_vector_[i]] = 0.0; joint_cmd_pubs_[joint_name_vector_[i]] = nh_.advertise<std_msgs::Float64>("/" + joint_name_vector_[i] + "/command", 5); ros::Subscriber sub = nh_.subscribe("/" + joint_name_vector_[i] + "/state", 1, &Hector_Small_Arm_Control::jointStateCallback, this); joint_state_subs_[joint_name_vector_[i]] = sub; nh_.setCallbackQueue(&subscriber_queue_); hardware_interface::JointStateHandle state_handle(joint_name_vector_[i], &joint_positions_[joint_name_vector_[i]], &joint_velocitys_[joint_name_vector_[i]], &joint_efforts_[joint_name_vector_[i]]); joint_state_interface_.registerHandle(state_handle); hardware_interface::JointHandle pos_handle(joint_state_interface_.getHandle(joint_name_vector_[i]), &joint_pos_cmds_[joint_name_vector_[i]]); position_joint_interface_.registerHandle(pos_handle); } registerInterface(&joint_state_interface_); registerInterface(&position_joint_interface_); subscriber_spinner_.reset(new ros::AsyncSpinner(1, &subscriber_queue_)); subscriber_spinner_->start(); _fake_dof_value = 0.0; } void Hector_Small_Arm_Control::cleanup() { subscriber_spinner_->stop(); } void Hector_Small_Arm_Control::read(ros::Time time, ros::Duration period) { if(received_joint_states_.size()<5){ return; } for(unsigned int i=0; i<joint_name_vector_.size()-1; i++) { joint_positions_[joint_name_vector_[i]] = received_joint_states_[joint_name_vector_[i]]->current_pos - joint_offset[joint_name_vector_[i]]; } //take last dof as fake joint_positions_[joint_name_vector_[joint_name_vector_.size()-1]] = _fake_dof_value; } void Hector_Small_Arm_Control::write(ros::Time time, ros::Duration period) { for(unsigned int i=0; i<joint_name_vector_.size(); i++) { std_msgs::Float64 msg; msg.data = joint_pos_cmds_[joint_name_vector_[i]]; joint_cmd_pubs_[joint_name_vector_[i]].publish(msg); } //remember last joint value for fake 6. dof _fake_dof_value = joint_pos_cmds_[joint_name_vector_[joint_name_vector_.size()-1]]; } void Hector_Small_Arm_Control::jointStateCallback(const dynamixel_msgs::JointStateConstPtr& dyn_joint_state) { // received_joint_states_[dyn_joint_state->name] = dyn_joint_state; } } int main(int argc, char** argv){ try{ ROS_INFO("starting"); ros::init(argc, argv, "hector_small_arm_control"); hector_small_arm_control::Hector_Small_Arm_Control hector_small_arm; controller_manager::ControllerManager cm(&hector_small_arm); ros::AsyncSpinner spinner(4); spinner.start(); ros::Rate loop_rate(50); ros::Time last_time = ros::Time::now(); while (ros::ok()) { //ROS_INFO("in main loop"); loop_rate.sleep(); ros::Time current_time = ros::Time::now(); ros::Duration elapsed_time = current_time - last_time; last_time = current_time; //ROS_INFO("before read"); hector_small_arm.read(current_time, elapsed_time); //ROS_INFO("after read"); //ROS_INFO("before cm.update"); cm.update(current_time, elapsed_time); //ROS_INFO("after cm.update"); //ROS_INFO("before write"); hector_small_arm.write(current_time, elapsed_time); //ROS_INFO("after write"); } hector_small_arm.cleanup(); } catch(...) { ROS_ERROR("Unhandled exception!"); return -1; } return 0; } <commit_msg>offset for reading and writing now<commit_after>/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2014, Christian Rose * Team Hector, * Technische Universität Darmstadt * 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 Technische Universität Darmstadt nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ #include <hector_small_arm_ros_control/hector_small_arm_control.hpp> #include <controller_manager/controller_manager.h> namespace hector_small_arm_control { Hector_Small_Arm_Control::Hector_Small_Arm_Control() { joint_name_vector_.push_back("joint_0"); joint_name_vector_.push_back("joint_1"); joint_name_vector_.push_back("joint_2"); joint_name_vector_.push_back("joint_3"); joint_name_vector_.push_back("joint_4"); joint_name_vector_.push_back("joint_5"); joint_offset["joint_0"] = 0.14317154020265985; joint_offset["joint_1"] = -1.1351457830353746; joint_offset["joint_2"] = 1.5033011721279284; joint_offset["joint_3"] = 0.6749515466696822; joint_offset["joint_4"] = 0.32213596545598466; joint_offset["joint_5"] = 0; for(unsigned int i=0; i<joint_name_vector_.size(); i++) { joint_positions_[joint_name_vector_[i]] = 0.0; joint_velocitys_[joint_name_vector_[i]] = 0.0; joint_efforts_[joint_name_vector_[i]] = 0.0; joint_cmd_pubs_[joint_name_vector_[i]] = nh_.advertise<std_msgs::Float64>("/" + joint_name_vector_[i] + "/command", 5); ros::Subscriber sub = nh_.subscribe("/" + joint_name_vector_[i] + "/state", 1, &Hector_Small_Arm_Control::jointStateCallback, this); joint_state_subs_[joint_name_vector_[i]] = sub; nh_.setCallbackQueue(&subscriber_queue_); hardware_interface::JointStateHandle state_handle(joint_name_vector_[i], &joint_positions_[joint_name_vector_[i]], &joint_velocitys_[joint_name_vector_[i]], &joint_efforts_[joint_name_vector_[i]]); joint_state_interface_.registerHandle(state_handle); hardware_interface::JointHandle pos_handle(joint_state_interface_.getHandle(joint_name_vector_[i]), &joint_pos_cmds_[joint_name_vector_[i]]); position_joint_interface_.registerHandle(pos_handle); } registerInterface(&joint_state_interface_); registerInterface(&position_joint_interface_); subscriber_spinner_.reset(new ros::AsyncSpinner(1, &subscriber_queue_)); subscriber_spinner_->start(); _fake_dof_value = 0.0; } void Hector_Small_Arm_Control::cleanup() { subscriber_spinner_->stop(); } void Hector_Small_Arm_Control::read(ros::Time time, ros::Duration period) { if(received_joint_states_.size()<5){ return; } for(unsigned int i=0; i<joint_name_vector_.size()-1; i++) { joint_positions_[joint_name_vector_[i]] = received_joint_states_[joint_name_vector_[i]]->current_pos - joint_offset[joint_name_vector_[i]]; } //take last dof as fake joint_positions_[joint_name_vector_[joint_name_vector_.size()-1]] = _fake_dof_value; } void Hector_Small_Arm_Control::write(ros::Time time, ros::Duration period) { for(unsigned int i=0; i<joint_name_vector_.size(); i++) { std_msgs::Float64 msg; msg.data = joint_pos_cmds_[joint_name_vector_[i]] + joint_offset[joint_name_vector_[i]]; joint_cmd_pubs_[joint_name_vector_[i]].publish(msg); } //remember last joint value for fake 6. dof _fake_dof_value = joint_pos_cmds_[joint_name_vector_[joint_name_vector_.size()-1]]; } void Hector_Small_Arm_Control::jointStateCallback(const dynamixel_msgs::JointStateConstPtr& dyn_joint_state) { // received_joint_states_[dyn_joint_state->name] = dyn_joint_state; } } int main(int argc, char** argv){ try{ ROS_INFO("starting"); ros::init(argc, argv, "hector_small_arm_control"); hector_small_arm_control::Hector_Small_Arm_Control hector_small_arm; controller_manager::ControllerManager cm(&hector_small_arm); ros::AsyncSpinner spinner(4); spinner.start(); ros::Rate loop_rate(50); ros::Time last_time = ros::Time::now(); while (ros::ok()) { //ROS_INFO("in main loop"); loop_rate.sleep(); ros::Time current_time = ros::Time::now(); ros::Duration elapsed_time = current_time - last_time; last_time = current_time; //ROS_INFO("before read"); hector_small_arm.read(current_time, elapsed_time); //ROS_INFO("after read"); //ROS_INFO("before cm.update"); cm.update(current_time, elapsed_time); //ROS_INFO("after cm.update"); //ROS_INFO("before write"); hector_small_arm.write(current_time, elapsed_time); //ROS_INFO("after write"); } hector_small_arm.cleanup(); } catch(...) { ROS_ERROR("Unhandled exception!"); return -1; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: bulitem.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ka $ $Date: 2001-10-31 16:48:59 $ * * 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 _SVX_BULITEM_HXX #define _SVX_BULITEM_HXX // include --------------------------------------------------------------- // define ---------------------------------------------------------------- // Styles #define BS_ABC_BIG 0 #define BS_ABC_SMALL 1 #define BS_ROMAN_BIG 2 #define BS_ROMAN_SMALL 3 #define BS_123 4 #define BS_NONE 5 #define BS_BULLET 6 #define BS_BMP 128 // Justification #define BJ_HLEFT 0x01 #define BJ_HRIGHT 0x02 #define BJ_HCENTER 0x04 #define BJ_VTOP 0x08 #define BJ_VBOTTOM 0x10 #define BJ_VCENTER 0x20 // Valid-Bits // Erstmal nur die Werte, die vom Dialog geaendert werden... #define VALID_FONTCOLOR 0x0001 #define VALID_FONTNAME 0x0002 #define VALID_SYMBOL 0x0004 #define VALID_BITMAP 0x0008 #define VALID_SCALE 0x0010 #define VALID_START 0x0020 #define VALID_STYLE 0x0040 #define VALID_PREVTEXT 0x0080 #define VALID_FOLLOWTEXT 0x0100 #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _VCL_FONT_HXX //autogen #include <vcl/font.hxx> #endif #ifndef _GRFMGR_HXX //autogen #include <goodies/grfmgr.hxx> #endif // class SvxBulletItem --------------------------------------------------- class SvxBulletItem : public SfxPoolItem { Font aFont; GraphicObject* pGraphicObject; String aPrevText; String aFollowText; USHORT nStart; USHORT nStyle; long nWidth; USHORT nScale; sal_Unicode cSymbol; BYTE nJustify; USHORT nValidMask; // Nur temporaer fuer GetAttribs/SetAttribs, wegen des grossen Bullets #ifdef _SVX_BULITEM_CXX void SetDefaultFont_Impl(); void SetDefaults_Impl(); #endif public: TYPEINFO(); SvxBulletItem( USHORT nWhich = 0 ); SvxBulletItem( BYTE nStyle, const Font& rFont, USHORT nStart = 0, USHORT nWhich = 0 ); SvxBulletItem( const Font& rFont, sal_Unicode cSymbol, USHORT nWhich=0 ); SvxBulletItem( const Bitmap&, USHORT nWhich = 0 ); SvxBulletItem( const GraphicObject&, USHORT nWhich = 0 ); SvxBulletItem( SvStream& rStrm, USHORT nWhich = 0 ); SvxBulletItem( const SvxBulletItem& ); ~SvxBulletItem(); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create( SvStream&, USHORT nVersion ) const; virtual SvStream& Store( SvStream & , USHORT nItemVersion ) const; String GetFullText() const; sal_Unicode GetSymbol() const { return cSymbol; } String GetPrevText() const { return aPrevText; } String GetFollowText() const { return aFollowText; } USHORT GetStart() const { return nStart; } long GetWidth() const { return nWidth; } USHORT GetStyle() const { return nStyle; } BYTE GetJustification() const { return nJustify; } Font GetFont() const { return aFont; } USHORT GetScale() const { return nScale; } Bitmap GetBitmap() const; void SetBitmap( const Bitmap& rBmp ); const GraphicObject& GetGraphicObject() const; void SetGraphicObject( const GraphicObject& rGraphicObject ); void SetSymbol( sal_Unicode c) { cSymbol = c; } void SetPrevText( const String& rStr) { aPrevText = rStr;} void SetFollowText(const String& rStr) { aFollowText=rStr;} void SetStart( USHORT nNew ) { nStart = nNew; } void SetWidth( long nNew ) { nWidth = nNew; } void SetStyle( USHORT nNew ) { nStyle = nNew; } void SetJustification( BYTE nNew ) { nJustify = nNew; } void SetFont( const Font& rNew) { aFont = rNew; } void SetScale( USHORT nNew ) { nScale = nNew; } virtual USHORT GetVersion(USHORT nFileVersion) const; virtual int operator==( const SfxPoolItem& ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper * = 0 ) const; static void StoreFont( SvStream&, const Font& ); static Font CreateFont( SvStream&, USHORT nVer ); USHORT& GetValidMask() { return nValidMask; } USHORT GetValidMask() const { return nValidMask; } USHORT IsValid( USHORT nFlag ) const { return nValidMask & nFlag; } void SetValid( USHORT nFlag, BOOL bValid ) { if ( bValid ) nValidMask |= nFlag; else nValidMask &= ~nFlag; } void CopyValidProperties( const SvxBulletItem& rCopyFrom ); }; #endif <commit_msg>INTEGRATION: CWS visibility01 (1.3.1022); FILE MERGED 2004/12/06 08:10:10 mnicel 1.3.1022.1: Part of symbol visibility markup - #i35758#<commit_after>/************************************************************************* * * $RCSfile: bulitem.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 14:10:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_BULITEM_HXX #define _SVX_BULITEM_HXX // include --------------------------------------------------------------- #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // define ---------------------------------------------------------------- // Styles #define BS_ABC_BIG 0 #define BS_ABC_SMALL 1 #define BS_ROMAN_BIG 2 #define BS_ROMAN_SMALL 3 #define BS_123 4 #define BS_NONE 5 #define BS_BULLET 6 #define BS_BMP 128 // Justification #define BJ_HLEFT 0x01 #define BJ_HRIGHT 0x02 #define BJ_HCENTER 0x04 #define BJ_VTOP 0x08 #define BJ_VBOTTOM 0x10 #define BJ_VCENTER 0x20 // Valid-Bits // Erstmal nur die Werte, die vom Dialog geaendert werden... #define VALID_FONTCOLOR 0x0001 #define VALID_FONTNAME 0x0002 #define VALID_SYMBOL 0x0004 #define VALID_BITMAP 0x0008 #define VALID_SCALE 0x0010 #define VALID_START 0x0020 #define VALID_STYLE 0x0040 #define VALID_PREVTEXT 0x0080 #define VALID_FOLLOWTEXT 0x0100 #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _VCL_FONT_HXX //autogen #include <vcl/font.hxx> #endif #ifndef _GRFMGR_HXX //autogen #include <goodies/grfmgr.hxx> #endif // class SvxBulletItem --------------------------------------------------- class SVX_DLLPUBLIC SvxBulletItem : public SfxPoolItem { Font aFont; GraphicObject* pGraphicObject; String aPrevText; String aFollowText; USHORT nStart; USHORT nStyle; long nWidth; USHORT nScale; sal_Unicode cSymbol; BYTE nJustify; USHORT nValidMask; // Nur temporaer fuer GetAttribs/SetAttribs, wegen des grossen Bullets #ifdef _SVX_BULITEM_CXX void SetDefaultFont_Impl(); void SetDefaults_Impl(); #endif public: TYPEINFO(); SvxBulletItem( USHORT nWhich = 0 ); SvxBulletItem( BYTE nStyle, const Font& rFont, USHORT nStart = 0, USHORT nWhich = 0 ); SvxBulletItem( const Font& rFont, sal_Unicode cSymbol, USHORT nWhich=0 ); SvxBulletItem( const Bitmap&, USHORT nWhich = 0 ); SvxBulletItem( const GraphicObject&, USHORT nWhich = 0 ); SvxBulletItem( SvStream& rStrm, USHORT nWhich = 0 ); SvxBulletItem( const SvxBulletItem& ); ~SvxBulletItem(); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxPoolItem* Create( SvStream&, USHORT nVersion ) const; virtual SvStream& Store( SvStream & , USHORT nItemVersion ) const; String GetFullText() const; sal_Unicode GetSymbol() const { return cSymbol; } String GetPrevText() const { return aPrevText; } String GetFollowText() const { return aFollowText; } USHORT GetStart() const { return nStart; } long GetWidth() const { return nWidth; } USHORT GetStyle() const { return nStyle; } BYTE GetJustification() const { return nJustify; } Font GetFont() const { return aFont; } USHORT GetScale() const { return nScale; } Bitmap GetBitmap() const; void SetBitmap( const Bitmap& rBmp ); const GraphicObject& GetGraphicObject() const; void SetGraphicObject( const GraphicObject& rGraphicObject ); void SetSymbol( sal_Unicode c) { cSymbol = c; } void SetPrevText( const String& rStr) { aPrevText = rStr;} void SetFollowText(const String& rStr) { aFollowText=rStr;} void SetStart( USHORT nNew ) { nStart = nNew; } void SetWidth( long nNew ) { nWidth = nNew; } void SetStyle( USHORT nNew ) { nStyle = nNew; } void SetJustification( BYTE nNew ) { nJustify = nNew; } void SetFont( const Font& rNew) { aFont = rNew; } void SetScale( USHORT nNew ) { nScale = nNew; } virtual USHORT GetVersion(USHORT nFileVersion) const; virtual int operator==( const SfxPoolItem& ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper * = 0 ) const; static void StoreFont( SvStream&, const Font& ); static Font CreateFont( SvStream&, USHORT nVer ); USHORT& GetValidMask() { return nValidMask; } USHORT GetValidMask() const { return nValidMask; } USHORT IsValid( USHORT nFlag ) const { return nValidMask & nFlag; } void SetValid( USHORT nFlag, BOOL bValid ) { if ( bValid ) nValidMask |= nFlag; else nValidMask &= ~nFlag; } void CopyValidProperties( const SvxBulletItem& rCopyFrom ); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: galmisc.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: ihi $ $Date: 2006-08-29 14:26:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_GALMISC_HXX_ #define _SVX_GALMISC_HXX_ #include <sot/storage.hxx> #include <tools/urlobj.hxx> #include <svtools/imap.hxx> #include <svtools/hint.hxx> #include <svtools/transfer.hxx> #include "svdobj.hxx" #include "galobj.hxx" #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP #include <com/sun/star/awt/XProgressMonitor.hpp> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // ----------- // - Defines - // ----------- #define IV_IMAPINFO (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000) #define ID_IMAPINFO 2 #define USERDATA_HDL() (LINK(this,SgaUserDataFactory,MakeUserData)) #define GAL_RESID( nId ) ResId( nId, GetGalleryResMgr() ) #define STREAMBUF_SIZE 16384L #define SGA_IMPORT_NONE 0x0000 #define SGA_IMPORT_FILE 0x0001 #define SGA_IMPORT_INET 0x0002 #define GALLERY_PROGRESS_RANGE 10000 #define GALLERY_FG_COLOR Application::GetSettings().GetStyleSettings().GetWindowTextColor() #define GALLERY_BG_COLOR Application::GetSettings().GetStyleSettings().GetWindowColor() #define GALLERY_DLG_COLOR Application::GetSettings().GetStyleSettings().GetDialogColor() // ------------- // - Functions - // ------------- class ResMgr; class String; class SvStream; class Graphic; class FmFormModel; class ImageMap; class Gallery; SVX_DLLPUBLIC ResMgr* GetGalleryResMgr(); USHORT GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE ); BOOL GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel ); BOOL CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap ); SVX_DLLPUBLIC String GetReducedString( const INetURLObject& rURL, ULONG nMaxLen ); String GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL ); BOOL FileExists( const INetURLObject& rURL ); BOOL CreateDir( const INetURLObject& rURL ); BOOL CopyFile( const INetURLObject& rSrcURL, const INetURLObject& rDstURL ); BOOL KillFile( const INetURLObject& rURL ); BitmapEx GalleryResGetBitmapEx( sal_uInt32 nId ); // --------------- // - SgaIMapInfo - // --------------- class SgaIMapInfo : public SdrObjUserData, public SfxListener { ImageMap aImageMap; public: SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {}; SgaIMapInfo( const ImageMap& rImageMap) : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ), aImageMap( rImageMap ) {}; virtual ~SgaIMapInfo() {}; virtual SdrObjUserData* Clone( SdrObject* ) const { SgaIMapInfo* pInfo = new SgaIMapInfo; pInfo->aImageMap = aImageMap; return pInfo; } const ImageMap& GetImageMap() const { return aImageMap; } }; // ---------------------- // - SgaUserDataFactory - // ---------------------- class SgaUserDataFactory { public: SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); } ~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); } DECL_LINK( MakeUserData, SdrObjFactory* ); }; // ------------------- // - GalleryProgress - // ------------------- class GraphicFilter; class SVX_DLLPUBLIC GalleryProgress { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar; GraphicFilter* mpFilter; DECL_LINK( Update, GraphicFilter * ); public: GalleryProgress( GraphicFilter* pFilter = NULL ); ~GalleryProgress(); void Update( ULONG nVal, ULONG nMaxVal ); }; // ----------------------- // - GalleryTransferable - // ----------------------- class Gallery; class GalleryTheme; class GraphicObject; class GalleryTransferable : public TransferableHelper { friend class GalleryTheme; private: GalleryTheme* mpTheme; SgaObjKind meObjectKind; sal_uInt32 mnObjectPos; SotStorageStreamRef mxModelStream; GraphicObject* mpGraphicObject; ImageMap* mpImageMap; INetURLObject* mpURL; protected: GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos, bool bLazy ); ~GalleryTransferable(); void InitData( bool bLazy ); // TransferableHelper virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void DragFinished( sal_Int8 nDropAction ); virtual void ObjectReleased(); void CopyToClipboard( Window* pWindow ); void StartDrag( Window* pWindow, sal_Int8 nDragSourceActions, sal_Int32 nDragPointer = DND_POINTER_NONE, sal_Int32 nDragImage = DND_IMAGE_NONE ); }; // --------------- // - GalleryHint - // --------------- #define GALLERY_HINT_NONE 0x00000000 #define GALLERY_HINT_CLOSE_THEME 0x00000001 #define GALLERY_HINT_THEME_REMOVED 0x00000002 #define GALLERY_HINT_THEME_RENAMED 0x00000004 #define GALLERY_HINT_THEME_CREATED 0x00000008 #define GALLERY_HINT_THEME_UPDATEVIEW 0x00000010 #define GALLERY_HINT_CLOSE_OBJECT 0x00000020 #define GALLERY_HINT_OBJECT_REMOVED 0x00000040 // ----------------------------------------------------------------------------- class GalleryHint : public SfxHint { private: ULONG mnType; String maThemeName; String maStringData; ULONG mnData1; ULONG mnData2; public: GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) : mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {} GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) : mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {} ULONG GetType() const { return mnType; } const String& GetThemeName() const { return maThemeName; } const String& GetStringData() const { return maStringData; } ULONG GetData1() const { return mnData1; } ULONG GetData2() const { return mnData2; } }; #endif <commit_msg>INTEGRATION: CWS sb59 (1.12.60); FILE MERGED 2006/08/03 13:47:03 cl 1.12.60.1: removed compiler warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: galmisc.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2006-10-12 11:44:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_GALMISC_HXX_ #define _SVX_GALMISC_HXX_ #include <sot/storage.hxx> #include <tools/urlobj.hxx> #include <svtools/imap.hxx> #include <svtools/hint.hxx> #include <svtools/transfer.hxx> #include "svdobj.hxx" #include "galobj.hxx" #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP #include <com/sun/star/awt/XProgressMonitor.hpp> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // ----------- // - Defines - // ----------- #define IV_IMAPINFO (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000) #define ID_IMAPINFO 2 #define USERDATA_HDL() (LINK(this,SgaUserDataFactory,MakeUserData)) #define GAL_RESID( nId ) ResId( nId, GetGalleryResMgr() ) #define STREAMBUF_SIZE 16384L #define SGA_IMPORT_NONE 0x0000 #define SGA_IMPORT_FILE 0x0001 #define SGA_IMPORT_INET 0x0002 #define GALLERY_PROGRESS_RANGE 10000 #define GALLERY_FG_COLOR Application::GetSettings().GetStyleSettings().GetWindowTextColor() #define GALLERY_BG_COLOR Application::GetSettings().GetStyleSettings().GetWindowColor() #define GALLERY_DLG_COLOR Application::GetSettings().GetStyleSettings().GetDialogColor() // ------------- // - Functions - // ------------- class ResMgr; class String; class SvStream; class Graphic; class FmFormModel; class ImageMap; class Gallery; SVX_DLLPUBLIC ResMgr* GetGalleryResMgr(); USHORT GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE ); BOOL GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel ); BOOL CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap ); SVX_DLLPUBLIC String GetReducedString( const INetURLObject& rURL, ULONG nMaxLen ); String GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL ); BOOL FileExists( const INetURLObject& rURL ); BOOL CreateDir( const INetURLObject& rURL ); BOOL CopyFile( const INetURLObject& rSrcURL, const INetURLObject& rDstURL ); BOOL KillFile( const INetURLObject& rURL ); BitmapEx GalleryResGetBitmapEx( sal_uInt32 nId ); // --------------- // - SgaIMapInfo - // --------------- class SgaIMapInfo : public SdrObjUserData, public SfxListener { ImageMap aImageMap; public: SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {}; SgaIMapInfo( const ImageMap& rImageMap) : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ), aImageMap( rImageMap ) {}; virtual ~SgaIMapInfo() {}; virtual SdrObjUserData* Clone( SdrObject* ) const { SgaIMapInfo* pInfo = new SgaIMapInfo; pInfo->aImageMap = aImageMap; return pInfo; } const ImageMap& GetImageMap() const { return aImageMap; } }; // ---------------------- // - SgaUserDataFactory - // ---------------------- class SgaUserDataFactory { public: SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); } ~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); } DECL_LINK( MakeUserData, SdrObjFactory* ); }; // ------------------- // - GalleryProgress - // ------------------- class GraphicFilter; class SVX_DLLPUBLIC GalleryProgress { ::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar; GraphicFilter* mpFilter; DECL_LINK( Update, GraphicFilter * ); public: GalleryProgress( GraphicFilter* pFilter = NULL ); ~GalleryProgress(); void Update( ULONG nVal, ULONG nMaxVal ); }; // ----------------------- // - GalleryTransferable - // ----------------------- class Gallery; class GalleryTheme; class GraphicObject; class GalleryTransferable : public TransferableHelper { friend class GalleryTheme; using TransferableHelper::CopyToClipboard; private: GalleryTheme* mpTheme; SgaObjKind meObjectKind; sal_uInt32 mnObjectPos; SotStorageStreamRef mxModelStream; GraphicObject* mpGraphicObject; ImageMap* mpImageMap; INetURLObject* mpURL; protected: GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos, bool bLazy ); ~GalleryTransferable(); void InitData( bool bLazy ); // TransferableHelper virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void DragFinished( sal_Int8 nDropAction ); virtual void ObjectReleased(); void CopyToClipboard( Window* pWindow ); void StartDrag( Window* pWindow, sal_Int8 nDragSourceActions, sal_Int32 nDragPointer = DND_POINTER_NONE, sal_Int32 nDragImage = DND_IMAGE_NONE ); }; // --------------- // - GalleryHint - // --------------- #define GALLERY_HINT_NONE 0x00000000 #define GALLERY_HINT_CLOSE_THEME 0x00000001 #define GALLERY_HINT_THEME_REMOVED 0x00000002 #define GALLERY_HINT_THEME_RENAMED 0x00000004 #define GALLERY_HINT_THEME_CREATED 0x00000008 #define GALLERY_HINT_THEME_UPDATEVIEW 0x00000010 #define GALLERY_HINT_CLOSE_OBJECT 0x00000020 #define GALLERY_HINT_OBJECT_REMOVED 0x00000040 // ----------------------------------------------------------------------------- class GalleryHint : public SfxHint { private: ULONG mnType; String maThemeName; String maStringData; ULONG mnData1; ULONG mnData2; public: GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) : mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {} GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) : mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {} ULONG GetType() const { return mnType; } const String& GetThemeName() const { return maThemeName; } const String& GetStringData() const { return maStringData; } ULONG GetData1() const { return mnData1; } ULONG GetData2() const { return mnData2; } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pszctrl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-09-09 15:37:56 $ * * 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 _SVX_PSZCTRL_HXX #define _SVX_PSZCTRL_HXX // include --------------------------------------------------------------- #ifndef _SFXSTBITEM_HXX //autogen #include <sfx2/stbitem.hxx> #endif // forward --------------------------------------------------------------- class SvxSizeItem; struct SvxPosSizeStatusBarControl_Impl; // class SvxPosSizeToolBoxControl ---------------------------------------- class SvxPosSizeStatusBarControl : public SfxStatusBarControl { private: SvxPosSizeStatusBarControl_Impl* pImp; public: SFX_DECL_STATUSBAR_CONTROL(); SvxPosSizeStatusBarControl( USHORT nSlotId, USHORT nId, StatusBar& rStb ); ~SvxPosSizeStatusBarControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void Paint( const UserDrawEvent& rEvt ); virtual void Command( const CommandEvent& rCEvt ); static ULONG GetDefItemWidth( const StatusBar& rStb ); }; #endif <commit_msg>INTEGRATION: CWS visibility01 (1.2.86); FILE MERGED 2004/11/19 12:54:22 mmeeks 1.2.86.1: Issue number: #i35758# Submitted by: mnicel Reviewed by: mmeeks<commit_after>/************************************************************************* * * $RCSfile: pszctrl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-21 15:10:18 $ * * 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 _SVX_PSZCTRL_HXX #define _SVX_PSZCTRL_HXX // include --------------------------------------------------------------- #ifndef _SFXSTBITEM_HXX //autogen #include <sfx2/stbitem.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // forward --------------------------------------------------------------- class SvxSizeItem; struct SvxPosSizeStatusBarControl_Impl; // class SvxPosSizeToolBoxControl ---------------------------------------- class SVX_DLLPUBLIC SvxPosSizeStatusBarControl : public SfxStatusBarControl { private: SvxPosSizeStatusBarControl_Impl* pImp; public: SFX_DECL_STATUSBAR_CONTROL(); SvxPosSizeStatusBarControl( USHORT nSlotId, USHORT nId, StatusBar& rStb ); ~SvxPosSizeStatusBarControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void Paint( const UserDrawEvent& rEvt ); virtual void Command( const CommandEvent& rCEvt ); static ULONG GetDefItemWidth( const StatusBar& rStb ); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: swdbdata.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: os $ $Date: 2001-03-30 11:59:05 $ * * 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 _SWDBDATA_HXX #define _SWDBDATA_HXX #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif // contains the description of a data source struct SwDBData { ::rtl::OUString sDataSource; ::rtl::OUString sCommand; //table, query or statement sal_Int32 nCommandType; //com::sun::star::sdb::CommandType SwDBData() : nCommandType(0){} BOOL operator !=(const SwDBData& rCmp) const {return rCmp.sDataSource != sDataSource || rCmp.sCommand != sCommand || rCmp.nCommandType != nCommandType;} BOOL operator ==(const SwDBData& rCmp) const {return rCmp.sDataSource == sDataSource && rCmp.sCommand == sCommand && rCmp.nCommandType == nCommandType;} }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.1450); FILE MERGED 2005/09/05 13:36:32 rt 1.2.1450.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: swdbdata.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:12: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 * ************************************************************************/ #ifndef _SWDBDATA_HXX #define _SWDBDATA_HXX #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif // contains the description of a data source struct SwDBData { ::rtl::OUString sDataSource; ::rtl::OUString sCommand; //table, query or statement sal_Int32 nCommandType; //com::sun::star::sdb::CommandType SwDBData() : nCommandType(0){} BOOL operator !=(const SwDBData& rCmp) const {return rCmp.sDataSource != sDataSource || rCmp.sCommand != sCommand || rCmp.nCommandType != nCommandType;} BOOL operator ==(const SwDBData& rCmp) const {return rCmp.sDataSource == sDataSource && rCmp.sCommand == sCommand && rCmp.nCommandType == nCommandType;} }; #endif <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file unnormalized_evaluation.hpp * \date May 2014 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com) */ #ifndef FL__DISTRIBUTION__INTERFACE__UNNORMALIZED_EVAUATION_HPP #define FL__DISTRIBUTION__INTERFACE__UNNORMALIZED_EVAUATION_HPP #include <cmath> namespace fl { /** * \interface UnnormalizedEvaluation * \ingroup distribution_interfaces * * UnnormalizedEvaluation represents the part of a distribution interface * which evaluates the unnormalized probability \f$\tilde{p}(x)\f$ of a sample * \f$x\f$ according to the implemented distribution. Unnormalized in this * context means the integral * * \f[ \int\limits_{-\infty}^{\infty} \tilde{p}(x) dx \in (-\infty; \infty) \f] * * does not necessarliy integrate to 1. */ template <typename Variate, typename Scalar> class UnnormalizedEvaluation { public: virtual ~UnnormalizedEvaluation() { } /** * Determines the normalized or unnormalized probability for the specified * variate. * * \param variate The sample \f$x\f$ to evaluate * * \return \f$\tilde{p}(x)\f$ */ virtual Scalar unnormalized_probability(const Variate& variate) const { std::exp(log_unnormalized_probability(variate)); } /** * The log of the unnormalized probability of the specified variate * * \param variate The sample \f$x\f$ to evaluate * * \return \f$\ln(\tilde{p}(x))\f$ */ virtual Scalar log_unnormalized_probability(const Variate& variate) const = 0; }; } #endif <commit_msg>fixed unnormalized_probability<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file unnormalized_evaluation.hpp * \date May 2014 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com) */ #ifndef FL__DISTRIBUTION__INTERFACE__UNNORMALIZED_EVAUATION_HPP #define FL__DISTRIBUTION__INTERFACE__UNNORMALIZED_EVAUATION_HPP #include <cmath> namespace fl { /** * \interface UnnormalizedEvaluation * \ingroup distribution_interfaces * * UnnormalizedEvaluation represents the part of a distribution interface * which evaluates the unnormalized probability \f$\tilde{p}(x)\f$ of a sample * \f$x\f$ according to the implemented distribution. Unnormalized in this * context means the integral * * \f[ \int\limits_{-\infty}^{\infty} \tilde{p}(x) dx \in (-\infty; \infty) \f] * * does not necessarliy integrate to 1. */ template <typename Variate, typename Scalar> class UnnormalizedEvaluation { public: virtual ~UnnormalizedEvaluation() { } /** * Determines the normalized or unnormalized probability for the specified * variate. * * \param variate The sample \f$x\f$ to evaluate * * \return \f$\tilde{p}(x)\f$ */ virtual Scalar unnormalized_probability(const Variate& variate) const { return std::exp(log_unnormalized_probability(variate)); } /** * The log of the unnormalized probability of the specified variate * * \param variate The sample \f$x\f$ to evaluate * * \return \f$\ln(\tilde{p}(x))\f$ */ virtual Scalar log_unnormalized_probability(const Variate& variate) const = 0; }; } #endif <|endoftext|>
<commit_before><commit_msg>Use bool instead of int<commit_after><|endoftext|>
<commit_before><commit_msg>devel: Added multiplicativeSeparability implementation<commit_after>namespace mant { template <typename ParameterType> class MultiplicativeSeparability : public Property<ParameterType> { public: bool isSeparable() const noexcept; void isSeparable(const bool isSeparable) noexcept; std::vector<arma::Col<unsigned int>> getSeparation() const noexcept; void setSeparation( const std::vector<arma::Col<unsigned int>>& separation); protected: bool isSeparable_; std::vector<arma::Col<unsigned int>> separation_; }; // // Implementation // template <typename ParameterType> bool MultiplicativeSeparability<ParameterType>::isSeparable() const noexcept { return isSeparable_; } template <typename ParameterType> void MultiplicativeSeparability<ParameterType>::isSeparable(const bool isSeparable) noexcept { isSeparable_ = isSeparable; } template <typename ParameterType> std::vector<arma::Col<unsigned int>> MultiplicativeSeparability<ParameterType>::getSeparation() const noexcept { return separation_; } template <typename ParameterType> void MultiplicativeSeparability<ParameterType>::setSeparation( const std::vector<arma::Col<unsigned int>>& separation) { separation_ = separation; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: radiobtnbox.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:35:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" /* #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif */ // include --------------------------------------------------------------- #include "radiobtnbox.hxx" #include <svx/dialmgr.hxx> namespace svx { // class SvxRadioButtonListBox ---------------------------------------------------- SvxRadioButtonListBox::SvxRadioButtonListBox( Window* _pParent, const ResId& _rId ) : SvxSimpleTable( _pParent, _rId ) { EnableCheckButton( new SvLBoxButtonData( this, true ) ); } SvxRadioButtonListBox::~SvxRadioButtonListBox() { } void SvxRadioButtonListBox::SetTabs() { SvxSimpleTable::SetTabs(); /* USHORT nAdjust = SV_LBOXTAB_ADJUST_RIGHT | SV_LBOXTAB_ADJUST_LEFT | SV_LBOXTAB_ADJUST_CENTER | SV_LBOXTAB_ADJUST_NUMERIC | SV_LBOXTAB_FORCE; if ( aTabs.Count() > 0 ) { SvLBoxTab* pTab = (SvLBoxTab*)aTabs.GetObject(0); pTab->nFlags &= ~nAdjust; pTab->nFlags |= SV_LBOXTAB_PUSHABLE | SV_LBOXTAB_ADJUST_CENTER | SV_LBOXTAB_FORCE; } */ } void SvxRadioButtonListBox::MouseButtonUp( const MouseEvent& _rMEvt ) { m_aCurMousePoint = _rMEvt.GetPosPixel(); SvxSimpleTable::MouseButtonUp( _rMEvt ); } void SvxRadioButtonListBox::KeyInput( const KeyEvent& rKEvt ) { if ( !rKEvt.GetKeyCode().GetModifier() && KEY_SPACE == rKEvt.GetKeyCode().GetCode() ) { SvLBoxEntry* pEntry = FirstSelected(); if ( GetCheckButtonState( pEntry ) == SV_BUTTON_UNCHECKED ) { SetCheckButtonState( pEntry, SV_BUTTON_CHECKED ); GetCheckButtonHdl().Call( NULL ); return ; } } SvxSimpleTable::KeyInput( rKEvt ); } void SvxRadioButtonListBox::HandleEntryChecked( SvLBoxEntry* _pEntry ) { Select( _pEntry, TRUE ); SvButtonState eState = GetCheckButtonState( _pEntry ); if ( SV_BUTTON_CHECKED == eState ) { // we have radio button behavior -> so uncheck the other entries SvLBoxEntry* pEntry = First(); while ( pEntry ) { if ( pEntry != _pEntry ) SetCheckButtonState( pEntry, SV_BUTTON_UNCHECKED ); pEntry = Next( pEntry ); } } else SetCheckButtonState( _pEntry, SV_BUTTON_CHECKED ); } const Point& SvxRadioButtonListBox::GetCurMousePoint() const { return m_aCurMousePoint; } } // end of namespace ::svx <commit_msg>INTEGRATION: CWS changefileheader (1.4.368); FILE MERGED 2008/03/31 14:20:01 rt 1.4.368.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: radiobtnbox.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" /* #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif */ // include --------------------------------------------------------------- #include "radiobtnbox.hxx" #include <svx/dialmgr.hxx> namespace svx { // class SvxRadioButtonListBox ---------------------------------------------------- SvxRadioButtonListBox::SvxRadioButtonListBox( Window* _pParent, const ResId& _rId ) : SvxSimpleTable( _pParent, _rId ) { EnableCheckButton( new SvLBoxButtonData( this, true ) ); } SvxRadioButtonListBox::~SvxRadioButtonListBox() { } void SvxRadioButtonListBox::SetTabs() { SvxSimpleTable::SetTabs(); /* USHORT nAdjust = SV_LBOXTAB_ADJUST_RIGHT | SV_LBOXTAB_ADJUST_LEFT | SV_LBOXTAB_ADJUST_CENTER | SV_LBOXTAB_ADJUST_NUMERIC | SV_LBOXTAB_FORCE; if ( aTabs.Count() > 0 ) { SvLBoxTab* pTab = (SvLBoxTab*)aTabs.GetObject(0); pTab->nFlags &= ~nAdjust; pTab->nFlags |= SV_LBOXTAB_PUSHABLE | SV_LBOXTAB_ADJUST_CENTER | SV_LBOXTAB_FORCE; } */ } void SvxRadioButtonListBox::MouseButtonUp( const MouseEvent& _rMEvt ) { m_aCurMousePoint = _rMEvt.GetPosPixel(); SvxSimpleTable::MouseButtonUp( _rMEvt ); } void SvxRadioButtonListBox::KeyInput( const KeyEvent& rKEvt ) { if ( !rKEvt.GetKeyCode().GetModifier() && KEY_SPACE == rKEvt.GetKeyCode().GetCode() ) { SvLBoxEntry* pEntry = FirstSelected(); if ( GetCheckButtonState( pEntry ) == SV_BUTTON_UNCHECKED ) { SetCheckButtonState( pEntry, SV_BUTTON_CHECKED ); GetCheckButtonHdl().Call( NULL ); return ; } } SvxSimpleTable::KeyInput( rKEvt ); } void SvxRadioButtonListBox::HandleEntryChecked( SvLBoxEntry* _pEntry ) { Select( _pEntry, TRUE ); SvButtonState eState = GetCheckButtonState( _pEntry ); if ( SV_BUTTON_CHECKED == eState ) { // we have radio button behavior -> so uncheck the other entries SvLBoxEntry* pEntry = First(); while ( pEntry ) { if ( pEntry != _pEntry ) SetCheckButtonState( pEntry, SV_BUTTON_UNCHECKED ); pEntry = Next( pEntry ); } } else SetCheckButtonState( _pEntry, SV_BUTTON_CHECKED ); } const Point& SvxRadioButtonListBox::GetCurMousePoint() const { return m_aCurMousePoint; } } // end of namespace ::svx <|endoftext|>
<commit_before><commit_msg>error C2782: template parameter '_Ty' is ambiguous<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: atrfld.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2004-02-26 15:34:07 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "doc.hxx" // Update fuer UserFields #include "fldbas.hxx" // fuer FieldType #ifndef _FMTFLD_HXX //autogen #include <fmtfld.hxx> #endif #ifndef _TXTFLD_HXX //autogen #include <txtfld.hxx> #endif #include "reffld.hxx" #include "ddefld.hxx" #include "usrfld.hxx" #include "expfld.hxx" #include "swfont.hxx" // fuer GetFldsColor #include "ndtxt.hxx" // SwTxtNode #include "calc.hxx" // Update fuer UserFields #include "hints.hxx" TYPEINIT2( SwFmtFld, SfxPoolItem, SwClient ) /**************************************************************************** * * class SwFmtFld * ****************************************************************************/ // Konstruktor fuers Default vom Attribut-Pool SwFmtFld::SwFmtFld() : SfxPoolItem( RES_TXTATR_FIELD ), SwClient( 0 ), pField( 0 ), pTxtAttr( 0 ) { } SwFmtFld::SwFmtFld( const SwField &rFld ) : SfxPoolItem( RES_TXTATR_FIELD ), SwClient( rFld.GetTyp() ), pTxtAttr( 0 ) { pField = rFld.Copy(); } SwFmtFld::SwFmtFld( const SwFmtFld& rAttr ) : SfxPoolItem( RES_TXTATR_FIELD ), SwClient( rAttr.GetFld()->GetTyp() ), pTxtAttr( 0 ) { pField = rAttr.GetFld()->Copy(); } SwFmtFld::~SwFmtFld() { SwFieldType* pType = pField ? pField->GetTyp() : 0; if (pType && pType->Which() == RES_DBFLD) pType = 0; // DB-Feldtypen zerstoeren sich selbst delete pField; // bei einige FeldTypen muessen wir den FeldTypen noch loeschen if( pType && pType->IsLastDepend() ) { BOOL bDel = FALSE; switch( pType->Which() ) { case RES_USERFLD: bDel = ((SwUserFieldType*)pType)->IsDeleted(); break; case RES_SETEXPFLD: bDel = ((SwSetExpFieldType*)pType)->IsDeleted(); break; case RES_DDEFLD: bDel = ((SwDDEFieldType*)pType)->IsDeleted(); break; } if( bDel ) { // vorm loeschen erstmal austragen pType->Remove( this ); delete pType; } } } int SwFmtFld::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return pField->GetTyp() == ((SwFmtFld&)rAttr).GetFld()->GetTyp() && pField->GetFormat() == ((SwFmtFld&)rAttr).GetFld()->GetFormat(); } SfxPoolItem* SwFmtFld::Clone( SfxItemPool* ) const { return new SwFmtFld( *this ); } void SwFmtFld::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew ) { if( !pTxtAttr ) return; SwTxtNode* pTxtNd = (SwTxtNode*)&pTxtAttr->GetTxtNode(); ASSERT( pTxtNd, "wo ist denn mein Node?" ); if( pNew ) { switch( pNew->Which() ) { case RES_TXTATR_FLDCHG: // "Farbe hat sich geaendert !" // this, this fuer "nur Painten" pTxtNd->Modify( this, this ); return; case RES_REFMARKFLD_UPDATE: // GetReferenz-Felder aktualisieren if( RES_GETREFFLD == GetFld()->GetTyp()->Which() ) ((SwGetRefField*)GetFld())->UpdateField(); break; case RES_DOCPOS_UPDATE: // Je nach DocPos aktualisieren (SwTxtFrm::Modify()) pTxtNd->Modify( pNew, this ); return; case RES_ATTRSET_CHG: case RES_FMT_CHG: pTxtNd->Modify( pOld, pNew ); return; } } switch (GetFld()->GetTyp()->Which()) { case RES_HIDDENPARAFLD: if( !pOld || RES_HIDDENPARA_PRINT != pOld->Which() ) break; case RES_DBSETNUMBERFLD: case RES_DBNUMSETFLD: case RES_DBNEXTSETFLD: case RES_DBNAMEFLD: pTxtNd->Modify( 0, pNew); return; } if( RES_USERFLD == GetFld()->GetTyp()->Which() ) { SwUserFieldType* pType = (SwUserFieldType*)GetFld()->GetTyp(); if(!pType->IsValid()) { SwCalc aCalc( *pTxtNd->GetDoc() ); pType->GetValue( aCalc ); } } pTxtAttr->Expand(); } BOOL SwFmtFld::GetInfo( SfxPoolItem& rInfo ) const { const SwTxtNode* pTxtNd; if( RES_AUTOFMT_DOCNODE != rInfo.Which() || !pTxtAttr || 0 == ( pTxtNd = pTxtAttr->GetpTxtNode() ) || &pTxtNd->GetNodes() != ((SwAutoFmtGetDocNode&)rInfo).pNodes ) return TRUE; ((SwAutoFmtGetDocNode&)rInfo).pCntntNode = pTxtNd; return FALSE; } BOOL SwFmtFld::IsFldInDoc() const { const SwTxtNode* pTxtNd; return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) && pTxtNd->GetNodes().IsDocNodes(); } BOOL SwFmtFld::IsProtect() const { const SwTxtNode* pTxtNd; return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) && pTxtNd->IsProtect(); } /************************************************************************* |* |* SwTxtFld::SwTxtFld() |* |* Beschreibung Attribut fuer automatischen Text, Ctor |* Ersterstellung BP 30.04.92 |* Letzte Aenderung JP 15.08.94 |* *************************************************************************/ SwTxtFld::SwTxtFld( const SwFmtFld& rAttr, xub_StrLen nStart ) : SwTxtAttr( rAttr, nStart ), aExpand( rAttr.GetFld()->Expand() ), pMyTxtNd( 0 ) { ((SwFmtFld&)rAttr).pTxtAttr = this; } SwTxtFld::~SwTxtFld( ) { } /************************************************************************* |* |* SwTxtFld::Expand() |* |* Beschreibung exandiert das Feld und tauscht den Text im Node |* Ersterstellung BP 30.04.92 |* Letzte Aenderung JP 15.08.94 |* *************************************************************************/ void SwTxtFld::Expand() { // Wenn das expandierte Feld sich nicht veraendert hat, wird returnt ASSERT( pMyTxtNd, "wo ist denn mein Node?" ); const SwField* pFld = GetFld().GetFld(); XubString aNewExpand( pFld->Expand() ); if( aNewExpand == aExpand ) { // Bei Seitennummernfeldern const USHORT nWhich = pFld->GetTyp()->Which(); if( RES_CHAPTERFLD != nWhich && RES_PAGENUMBERFLD != nWhich && RES_REFPAGEGETFLD != nWhich && ( RES_GETEXPFLD != nWhich || ((SwGetExpField*)pFld)->IsInBodyTxt() ) ) { // BP: das muesste man noch optimieren! //JP 12.06.97: stimmt, man sollte auf jedenfall eine Status- // aenderung an die Frames posten if( pMyTxtNd->CalcHiddenParaField() ) pMyTxtNd->Modify( 0, 0 ); return; } } aExpand = aNewExpand; // 0, this fuer Formatieren pMyTxtNd->Modify( 0, (SfxPoolItem*)&GetFld() ); } /************************************************************************* * SwTxtFld::CopyFld() *************************************************************************/ void SwTxtFld::CopyFld( SwTxtFld *pDest ) const { ASSERT( pMyTxtNd, "wo ist denn mein Node?" ); ASSERT( pDest->pMyTxtNd, "wo ist denn mein Node?" ); SwDoc *pDoc = pMyTxtNd->GetDoc(); SwDoc *pDestDoc = pDest->pMyTxtNd->GetDoc(); SwFmtFld& rFmtFld = (SwFmtFld&)pDest->GetFld(); const USHORT nFldWhich = rFmtFld.GetFld()->GetTyp()->Which(); if( pDoc != pDestDoc ) { // Die Hints stehen in unterschiedlichen Dokumenten, // der Feldtyp muss im neuen Dokument angemeldet werden. // Z.B: Kopieren ins ClipBoard. SwFieldType* pFldType; if( nFldWhich != RES_DBFLD && nFldWhich != RES_USERFLD && nFldWhich != RES_SETEXPFLD && nFldWhich != RES_DDEFLD && RES_AUTHORITY != nFldWhich ) pFldType = pDestDoc->GetSysFldType( (const RES_FIELDS)nFldWhich ); else pFldType = pDestDoc->InsertFldType( *rFmtFld.GetFld()->GetTyp() ); // Sonderbehandlung fuer DDE-Felder if( RES_DDEFLD == nFldWhich ) { if( rFmtFld.GetTxtFld() ) ((SwDDEFieldType*)rFmtFld.GetFld()->GetTyp())->DecRefCnt(); ((SwDDEFieldType*)pFldType)->IncRefCnt(); } ASSERT( pFldType, "unbekannter FieldType" ); pFldType->Add( &rFmtFld ); // ummelden rFmtFld.GetFld()->ChgTyp( pFldType ); } // Expressionfelder Updaten if( nFldWhich == RES_SETEXPFLD || nFldWhich == RES_GETEXPFLD || nFldWhich == RES_HIDDENTXTFLD ) { SwTxtFld* pFld = (SwTxtFld*)this; pDestDoc->UpdateExpFlds( pFld ); } // Tabellenfelder auf externe Darstellung else if( RES_TABLEFLD == nFldWhich && ((SwTblField*)rFmtFld.GetFld())->IsIntrnlName() ) { // erzeuge aus der internen (fuer CORE) die externe (fuer UI) Formel const SwTableNode* pTblNd = pMyTxtNd->FindTableNode(); if( pTblNd ) // steht in einer Tabelle ((SwTblField*)rFmtFld.GetFld())->PtrToBoxNm( &pTblNd->GetTable() ); } } <commit_msg>INTEGRATION: CWS aw008 (1.2.392); FILE MERGED 2004/02/26 10:33:21 aw 1.2.392.2: #i24434# One more change was necessary from the OS code 2004/02/06 14:10:55 aw 1.2.392.1: #i24434#<commit_after>/************************************************************************* * * $RCSfile: atrfld.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-02-26 17:39:16 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "doc.hxx" // Update fuer UserFields #include "fldbas.hxx" // fuer FieldType #ifndef _FMTFLD_HXX //autogen #include <fmtfld.hxx> #endif #ifndef _TXTFLD_HXX //autogen #include <txtfld.hxx> #endif #include "reffld.hxx" #include "ddefld.hxx" #include "usrfld.hxx" #include "expfld.hxx" #include "swfont.hxx" // fuer GetFldsColor #include "ndtxt.hxx" // SwTxtNode #include "calc.hxx" // Update fuer UserFields #include "hints.hxx" TYPEINIT2( SwFmtFld, SfxPoolItem, SwClient ) /**************************************************************************** * * class SwFmtFld * ****************************************************************************/ // Konstruktor fuers Default vom Attribut-Pool SwFmtFld::SwFmtFld() : SfxPoolItem( RES_TXTATR_FIELD ), SwClient( 0 ), pField( 0 ), pTxtAttr( 0 ) { } SwFmtFld::SwFmtFld( const SwField &rFld ) : SfxPoolItem( RES_TXTATR_FIELD ), SwClient( rFld.GetTyp() ), pTxtAttr( 0 ) { pField = rFld.Copy(); } // #i24434# // Since Items are used in ItemPool and in default constructed ItemSets with // full pool range, all items need to be clonable. Thus, this one needed to be // corrected SwFmtFld::SwFmtFld( const SwFmtFld& rAttr ) : SfxPoolItem( RES_TXTATR_FIELD ), pTxtAttr( 0 ), pField( 0 ) { if(rAttr.GetFld()) { rAttr.GetFld()->GetTyp()->Add(this); pField = rAttr.GetFld()->Copy(); } } SwFmtFld::~SwFmtFld() { SwFieldType* pType = pField ? pField->GetTyp() : 0; if (pType && pType->Which() == RES_DBFLD) pType = 0; // DB-Feldtypen zerstoeren sich selbst delete pField; // bei einige FeldTypen muessen wir den FeldTypen noch loeschen if( pType && pType->IsLastDepend() ) { BOOL bDel = FALSE; switch( pType->Which() ) { case RES_USERFLD: bDel = ((SwUserFieldType*)pType)->IsDeleted(); break; case RES_SETEXPFLD: bDel = ((SwSetExpFieldType*)pType)->IsDeleted(); break; case RES_DDEFLD: bDel = ((SwDDEFieldType*)pType)->IsDeleted(); break; } if( bDel ) { // vorm loeschen erstmal austragen pType->Remove( this ); delete pType; } } } int SwFmtFld::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return pField->GetTyp() == ((SwFmtFld&)rAttr).GetFld()->GetTyp() && pField->GetFormat() == ((SwFmtFld&)rAttr).GetFld()->GetFormat(); } SfxPoolItem* SwFmtFld::Clone( SfxItemPool* ) const { return new SwFmtFld( *this ); } void SwFmtFld::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew ) { if( !pTxtAttr ) return; SwTxtNode* pTxtNd = (SwTxtNode*)&pTxtAttr->GetTxtNode(); ASSERT( pTxtNd, "wo ist denn mein Node?" ); if( pNew ) { switch( pNew->Which() ) { case RES_TXTATR_FLDCHG: // "Farbe hat sich geaendert !" // this, this fuer "nur Painten" pTxtNd->Modify( this, this ); return; case RES_REFMARKFLD_UPDATE: // GetReferenz-Felder aktualisieren if( RES_GETREFFLD == GetFld()->GetTyp()->Which() ) ((SwGetRefField*)GetFld())->UpdateField(); break; case RES_DOCPOS_UPDATE: // Je nach DocPos aktualisieren (SwTxtFrm::Modify()) pTxtNd->Modify( pNew, this ); return; case RES_ATTRSET_CHG: case RES_FMT_CHG: pTxtNd->Modify( pOld, pNew ); return; } } switch (GetFld()->GetTyp()->Which()) { case RES_HIDDENPARAFLD: if( !pOld || RES_HIDDENPARA_PRINT != pOld->Which() ) break; case RES_DBSETNUMBERFLD: case RES_DBNUMSETFLD: case RES_DBNEXTSETFLD: case RES_DBNAMEFLD: pTxtNd->Modify( 0, pNew); return; } if( RES_USERFLD == GetFld()->GetTyp()->Which() ) { SwUserFieldType* pType = (SwUserFieldType*)GetFld()->GetTyp(); if(!pType->IsValid()) { SwCalc aCalc( *pTxtNd->GetDoc() ); pType->GetValue( aCalc ); } } pTxtAttr->Expand(); } BOOL SwFmtFld::GetInfo( SfxPoolItem& rInfo ) const { const SwTxtNode* pTxtNd; if( RES_AUTOFMT_DOCNODE != rInfo.Which() || !pTxtAttr || 0 == ( pTxtNd = pTxtAttr->GetpTxtNode() ) || &pTxtNd->GetNodes() != ((SwAutoFmtGetDocNode&)rInfo).pNodes ) return TRUE; ((SwAutoFmtGetDocNode&)rInfo).pCntntNode = pTxtNd; return FALSE; } BOOL SwFmtFld::IsFldInDoc() const { const SwTxtNode* pTxtNd; return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) && pTxtNd->GetNodes().IsDocNodes(); } BOOL SwFmtFld::IsProtect() const { const SwTxtNode* pTxtNd; return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) && pTxtNd->IsProtect(); } /************************************************************************* |* |* SwTxtFld::SwTxtFld() |* |* Beschreibung Attribut fuer automatischen Text, Ctor |* Ersterstellung BP 30.04.92 |* Letzte Aenderung JP 15.08.94 |* *************************************************************************/ SwTxtFld::SwTxtFld( const SwFmtFld& rAttr, xub_StrLen nStart ) : SwTxtAttr( rAttr, nStart ), aExpand( rAttr.GetFld()->Expand() ), pMyTxtNd( 0 ) { ((SwFmtFld&)rAttr).pTxtAttr = this; } SwTxtFld::~SwTxtFld( ) { } /************************************************************************* |* |* SwTxtFld::Expand() |* |* Beschreibung exandiert das Feld und tauscht den Text im Node |* Ersterstellung BP 30.04.92 |* Letzte Aenderung JP 15.08.94 |* *************************************************************************/ void SwTxtFld::Expand() { // Wenn das expandierte Feld sich nicht veraendert hat, wird returnt ASSERT( pMyTxtNd, "wo ist denn mein Node?" ); const SwField* pFld = GetFld().GetFld(); XubString aNewExpand( pFld->Expand() ); if( aNewExpand == aExpand ) { // Bei Seitennummernfeldern const USHORT nWhich = pFld->GetTyp()->Which(); if( RES_CHAPTERFLD != nWhich && RES_PAGENUMBERFLD != nWhich && RES_REFPAGEGETFLD != nWhich && ( RES_GETEXPFLD != nWhich || ((SwGetExpField*)pFld)->IsInBodyTxt() ) ) { // BP: das muesste man noch optimieren! //JP 12.06.97: stimmt, man sollte auf jedenfall eine Status- // aenderung an die Frames posten if( pMyTxtNd->CalcHiddenParaField() ) pMyTxtNd->Modify( 0, 0 ); return; } } aExpand = aNewExpand; // 0, this fuer Formatieren pMyTxtNd->Modify( 0, (SfxPoolItem*)&GetFld() ); } /************************************************************************* * SwTxtFld::CopyFld() *************************************************************************/ void SwTxtFld::CopyFld( SwTxtFld *pDest ) const { ASSERT( pMyTxtNd, "wo ist denn mein Node?" ); ASSERT( pDest->pMyTxtNd, "wo ist denn mein Node?" ); SwDoc *pDoc = pMyTxtNd->GetDoc(); SwDoc *pDestDoc = pDest->pMyTxtNd->GetDoc(); SwFmtFld& rFmtFld = (SwFmtFld&)pDest->GetFld(); const USHORT nFldWhich = rFmtFld.GetFld()->GetTyp()->Which(); if( pDoc != pDestDoc ) { // Die Hints stehen in unterschiedlichen Dokumenten, // der Feldtyp muss im neuen Dokument angemeldet werden. // Z.B: Kopieren ins ClipBoard. SwFieldType* pFldType; if( nFldWhich != RES_DBFLD && nFldWhich != RES_USERFLD && nFldWhich != RES_SETEXPFLD && nFldWhich != RES_DDEFLD && RES_AUTHORITY != nFldWhich ) pFldType = pDestDoc->GetSysFldType( (const RES_FIELDS)nFldWhich ); else pFldType = pDestDoc->InsertFldType( *rFmtFld.GetFld()->GetTyp() ); // Sonderbehandlung fuer DDE-Felder if( RES_DDEFLD == nFldWhich ) { if( rFmtFld.GetTxtFld() ) ((SwDDEFieldType*)rFmtFld.GetFld()->GetTyp())->DecRefCnt(); ((SwDDEFieldType*)pFldType)->IncRefCnt(); } ASSERT( pFldType, "unbekannter FieldType" ); pFldType->Add( &rFmtFld ); // ummelden rFmtFld.GetFld()->ChgTyp( pFldType ); } // Expressionfelder Updaten if( nFldWhich == RES_SETEXPFLD || nFldWhich == RES_GETEXPFLD || nFldWhich == RES_HIDDENTXTFLD ) { SwTxtFld* pFld = (SwTxtFld*)this; pDestDoc->UpdateExpFlds( pFld ); } // Tabellenfelder auf externe Darstellung else if( RES_TABLEFLD == nFldWhich && ((SwTblField*)rFmtFld.GetFld())->IsIntrnlName() ) { // erzeuge aus der internen (fuer CORE) die externe (fuer UI) Formel const SwTableNode* pTblNd = pMyTxtNd->FindTableNode(); if( pTblNd ) // steht in einer Tabelle ((SwTblField*)rFmtFld.GetFld())->PtrToBoxNm( &pTblNd->GetTable() ); } } <|endoftext|>
<commit_before><commit_msg>WaE: default constructor could not be generated<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#1309049 Unchecked return value<commit_after><|endoftext|>
<commit_before><commit_msg>simplify a bit<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: htmlnum.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 17:14:55 $ * * 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 _HTMLNUM_HXX #define _HTMLNUM_HXX #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #include <string.h> #define HTML_NUMBUL_MARGINLEFT (MM50*2 + MM50/2) #define HTML_NUMBUL_INDENT (-MM50) class SwTxtNode; class SwNumRule; class SwHTMLNumRuleInfo { sal_uInt16 aNumStarts[MAXLEVEL]; SwNumRule * pNumRule; // Aktuelle Numerierung sal_uInt16 nDeep; // aktuelle Num-Tiefe (1, 2, 3, ...) sal_Bool bRestart : 1; // Export: Numerierung neu starten sal_Bool bNumbered : 1; // Export: Absatz ist numeriert #ifndef NUM_RELSPACE sal_Bool bUpdateWholeNum : 1; // Import: Muss die NumRule // vollstaendig aktualisiert werden #endif public: inline void Set( const SwHTMLNumRuleInfo& rInf ); void Set( const SwTxtNode& rTxtNd ); SwHTMLNumRuleInfo() : pNumRule( 0 ), nDeep( 0 ), #ifndef NUM_RELSPACE bUpdateWholeNum( sal_False ), #endif bRestart( sal_False ), bNumbered( sal_False ) { memset( &aNumStarts, 0xff, sizeof( aNumStarts ) ); } SwHTMLNumRuleInfo( const SwHTMLNumRuleInfo& rInf ) : pNumRule( rInf.pNumRule ), nDeep( rInf.nDeep ), #ifndef NUM_RELSPACE bUpdateWholeNum( rInf.bUpdateWholeNum ), #endif bRestart( rInf.bRestart ), bNumbered( rInf.bNumbered ) { memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) ); } SwHTMLNumRuleInfo( const SwTxtNode& rTxtNd ) { Set( rTxtNd ); } inline SwHTMLNumRuleInfo& operator=( const SwHTMLNumRuleInfo& rInf ); inline void Clear(); void SetNumRule( const SwNumRule *pRule ) { pNumRule = (SwNumRule *)pRule; } SwNumRule *GetNumRule() { return pNumRule; } const SwNumRule *GetNumRule() const { return pNumRule; } void SetDepth( sal_uInt16 nDepth ) { nDeep = nDepth; } sal_uInt16 GetDepth() const { return nDeep; } sal_uInt16 IncDepth() { return ++nDeep; } sal_uInt16 DecDepth() { return nDeep==0 ? 0 : --nDeep; } inline sal_uInt8 GetLevel() const; #ifndef NUM_RELSPACE void SetUpdateWholeNum( sal_Bool bSet ) { bUpdateWholeNum = bSet; } sal_Bool IsUpdateWholeNum() const { return bUpdateWholeNum; } #endif void SetRestart( sal_Bool bSet ) { bRestart = bSet; } sal_Bool IsRestart() const { return bRestart; } void SetNumbered( sal_Bool bSet ) { bNumbered = bSet; } sal_Bool IsNumbered() const { return bNumbered; } inline void SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal=USHRT_MAX ); sal_uInt16 GetNodeStartValue( sal_uInt8 nLvl ) const { return aNumStarts[nLvl]; } }; inline SwHTMLNumRuleInfo& SwHTMLNumRuleInfo::operator=( const SwHTMLNumRuleInfo& rInf ) { Set( rInf ); return *this; } inline void SwHTMLNumRuleInfo::Set( const SwHTMLNumRuleInfo& rInf ) { pNumRule = rInf.pNumRule; nDeep = rInf.nDeep; #ifndef NUM_RELSPACE bUpdateWholeNum = rInf.bUpdateWholeNum; #endif bRestart = rInf.bRestart; bNumbered = rInf.bNumbered; memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) ); } inline void SwHTMLNumRuleInfo::Clear() { pNumRule = 0; nDeep = 0; #ifndef NUM_RELSPACE bUpdateWholeNum = sal_False; #endif bRestart = bNumbered = sal_False; memset( &aNumStarts, 0xff, sizeof( aNumStarts ) ); } inline sal_uInt8 SwHTMLNumRuleInfo::GetLevel() const { return (sal_uInt8)( pNumRule!=0 && nDeep != 0 ? ( nDeep<=MAXLEVEL ? nDeep-1 : MAXLEVEL - 1 ) : 0 ); } inline void SwHTMLNumRuleInfo::SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal ) { aNumStarts[nLvl] = nVal; } #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1462); FILE MERGED 2005/09/05 13:42:05 rt 1.1.1.1.1462.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: htmlnum.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:45:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _HTMLNUM_HXX #define _HTMLNUM_HXX #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #include <string.h> #define HTML_NUMBUL_MARGINLEFT (MM50*2 + MM50/2) #define HTML_NUMBUL_INDENT (-MM50) class SwTxtNode; class SwNumRule; class SwHTMLNumRuleInfo { sal_uInt16 aNumStarts[MAXLEVEL]; SwNumRule * pNumRule; // Aktuelle Numerierung sal_uInt16 nDeep; // aktuelle Num-Tiefe (1, 2, 3, ...) sal_Bool bRestart : 1; // Export: Numerierung neu starten sal_Bool bNumbered : 1; // Export: Absatz ist numeriert #ifndef NUM_RELSPACE sal_Bool bUpdateWholeNum : 1; // Import: Muss die NumRule // vollstaendig aktualisiert werden #endif public: inline void Set( const SwHTMLNumRuleInfo& rInf ); void Set( const SwTxtNode& rTxtNd ); SwHTMLNumRuleInfo() : pNumRule( 0 ), nDeep( 0 ), #ifndef NUM_RELSPACE bUpdateWholeNum( sal_False ), #endif bRestart( sal_False ), bNumbered( sal_False ) { memset( &aNumStarts, 0xff, sizeof( aNumStarts ) ); } SwHTMLNumRuleInfo( const SwHTMLNumRuleInfo& rInf ) : pNumRule( rInf.pNumRule ), nDeep( rInf.nDeep ), #ifndef NUM_RELSPACE bUpdateWholeNum( rInf.bUpdateWholeNum ), #endif bRestart( rInf.bRestart ), bNumbered( rInf.bNumbered ) { memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) ); } SwHTMLNumRuleInfo( const SwTxtNode& rTxtNd ) { Set( rTxtNd ); } inline SwHTMLNumRuleInfo& operator=( const SwHTMLNumRuleInfo& rInf ); inline void Clear(); void SetNumRule( const SwNumRule *pRule ) { pNumRule = (SwNumRule *)pRule; } SwNumRule *GetNumRule() { return pNumRule; } const SwNumRule *GetNumRule() const { return pNumRule; } void SetDepth( sal_uInt16 nDepth ) { nDeep = nDepth; } sal_uInt16 GetDepth() const { return nDeep; } sal_uInt16 IncDepth() { return ++nDeep; } sal_uInt16 DecDepth() { return nDeep==0 ? 0 : --nDeep; } inline sal_uInt8 GetLevel() const; #ifndef NUM_RELSPACE void SetUpdateWholeNum( sal_Bool bSet ) { bUpdateWholeNum = bSet; } sal_Bool IsUpdateWholeNum() const { return bUpdateWholeNum; } #endif void SetRestart( sal_Bool bSet ) { bRestart = bSet; } sal_Bool IsRestart() const { return bRestart; } void SetNumbered( sal_Bool bSet ) { bNumbered = bSet; } sal_Bool IsNumbered() const { return bNumbered; } inline void SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal=USHRT_MAX ); sal_uInt16 GetNodeStartValue( sal_uInt8 nLvl ) const { return aNumStarts[nLvl]; } }; inline SwHTMLNumRuleInfo& SwHTMLNumRuleInfo::operator=( const SwHTMLNumRuleInfo& rInf ) { Set( rInf ); return *this; } inline void SwHTMLNumRuleInfo::Set( const SwHTMLNumRuleInfo& rInf ) { pNumRule = rInf.pNumRule; nDeep = rInf.nDeep; #ifndef NUM_RELSPACE bUpdateWholeNum = rInf.bUpdateWholeNum; #endif bRestart = rInf.bRestart; bNumbered = rInf.bNumbered; memcpy( &aNumStarts, &rInf.aNumStarts, sizeof( aNumStarts ) ); } inline void SwHTMLNumRuleInfo::Clear() { pNumRule = 0; nDeep = 0; #ifndef NUM_RELSPACE bUpdateWholeNum = sal_False; #endif bRestart = bNumbered = sal_False; memset( &aNumStarts, 0xff, sizeof( aNumStarts ) ); } inline sal_uInt8 SwHTMLNumRuleInfo::GetLevel() const { return (sal_uInt8)( pNumRule!=0 && nDeep != 0 ? ( nDeep<=MAXLEVEL ? nDeep-1 : MAXLEVEL - 1 ) : 0 ); } inline void SwHTMLNumRuleInfo::SetNodeStartValue( sal_uInt8 nLvl, sal_uInt16 nVal ) { aNumStarts[nLvl] = nVal; } #endif <|endoftext|>
<commit_before><commit_msg>remove unconditionally dead code<commit_after><|endoftext|>
<commit_before>// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/kasko/reporter.h" #include <Windows.h> // NOLINT #include <Dbgeng.h> #include <Rpc.h> #include <string> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "gtest/gtest.h" #include "syzygy/common/rpc/helpers.h" #include "syzygy/kasko/kasko_rpc.h" #include "syzygy/kasko/testing/minidump_unittest_helpers.h" #include "syzygy/kasko/testing/test_server.h" #include "syzygy/kasko/testing/upload_observer.h" // The test server will respond to POSTs to /crash by writing all parameters to // a report directory. Each file in the directory has the name of a parameter // and the parameter value as its contents. // // This test instantiates a reporter process, points it at a test server, and // then monitors the server's "incoming" director for new files named // Reporter::kMinidumpUploadFilePart. namespace kasko { namespace { const char kCrashKey1Name[] = "foo"; const char kCrashKey1Value[] = "bar"; const char kCrashKey2Name[] = "hello"; const char kCrashKey2Value[] = "world"; // Invokes the diagnostic report RPC service at |endpoint|, requesting a dump of // the current process, and including |protobuf|. void DoInvokeService(const base::string16& endpoint, const std::string& protobuf) { common::rpc::ScopedRpcBinding rpc_binding; ASSERT_TRUE(rpc_binding.Open(L"ncalrpc", endpoint)); CrashKey crash_keys[] = { {reinterpret_cast<const signed char*>(kCrashKey1Name), reinterpret_cast<const signed char*>(kCrashKey1Value)}, {reinterpret_cast<const signed char*>(kCrashKey2Name), reinterpret_cast<const signed char*>(kCrashKey2Value)}}; common::rpc::RpcStatus status = common::rpc::InvokeRpc( KaskoClient_SendDiagnosticReport, rpc_binding.Get(), NULL, 0, protobuf.length(), reinterpret_cast<const signed char*>(protobuf.c_str()), arraysize(crash_keys), crash_keys); ASSERT_FALSE(status.exception_occurred); ASSERT_TRUE(status.succeeded()); } // Verifies that the uploaded minidump is plausibly a dump of this test process. void ValidateMinidump(IDebugClient4* debug_client, IDebugControl* debug_control, IDebugSymbols* debug_symbols) { ASSERT_HRESULT_SUCCEEDED( debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL)); } } // namespace class ReporterTest : public ::testing::Test { public: ReporterTest() {} virtual void SetUp() override { ASSERT_TRUE(server_.Start()); ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); } protected: uint16_t server_port() { return server_.port(); } // This directory is intentionally non-existant to verify that the reporter // creates the target directory as needed. base::FilePath data_directory() { return temp_directory_.path().Append(L"Crash Reports"); } // This directory is intentionally non-existant to verify that the reporter // creates the target directory as needed. base::FilePath permanent_failure_directory() { return temp_directory_.path().Append(L"Permanent Failure"); } base::FilePath upload_directory() { return server_.incoming_directory(); } private: testing::TestServer server_; base::ScopedTempDir temp_directory_; DISALLOW_COPY_AND_ASSIGN(ReporterTest); }; TEST_F(ReporterTest, BasicTest) { scoped_ptr<Reporter> instance(Reporter::Create( L"test_endpoint", L"http://127.0.0.1:" + base::UintToString16(server_port()) + L"/crash", data_directory(), permanent_failure_directory(), base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1))); ASSERT_TRUE(instance); testing::UploadObserver upload_observer(upload_directory(), permanent_failure_directory()); ASSERT_NO_FATAL_FAILURE(DoInvokeService(L"test_endpoint", "protobuf")); base::FilePath minidump_path; std::map<std::string, std::string> crash_keys; bool upload_success = false; upload_observer.WaitForUpload(&minidump_path, &crash_keys, &upload_success); ASSERT_TRUE(upload_success); EXPECT_HRESULT_SUCCEEDED( testing::VisitMinidump(minidump_path, base::Bind(&ValidateMinidump))); Reporter::Shutdown(instance.Pass()); } TEST_F(ReporterTest, SendReportForProcessTest) { scoped_ptr<Reporter> instance(Reporter::Create( L"test_endpoint", L"http://127.0.0.1:" + base::UintToString16(server_port()) + L"/crash", data_directory(), permanent_failure_directory(), base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1))); ASSERT_TRUE(instance); testing::UploadObserver upload_observer(upload_directory(), permanent_failure_directory()); std::map<base::string16, base::string16> crash_keys_in; crash_keys_in[base::UTF8ToUTF16(kCrashKey1Name)] = base::UTF8ToUTF16(kCrashKey1Value); crash_keys_in[base::UTF8ToUTF16(kCrashKey2Name)] = base::UTF8ToUTF16(kCrashKey2Value); instance->SendReportForProcess(base::GetCurrentProcessHandle(), crash_keys_in); base::FilePath minidump_path; std::map<std::string, std::string> crash_keys; bool upload_success = false; upload_observer.WaitForUpload(&minidump_path, &crash_keys, &upload_success); ASSERT_TRUE(upload_success); EXPECT_HRESULT_SUCCEEDED( testing::VisitMinidump(minidump_path, base::Bind(&ValidateMinidump))); Reporter::Shutdown(instance.Pass()); } TEST_F(ReporterTest, PermanentFailureTest) { scoped_ptr<Reporter> instance(Reporter::Create( L"test_endpoint", L"http://127.0.0.1:" + base::UintToString16(server_port()) + L"/crash_failure", data_directory(), permanent_failure_directory(), base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1))); ASSERT_TRUE(instance); testing::UploadObserver upload_observer(upload_directory(), permanent_failure_directory()); ASSERT_NO_FATAL_FAILURE(DoInvokeService(L"test_endpoint", "protobuf")); base::FilePath minidump_path; std::map<std::string, std::string> crash_keys; bool upload_success = false; upload_observer.WaitForUpload(&minidump_path, &crash_keys, &upload_success); ASSERT_FALSE(upload_success); EXPECT_HRESULT_SUCCEEDED( testing::VisitMinidump(minidump_path, base::Bind(&ValidateMinidump))); Reporter::Shutdown(instance.Pass()); } } // namespace kasko <commit_msg>Disable these still-flaky tests.<commit_after>// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/kasko/reporter.h" #include <Windows.h> // NOLINT #include <Dbgeng.h> #include <Rpc.h> #include <string> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "gtest/gtest.h" #include "syzygy/common/rpc/helpers.h" #include "syzygy/kasko/kasko_rpc.h" #include "syzygy/kasko/testing/minidump_unittest_helpers.h" #include "syzygy/kasko/testing/test_server.h" #include "syzygy/kasko/testing/upload_observer.h" // The test server will respond to POSTs to /crash by writing all parameters to // a report directory. Each file in the directory has the name of a parameter // and the parameter value as its contents. // // This test instantiates a reporter process, points it at a test server, and // then monitors the server's "incoming" director for new files named // Reporter::kMinidumpUploadFilePart. // // These tests are flaky on the bots. They appear to occasionally hang. // Presumably there is some kind of race condition. // TODO(erikwright): Debug these on the bots, add additional tracing, or do // whatever's necessary to diagnose and deflake these tests. namespace kasko { namespace { const char kCrashKey1Name[] = "foo"; const char kCrashKey1Value[] = "bar"; const char kCrashKey2Name[] = "hello"; const char kCrashKey2Value[] = "world"; // Invokes the diagnostic report RPC service at |endpoint|, requesting a dump of // the current process, and including |protobuf|. void DoInvokeService(const base::string16& endpoint, const std::string& protobuf) { common::rpc::ScopedRpcBinding rpc_binding; ASSERT_TRUE(rpc_binding.Open(L"ncalrpc", endpoint)); CrashKey crash_keys[] = { {reinterpret_cast<const signed char*>(kCrashKey1Name), reinterpret_cast<const signed char*>(kCrashKey1Value)}, {reinterpret_cast<const signed char*>(kCrashKey2Name), reinterpret_cast<const signed char*>(kCrashKey2Value)}}; common::rpc::RpcStatus status = common::rpc::InvokeRpc( KaskoClient_SendDiagnosticReport, rpc_binding.Get(), NULL, 0, protobuf.length(), reinterpret_cast<const signed char*>(protobuf.c_str()), arraysize(crash_keys), crash_keys); ASSERT_FALSE(status.exception_occurred); ASSERT_TRUE(status.succeeded()); } // Verifies that the uploaded minidump is plausibly a dump of this test process. void ValidateMinidump(IDebugClient4* debug_client, IDebugControl* debug_control, IDebugSymbols* debug_symbols) { ASSERT_HRESULT_SUCCEEDED( debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL)); } } // namespace class ReporterTest : public ::testing::Test { public: ReporterTest() {} virtual void SetUp() override { ASSERT_TRUE(server_.Start()); ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); } protected: uint16_t server_port() { return server_.port(); } // This directory is intentionally non-existant to verify that the reporter // creates the target directory as needed. base::FilePath data_directory() { return temp_directory_.path().Append(L"Crash Reports"); } // This directory is intentionally non-existant to verify that the reporter // creates the target directory as needed. base::FilePath permanent_failure_directory() { return temp_directory_.path().Append(L"Permanent Failure"); } base::FilePath upload_directory() { return server_.incoming_directory(); } private: testing::TestServer server_; base::ScopedTempDir temp_directory_; DISALLOW_COPY_AND_ASSIGN(ReporterTest); }; TEST_F(ReporterTest, DISABLED_BasicTest) { scoped_ptr<Reporter> instance(Reporter::Create( L"test_endpoint", L"http://127.0.0.1:" + base::UintToString16(server_port()) + L"/crash", data_directory(), permanent_failure_directory(), base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1))); ASSERT_TRUE(instance); testing::UploadObserver upload_observer(upload_directory(), permanent_failure_directory()); ASSERT_NO_FATAL_FAILURE(DoInvokeService(L"test_endpoint", "protobuf")); base::FilePath minidump_path; std::map<std::string, std::string> crash_keys; bool upload_success = false; upload_observer.WaitForUpload(&minidump_path, &crash_keys, &upload_success); ASSERT_TRUE(upload_success); EXPECT_HRESULT_SUCCEEDED( testing::VisitMinidump(minidump_path, base::Bind(&ValidateMinidump))); Reporter::Shutdown(instance.Pass()); } TEST_F(ReporterTest, DISABLED_SendReportForProcessTest) { scoped_ptr<Reporter> instance(Reporter::Create( L"test_endpoint", L"http://127.0.0.1:" + base::UintToString16(server_port()) + L"/crash", data_directory(), permanent_failure_directory(), base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1))); ASSERT_TRUE(instance); testing::UploadObserver upload_observer(upload_directory(), permanent_failure_directory()); std::map<base::string16, base::string16> crash_keys_in; crash_keys_in[base::UTF8ToUTF16(kCrashKey1Name)] = base::UTF8ToUTF16(kCrashKey1Value); crash_keys_in[base::UTF8ToUTF16(kCrashKey2Name)] = base::UTF8ToUTF16(kCrashKey2Value); instance->SendReportForProcess(base::GetCurrentProcessHandle(), crash_keys_in); base::FilePath minidump_path; std::map<std::string, std::string> crash_keys; bool upload_success = false; upload_observer.WaitForUpload(&minidump_path, &crash_keys, &upload_success); ASSERT_TRUE(upload_success); EXPECT_HRESULT_SUCCEEDED( testing::VisitMinidump(minidump_path, base::Bind(&ValidateMinidump))); Reporter::Shutdown(instance.Pass()); } TEST_F(ReporterTest, DISABLED_PermanentFailureTest) { scoped_ptr<Reporter> instance(Reporter::Create( L"test_endpoint", L"http://127.0.0.1:" + base::UintToString16(server_port()) + L"/crash_failure", data_directory(), permanent_failure_directory(), base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1))); ASSERT_TRUE(instance); testing::UploadObserver upload_observer(upload_directory(), permanent_failure_directory()); ASSERT_NO_FATAL_FAILURE(DoInvokeService(L"test_endpoint", "protobuf")); base::FilePath minidump_path; std::map<std::string, std::string> crash_keys; bool upload_success = false; upload_observer.WaitForUpload(&minidump_path, &crash_keys, &upload_success); ASSERT_FALSE(upload_success); EXPECT_HRESULT_SUCCEEDED( testing::VisitMinidump(minidump_path, base::Bind(&ValidateMinidump))); Reporter::Shutdown(instance.Pass()); } } // namespace kasko <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2016 Inviwo 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "volumecombiner.h" #include <modules/opengl/volume/volumegl.h> #include <modules/opengl/texture/textureunit.h> #include <inviwo/core/util/shuntingyard.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/volume/volumeutils.h> namespace inviwo { const ProcessorInfo VolumeCombiner::processorInfo_{ "org.inviwo.VolumeCombiner", // Class identifier "Volume Combiner", // Display name "Volume Operation", // Category CodeState::Experimental, // Code state Tags::GL, // Tags }; const ProcessorInfo VolumeCombiner::getProcessorInfo() const { return processorInfo_; } VolumeCombiner::VolumeCombiner() : Processor() , inport_("inport") , outport_("outport") , description_("description", "Volumes") , eqn_("eqn", "Equation", "v1") , scales_("scales", "Scale factors") , addScale_("addScale", "Add Scale Factor") , removeScale_("removeScale", "Remove Scale Factor") , useWorldSpace_("useWorldSpaceCoordinateSystem", "World Space", false) , borderValue_("borderValue", "Border value", vec4(0.f), vec4(0.f), vec4(1.f), vec4(0.1f)) , fragment_{std::make_shared<StringShaderResource>("volumecombiner.frag", "")} , shader_({{ShaderType::Vertex, utilgl::findShaderResource("volume_gpu.vert")}, {ShaderType::Geometry, utilgl::findShaderResource("volume_gpu.geom")}, {ShaderType::Fragment, fragment_}}, Shader::Build::No) , fbo_() { description_.setSemantics(PropertySemantics::Multiline); description_.setReadOnly(true); description_.setCurrentStateAsDefault(); addPort(inport_); addPort(outport_); addProperty(description_); addProperty(eqn_); addProperty(addScale_); addProperty(removeScale_); addProperty(scales_); addProperty(useWorldSpace_); useWorldSpace_.addProperty(borderValue_); addScale_.onChange([&]() { size_t i = scales_.size(); auto p = util::make_unique<FloatProperty>("scale" + toString(i), "s" + toString(i + 1), 1.0f, -2.f, 2.f, 0.01f); p->setSerializationMode(PropertySerializationMode::All); scales_.addProperty(p.release()); }); removeScale_.onChange([&]() { if (scales_.size() > 0) { dirty_ = true; delete scales_.removeProperty(scales_.getProperties().back()); } }); eqn_.onChange([&]() { dirty_ = true; }); inport_.onConnect([&]() { dirty_ = true; updateProperties(); }); inport_.onDisconnect([&]() { dirty_ = true; updateProperties(); }); useWorldSpace_.onChange([this]() { dirty_ = true; }); } bool VolumeCombiner::isReady() const { return Processor::isReady() && (valid_ || dirty_); } #include <warn/push> #include <warn/ignore/unused-variable> std::string VolumeCombiner::buildEquation() const { std::map<std::string, double> vars = {}; std::map<std::string, std::string> symbols; size_t i = 0; for (const auto& dummy : inport_) { symbols["s" + toString(i + 1)] = "scale" + toString(i); symbols["v" + toString(i + 1)] = "vol" + toString(i); ++i; } return shuntingyard::Calculator::shaderCode(eqn_.get(), vars, symbols); } void VolumeCombiner::buildShader(const std::string& eqn) { std::stringstream ss; ss << "#include \"utils/structs.glsl\"\n"; ss << "#include \"utils/sampler3d.glsl\"\n\n"; ss << "in vec4 texCoord_;\n"; ss << "uniform vec4 " << borderValue_.getIdentifier() << ";\n"; size_t id = 0; for (const auto& dummy : inport_) { ss << "uniform sampler3D volume" << id << ";\n"; ss << "uniform VolumeParameters volume" << id << "Parameters;\n"; ++id; } for (auto prop : scales_.getProperties()) { ss << "uniform float " << prop->getIdentifier() << ";\n"; } ss << "\nvoid main() {\n"; id = 0; for (const auto& dummy : inport_) { const std::string vol = "vol" + toString(id); const std::string v = "volume" + toString(id); const std::string vp = "volume" + toString(id) + "Parameters"; if (useWorldSpace_) { const std::string coord = "coord" + toString(id); // Retrieve data from world space and use border value if outside of volume ss << " vec3 " << coord << " = (" << vp << ".worldToTexture * " << "volume0Parameters.textureToWorld * texCoord_).xyz;\n"; ss << " vec4 " << vol << ";\n"; ss << " if (all(greaterThanEqual(" << coord << ", vec3(0))) &&" << " all(lessThanEqual(" << coord << ", vec3(1)))) {\n"; ss << " " << vol << " = getNormalizedVoxel(" << v << ", " << vp << ", " << coord << ");\n"; ss << " } else {\n"; ss << " " << vol << " = borderValue;\n"; ss << " }\n\n"; } else { ss << " vec4 " << vol << " = getNormalizedVoxel(" << v << ", " << vp << ", texCoord_.xyz);\n"; } ++id; } ss << " FragData0 = " << eqn << ";\n"; ss << " gl_FragDepth = 1.0;\n"; ss << "}\n"; fragment_->setSource(ss.str()); shader_.build(); } void VolumeCombiner::updateProperties() { size_t i = 0; std::stringstream desc; for (const auto& port : inport_.getConnectedOutports()) { desc << "v" + toString(i + 1) + ": " + port->getProcessor()->getIdentifier() << "\n"; i++; } description_.set(desc.str()); } #include <warn/pop> void VolumeCombiner::process() { if (inport_.isChanged()) { const DataFormatBase* format = inport_.getData()->getDataFormat(); volume_ = std::make_shared<Volume>(inport_.getData()->getDimensions(), format); volume_->setModelMatrix(inport_.getData()->getModelMatrix()); volume_->setWorldMatrix(inport_.getData()->getWorldMatrix()); // pass on metadata volume_->copyMetaDataFrom(*inport_.getData()); volume_->dataMap_ = inport_.getData()->dataMap_; outport_.setData(volume_); } if (dirty_) { dirty_ = false; try { buildShader(buildEquation()); valid_ = true; } catch (Exception& e) { valid_ = false; throw Exception(e.getMessage() + ": " + eqn_.get(), IvwContext); } } shader_.activate(); TextureUnitContainer cont; int i = 0; for (const auto& vol : inport_) { utilgl::bindAndSetUniforms(shader_, cont, *vol, "volume" + toString(i)); ++i; } utilgl::setUniforms(shader_, borderValue_); for (auto prop : scales_.getProperties()) { utilgl::setUniforms(shader_, *static_cast<FloatProperty*>(prop)); } const size3_t dim{inport_.getData()->getDimensions()}; fbo_.activate(); glViewport(0, 0, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y)); // We always need to ask for a editable representation // this will invalidate any other representations VolumeGL* outVolumeGL = volume_->getEditableRepresentation<VolumeGL>(); if (inport_.isChanged()) { fbo_.attachColorTexture(outVolumeGL->getTexture().get(), 0); } utilgl::multiDrawImagePlaneRect(static_cast<int>(dim.z)); shader_.deactivate(); fbo_.deactivate(); } } // namespace <commit_msg>BaseGL: VolumeCombiner fix: volume with index zero needs to be called volume and volumeParameters since it is used in the geometry shader<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2016 Inviwo 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "volumecombiner.h" #include <modules/opengl/volume/volumegl.h> #include <modules/opengl/texture/textureunit.h> #include <inviwo/core/util/shuntingyard.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/volume/volumeutils.h> namespace { std::string idToString (const size_t& id){ if (id == 0) return ""; return inviwo::toString(id); }; } namespace inviwo { const ProcessorInfo VolumeCombiner::processorInfo_{ "org.inviwo.VolumeCombiner", // Class identifier "Volume Combiner", // Display name "Volume Operation", // Category CodeState::Experimental, // Code state Tags::GL, // Tags }; const ProcessorInfo VolumeCombiner::getProcessorInfo() const { return processorInfo_; } VolumeCombiner::VolumeCombiner() : Processor() , inport_("inport") , outport_("outport") , description_("description", "Volumes") , eqn_("eqn", "Equation", "v1") , scales_("scales", "Scale factors") , addScale_("addScale", "Add Scale Factor") , removeScale_("removeScale", "Remove Scale Factor") , useWorldSpace_("useWorldSpaceCoordinateSystem", "World Space", false) , borderValue_("borderValue", "Border value", vec4(0.f), vec4(0.f), vec4(1.f), vec4(0.1f)) , fragment_{std::make_shared<StringShaderResource>("volumecombiner.frag", "")} , shader_({{ShaderType::Vertex, utilgl::findShaderResource("volume_gpu.vert")}, {ShaderType::Geometry, utilgl::findShaderResource("volume_gpu.geom")}, {ShaderType::Fragment, fragment_}}, Shader::Build::No) , fbo_() { description_.setSemantics(PropertySemantics::Multiline); description_.setReadOnly(true); description_.setCurrentStateAsDefault(); addPort(inport_); addPort(outport_); addProperty(description_); addProperty(eqn_); addProperty(addScale_); addProperty(removeScale_); addProperty(scales_); addProperty(useWorldSpace_); useWorldSpace_.addProperty(borderValue_); addScale_.onChange([&]() { size_t i = scales_.size(); auto p = util::make_unique<FloatProperty>("scale" + toString(i), "s" + toString(i + 1), 1.0f, -2.f, 2.f, 0.01f); p->setSerializationMode(PropertySerializationMode::All); scales_.addProperty(p.release()); }); removeScale_.onChange([&]() { if (scales_.size() > 0) { dirty_ = true; delete scales_.removeProperty(scales_.getProperties().back()); } }); eqn_.onChange([&]() { dirty_ = true; }); inport_.onConnect([&]() { dirty_ = true; updateProperties(); }); inport_.onDisconnect([&]() { dirty_ = true; updateProperties(); }); useWorldSpace_.onChange([this]() { dirty_ = true; }); } bool VolumeCombiner::isReady() const { return Processor::isReady() && (valid_ || dirty_); } #include <warn/push> #include <warn/ignore/unused-variable> std::string VolumeCombiner::buildEquation() const { std::map<std::string, double> vars = {}; std::map<std::string, std::string> symbols; size_t i = 0; for (const auto& dummy : inport_) { symbols["s" + toString(i + 1)] = "scale" + toString(i); symbols["v" + toString(i + 1)] = "vol" + toString(i); ++i; } return shuntingyard::Calculator::shaderCode(eqn_.get(), vars, symbols); } void VolumeCombiner::buildShader(const std::string& eqn) { std::stringstream ss; ss << "#include \"utils/structs.glsl\"\n"; ss << "#include \"utils/sampler3d.glsl\"\n\n"; ss << "in vec4 texCoord_;\n"; ss << "uniform vec4 " << borderValue_.getIdentifier() << ";\n"; size_t id = 0; for (const auto& dummy : inport_) { ss << "uniform sampler3D volume" << idToString(id) << ";\n"; ss << "uniform VolumeParameters volume" << idToString(id) << "Parameters;\n"; ++id; } for (auto prop : scales_.getProperties()) { ss << "uniform float " << prop->getIdentifier() << ";\n"; } ss << "\nvoid main() {\n"; id = 0; for (const auto& dummy : inport_) { const std::string vol = "vol" + toString(id); const std::string v = "volume" + idToString(id); const std::string vp = "volume" + idToString(id) + "Parameters"; if (useWorldSpace_) { const std::string coord = "coord" + toString(id); // Retrieve data from world space and use border value if outside of volume ss << " vec3 " << coord << " = (" << vp << ".worldToTexture * " << "volumeParameters.textureToWorld * texCoord_).xyz;\n"; ss << " vec4 " << vol << ";\n"; ss << " if (all(greaterThanEqual(" << coord << ", vec3(0))) &&" << " all(lessThanEqual(" << coord << ", vec3(1)))) {\n"; ss << " " << vol << " = getNormalizedVoxel(" << v << ", " << vp << ", " << coord << ");\n"; ss << " } else {\n"; ss << " " << vol << " = borderValue;\n"; ss << " }\n\n"; } else { ss << " vec4 " << vol << " = getNormalizedVoxel(" << v << ", " << vp << ", texCoord_.xyz);\n"; } ++id; } ss << " FragData0 = " << eqn << ";\n"; ss << " gl_FragDepth = 1.0;\n"; ss << "}\n"; fragment_->setSource(ss.str()); shader_.build(); } void VolumeCombiner::updateProperties() { size_t i = 0; std::stringstream desc; for (const auto& port : inport_.getConnectedOutports()) { desc << "v" + toString(i + 1) + ": " + port->getProcessor()->getIdentifier() << "\n"; i++; } description_.set(desc.str()); } #include <warn/pop> void VolumeCombiner::process() { if (inport_.isChanged()) { const DataFormatBase* format = inport_.getData()->getDataFormat(); volume_ = std::make_shared<Volume>(inport_.getData()->getDimensions(), format); volume_->setModelMatrix(inport_.getData()->getModelMatrix()); volume_->setWorldMatrix(inport_.getData()->getWorldMatrix()); // pass on metadata volume_->copyMetaDataFrom(*inport_.getData()); volume_->dataMap_ = inport_.getData()->dataMap_; outport_.setData(volume_); } if (dirty_) { dirty_ = false; try { buildShader(buildEquation()); valid_ = true; } catch (Exception& e) { valid_ = false; throw Exception(e.getMessage() + ": " + eqn_.get(), IvwContext); } } shader_.activate(); TextureUnitContainer cont; int i = 0; for (const auto& vol : inport_) { utilgl::bindAndSetUniforms(shader_, cont, *vol, "volume" + idToString(i)); ++i; } utilgl::setUniforms(shader_, borderValue_); for (auto prop : scales_.getProperties()) { utilgl::setUniforms(shader_, *static_cast<FloatProperty*>(prop)); } const size3_t dim{inport_.getData()->getDimensions()}; fbo_.activate(); glViewport(0, 0, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y)); // We always need to ask for a editable representation // this will invalidate any other representations VolumeGL* outVolumeGL = volume_->getEditableRepresentation<VolumeGL>(); if (inport_.isChanged()) { fbo_.attachColorTexture(outVolumeGL->getTexture().get(), 0); } utilgl::multiDrawImagePlaneRect(static_cast<int>(dim.z)); shader_.deactivate(); fbo_.deactivate(); } } // namespace <|endoftext|>
<commit_before>/* ** Copyright 2012-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdio> #include <cstdlib> #include <ctime> #include <iostream> #include <QSqlError> #include <QSqlQuery> #include <QVariant> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "test/cbd.hh" #include "test/config.hh" #include "test/engine.hh" #include "test/generate.hh" #include "test/misc.hh" #include "test/vars.hh" using namespace com::centreon::broker; #define DB_NAME "broker_bbdo_multiple_connections" #define ENGINE_COUNT 3 /** * Check that multiple connections to cbd work properly. * * @return EXIT_SUCCESS on success. */ int main() { // Error flag. bool error(true); // Variables that need cleaning. std::list<host> hosts[ENGINE_COUNT]; std::list<service> services[ENGINE_COUNT]; std::string engine_config_path[ENGINE_COUNT]; for (unsigned int i(0); i < ENGINE_COUNT; ++i) engine_config_path[i] = tmpnam(NULL); engine daemon[ENGINE_COUNT]; cbd broker; test_db db; try { // Prepare database. db.open(DB_NAME); db.set_remove_db_on_close(false); // Prepare monitoring engine configuration parameters. for (unsigned int i(0); i < 3; ++i) { generate_hosts(hosts[i], 1); generate_services(services[i], hosts[i], i + 1); std::string cbmod_loading; { std::ostringstream oss; oss << "broker_module=" << CBMOD_PATH << " " << PROJECT_SOURCE_DIR << "/test/cfg/bbdo_multiple_connections_" << (!i ? 0 : 1) << ".xml"; cbmod_loading = oss.str(); } // Generate monitoring engine configuration files. config_write( engine_config_path[i].c_str(), cbmod_loading.c_str(), hosts + i, services + i); } // Start Broker daemon. broker.set_config_file( PROJECT_SOURCE_DIR "/test/cfg/bbdo_multiple_connections_2.xml"); broker.start(); sleep_for(2 * MONITORING_ENGINE_INTERVAL_LENGTH); broker.update(); // Start engines. for (unsigned int i(0); i < ENGINE_COUNT; ++i) { std::string engine_config_file(engine_config_path[i]); engine_config_file.append("/nagios.cfg"); daemon[i].set_config_file(engine_config_file); daemon[i].start(); sleep_for(2 * MONITORING_ENGINE_INTERVAL_LENGTH); } sleep_for(15 * MONITORING_ENGINE_INTERVAL_LENGTH); // Terminate monitoring engine. for (int i(ENGINE_COUNT - 1); i >= 0; --i) daemon[i].stop(); // Terminate Broker daemon. broker.stop(); // Check host count. { std::ostringstream query; query << "SELECT COUNT(host_id) FROM rt_hosts"; QSqlQuery q(*db.storage_db()); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read host count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 2) || q.next()) throw (exceptions::msg() << "invalid host count: got " << q.value(0).toUInt() << ", expected 2"); } // Check service count. { std::ostringstream query; query << "SELECT COUNT(service_id) FROM rt_services"; QSqlQuery q(*db.storage_db()); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read service count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 5) || q.next()) throw (exceptions::msg() << "invalid service count: got " << q.value(0).toUInt() << ", expected 5"); } // Success. error = false; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "unknown exception" << std::endl; } // Cleanup. for (int i(ENGINE_COUNT - 1); i >= 0; --i) daemon[i].stop(); broker.stop(); for (unsigned int i(0); i < ENGINE_COUNT; ++i) config_remove(engine_config_path[i].c_str()); for (unsigned int i(0); i < ENGINE_COUNT; ++i) { free_hosts(hosts[i]); free_services(services[i]); } return (error ? EXIT_FAILURE : EXIT_SUCCESS); } <commit_msg>Test: Fix bbdo_multiple_connections unit test.<commit_after>/* ** Copyright 2012-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdio> #include <cstdlib> #include <ctime> #include <iostream> #include <QSqlError> #include <QSqlQuery> #include <QVariant> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "test/cbd.hh" #include "test/config.hh" #include "test/engine.hh" #include "test/generate.hh" #include "test/misc.hh" #include "test/vars.hh" using namespace com::centreon::broker; #define DB_NAME "broker_bbdo_multiple_connections" #define ENGINE_COUNT 3 /** * Check that multiple connections to cbd work properly. * * @return EXIT_SUCCESS on success. */ int main() { // Error flag. bool error(true); // Variables that need cleaning. std::list<host> hosts[ENGINE_COUNT]; std::list<service> services[ENGINE_COUNT]; std::string engine_config_path[ENGINE_COUNT]; for (unsigned int i(0); i < ENGINE_COUNT; ++i) engine_config_path[i] = tmpnam(NULL); engine daemon[ENGINE_COUNT]; cbd broker; test_db db; try { // Prepare database. db.open(DB_NAME); db.set_remove_db_on_close(false); // Prepare monitoring engine configuration parameters. for (unsigned int i(0); i < 3; ++i) { generate_hosts(hosts[i], 1); generate_services(services[i], hosts[i], i + 1); std::string cbmod_loading; { std::ostringstream oss; oss << "broker_module=" << CBMOD_PATH << " " << PROJECT_SOURCE_DIR << "/test/cfg/bbdo_multiple_connections_" << (!i ? 0 : 1) << ".xml"; cbmod_loading = oss.str(); } // Generate monitoring engine configuration files. config_write( engine_config_path[i].c_str(), cbmod_loading.c_str(), hosts + i, services + i); } // Start Broker daemon. broker.set_config_file( PROJECT_SOURCE_DIR "/test/cfg/bbdo_multiple_connections_2.xml"); broker.start(); sleep_for(2 * MONITORING_ENGINE_INTERVAL_LENGTH); broker.update(); // Start engines. for (unsigned int i(0); i < ENGINE_COUNT; ++i) { std::string engine_config_file(engine_config_path[i]); engine_config_file.append("/nagios.cfg"); daemon[i].set_config_file(engine_config_file); daemon[i].start(); sleep_for(2 * MONITORING_ENGINE_INTERVAL_LENGTH); } sleep_for(15 * MONITORING_ENGINE_INTERVAL_LENGTH); // Terminate monitoring engine. for (int i(ENGINE_COUNT - 1); i >= 0; --i) daemon[i].stop(); // Terminate Broker daemon. broker.stop(); // Check host count. { std::ostringstream query; query << "SELECT COUNT(host_id) FROM rt_hosts"; QSqlQuery q(*db.storage_db()); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read host count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 3) || q.next()) throw (exceptions::msg() << "invalid host count: got " << q.value(0).toUInt() << ", expected 3"); } // Check service count. { std::ostringstream query; query << "SELECT COUNT(service_id) FROM rt_services"; QSqlQuery q(*db.storage_db()); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read service count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 6) || q.next()) throw (exceptions::msg() << "invalid service count: got " << q.value(0).toUInt() << ", expected 6"); } // Success. error = false; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "unknown exception" << std::endl; } // Cleanup. for (int i(ENGINE_COUNT - 1); i >= 0; --i) daemon[i].stop(); broker.stop(); for (unsigned int i(0); i < ENGINE_COUNT; ++i) config_remove(engine_config_path[i].c_str()); for (unsigned int i(0); i < ENGINE_COUNT; ++i) { free_hosts(hosts[i]); free_services(services[i]); } return (error ? EXIT_FAILURE : EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include <limits.h> #include <stdio.h> #include <iostream> #include <stdlib.h> #include <string.h> #include <math.h> #include <vector> #include <map> #include <set> #include <algorithm> #include <assert.h> #include <string> using namespace std; typedef vector<int> VI; typedef vector<long long> VLL; typedef vector<bool> VB; typedef vector<string> VS; typedef pair<int,int> PI; typedef vector<PI> VPI; typedef long long int lint; #define FOR0(i, n) for(int i = 0; i < n; i++) #define Class_Name TheKingsFactorization #define FuncName getVector class Class_Name { class Prime { public: long long prime; int power; Prime(long long int p, int pwr) : prime(p), power(pwr) {} }; vector<Prime> factorize(long long n) { long long r = n; vector<Prime> res; long long sqrtn = sqrtl(n); for(long long int p = 2; p <= sqrtn; p++){ int c = 0; while ( r % p == 0){ c++; r = r / p; } if(c){ res.push_back(Prime(p, c)); } if(r == 1){ break; } } if(r > 1){ res.push_back(Prime(r,1)); } return res; } public: vector<long long> getVector(long long N, vector<long long> p) { FOR0(i, p.size()){ N = N/p[i]; } vector<Prime> rp = factorize(N); FOR0(i, rp.size()){ FOR0(j, rp[i].power){ p.push_back(rp[i].prime); } } sort(p.begin(), p.end()); return p; } }; #include "../utils.cpp" int main(int argc, char **argv) { Class_Name g; if(argc == 2 && strstr(argv[1],".txt")){ filename = argv[1]; } #if 1 VLL a; lint n; while((n = parseLL()) != -1){ a = parseV<lint>(); pv( g.FuncName(n, a)); } #else VI a; int n; while((a = parseVI(),a.size()) != 0){ n = parseInt(); cout << g.FuncName(a,n) << "\n"; } #endif return 0; } <commit_msg>Fixed 643-1 1<commit_after>//passed #include <limits.h> #include <stdio.h> #include <iostream> #include <stdlib.h> #include <string.h> #include <math.h> #include <vector> #include <map> #include <set> #include <algorithm> #include <assert.h> #include <string> using namespace std; typedef vector<int> VI; typedef vector<long long> VLL; typedef vector<bool> VB; typedef vector<string> VS; typedef pair<int,int> PI; typedef vector<PI> VPI; typedef long long int lint; #define FOR0(i, n) for(int i = 0; i < n; i++) #define Class_Name TheKingsFactorization #define FuncName getVector class Class_Name { class Prime { public: long long prime; int power; Prime(long long int p, int pwr) : prime(p), power(pwr) {} }; /* we know that there are at max maxf factors */ vector<Prime> factorize(long long n, int maxf) { long long r = n; vector<Prime> res; long long sqrtn = sqrtl(n); for(long long int p = 2; p <= sqrtn; p++){ if(maxf == 1){ //r must be prime break; } int c = 0; while ( r % p == 0){ c++; maxf--; r = r / p; } if(c){ res.push_back(Prime(p, c)); } if(r == 1){ break; } } if(r > 1){ res.push_back(Prime(r,1)); } return res; } public: vector<long long> getVector(long long N, vector<long long> p) { FOR0(i, p.size()){ N = N/p[i]; } vector<Prime> rp = factorize(N, p.size()); FOR0(i, rp.size()){ FOR0(j, rp[i].power){ p.push_back(rp[i].prime); } } sort(p.begin(), p.end()); return p; } }; #include "../utils.cpp" int main(int argc, char **argv) { Class_Name g; if(argc == 2 && strstr(argv[1],".txt")){ filename = argv[1]; } #if 1 VLL a; lint n; while((n = parseLL()) != -1){ a = parseV<lint>(); pv( g.FuncName(n, a)); } #else VI a; int n; while((a = parseVI(),a.size()) != 0){ n = parseInt(); cout << g.FuncName(a,n) << "\n"; } #endif return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016, https://github.com/zhatalk * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "dal/user_sequence_dao_impl.h" UserSequenceDAO& UserSequenceDAO::GetInstance() { static UserSequenceDAOImpl impl; return impl; } int64_t UserSequenceDAOImpl::Create(UserSequenceDO& user_sequence) { return DoStorageInsertID("nebula_engine", [&](std::string& query_string) { db::QueryParam p; p.AddParam(user_sequence.user_id.c_str()); p.AddParam(&user_sequence.seq); p.AddParam(&user_sequence.header); // p.AddParamEsc(user_sequence.data.c_str()); p.AddParam(&user_sequence.created_at); db::MakeQueryString("INSERT INTO user_sequence" "(user_id,seq,header,data,created_at)" " VALUES " "(:1,:2,:3,'testing',:4)", &p, &query_string); }); } <commit_msg>benqi: user_sequence表data字段修改为blob类型<commit_after>/* * Copyright (c) 2016, https://github.com/zhatalk * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "dal/user_sequence_dao_impl.h" UserSequenceDAO& UserSequenceDAO::GetInstance() { static UserSequenceDAOImpl impl; return impl; } int64_t UserSequenceDAOImpl::Create(UserSequenceDO& user_sequence) { return DoStorageInsertID("nebula_engine", [&](std::string& query_string) { db::QueryParam p; p.AddParam(user_sequence.user_id.c_str()); p.AddParam(&user_sequence.seq); p.AddParam(&user_sequence.header); p.AddParamEsc(user_sequence.data.c_str()); p.AddParam(&user_sequence.created_at); db::MakeQueryString("INSERT INTO user_sequence" "(user_id,seq,header,data,created_at)" " VALUES " "(:1,:2,:3,:4,:5)", &p, &query_string); }); } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "nodes/Reference.h" #include "commands/FieldSet.h" #include "model/Model.h" #include "ModelException.h" #include "NameText.h" #include "ModelBase/src/nodes/TypedListDefinition.h" DEFINE_TYPED_LIST(Model::Reference) namespace Model { NODE_DEFINE_TYPE_REGISTRATION_METHODS(Reference) QSet<Reference*> Reference::pendingResolution_; Reference::Reference(Node *parent) : Super(parent) { if (parent && parent->model()) pendingResolution_.insert(this); } Reference::Reference(Node *parent, PersistentStore &store, bool) : Super(parent) { name_ = store.loadReferenceValue(this); if (state_ == ReferenceNeedsToBeResolved && parent && parent->model()) pendingResolution_.insert(this); } Reference::~Reference() { pendingResolution_.remove(this); } void Reference::setName(const QString &name) { if (name != name_) { execute(new FieldSet<QString> (this, name_, name)); target_ = nullptr; setResolutionNeeded(); } } Node* Reference::computeTarget() const { Q_ASSERT(false && "Should not call Reference::computeTarget()"); return nullptr; } bool Reference::resolveHelper(bool indirect) { // TODO this is not multithread friendly. if (state_ != ReferenceNeedsToBeResolved) return isResolved(); state_ = ReferenceIsBeingResolved; auto newTarget = computeTarget(); Q_ASSERT(!newTarget || (newTarget->definesSymbol() && newTarget->symbolName() == name_)); auto oldTarget = target_; target_ = newTarget; if (target_ || !indirect) { // This is needed because of the following situation. // We are resolving a reference A, and during the process we explore reference B, needed for the resolution of A, // and reference C, which is not needed for the resolution of A. All references but A will be explored indirectly. // It could happen that to resolve C properly we need to resolve A first. Therefore when failing to resolve a // reference that is explored indirectly, we shouldn't assume that resolution will fail. pendingResolution_.remove(this); state_ = ReferenceEstablished; } else state_ = ReferenceNeedsToBeResolved; if (oldTarget != target_) targetChanged(oldTarget); return isResolved(); } void Reference::targetChanged(Node*){} void Reference::save(PersistentStore &store) const { store.saveReferenceValue(name_, target_); } void Reference::load(PersistentStore &store) { // TODO: Implement reference loading properly. throw ModelException("Loading references outside a Reference constructor is not properly implemented yet"); if (store.currentNodeType() != typeName()) throw ModelException("Trying to load a Reference node from an incompatible node type " + store.currentNodeType()); setName( store.loadReferenceValue(this) ); } Node* Reference::target() { if (state_ == ReferenceNeedsToBeResolved) resolveHelper(true); return state_ == ReferenceEstablished ? target_ : nullptr; } void Reference::setResolutionNeeded() { state_ = ReferenceNeedsToBeResolved; pendingResolution_.insert(this); } template<class NodeType> void Reference::forAll(Node* subTree, Node* avoid, std::function<void (NodeType*)> function) { if (subTree) { QList<Node*> stack; stack << subTree; while (!stack.isEmpty()) { auto top = stack.takeLast(); if (top == avoid) continue; if (auto node = DCast<NodeType>(top) ) function(node); else stack.append(top->children()); } } } void Reference::unresolveAll(Node* subTree, bool markForResolution) { if (markForResolution) forAll<Reference>(subTree, nullptr, [](Reference* ref) { ref->setResolutionNeeded();}); else forAll<Reference>(subTree, nullptr, [](Reference* ref) { ref->state_ = ReferenceNeedsToBeResolved; }); } void Reference::unresolveNames(Node* subTree, bool markForResolution, const QSet<QString>& names) { if (markForResolution) forAll<Reference>(subTree, nullptr, [=](Reference* ref) { if (names.contains(ref->name())) ref->setResolutionNeeded();}); else forAll<Reference>(subTree, nullptr, [=](Reference* ref) { if (names.contains(ref->name())) ref->state_ = ReferenceNeedsToBeResolved; }); } void Reference::unresolveIfNameIntroduced(Node* subTreeToUnresolve, bool markForResolution, Node* subTreeToLookForNewNames) { QSet<QString> names; forAll<NameText>(subTreeToLookForNewNames, nullptr, [&names](NameText* name){ names.insert(name->get());}); if (markForResolution) forAll<Reference>(subTreeToUnresolve, subTreeToLookForNewNames, [=](Reference* ref) { if (names.contains(ref->name())) ref->setResolutionNeeded();}); else forAll<Reference>(subTreeToUnresolve, subTreeToLookForNewNames, [=](Reference* ref) { if (names.contains(ref->name())) ref->state_ = ReferenceNeedsToBeResolved; }); } void Reference::resolvePending() { log.debug("Resolving references"); int i = 0; int round = 0; int resolved = 0; auto pending = pendingResolution_; while(!pending.isEmpty()) { log.debug("resolution round " + QString::number(round) + ", " + QString::number(pendingResolution_.size()) + " references pending."); ++round; for (auto r : pending) { if ( r->resolve() ) ++resolved; if (++i % 10000 == 0) log.debug("Processed " + QString::number(i) + " references."); } // As a result of resolution of some references, some other references could have become invalid. pending = pendingResolution_; } log.debug("Resolved a total of " + QString::number(resolved) + " references in " + QString::number(round) + (round > 1 ? " rounds." : " round.")); } } <commit_msg>Skip reference exploration when there is nothing to resolve.<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "nodes/Reference.h" #include "commands/FieldSet.h" #include "model/Model.h" #include "ModelException.h" #include "NameText.h" #include "ModelBase/src/nodes/TypedListDefinition.h" DEFINE_TYPED_LIST(Model::Reference) namespace Model { NODE_DEFINE_TYPE_REGISTRATION_METHODS(Reference) QSet<Reference*> Reference::pendingResolution_; Reference::Reference(Node *parent) : Super(parent) { if (parent && parent->model()) pendingResolution_.insert(this); } Reference::Reference(Node *parent, PersistentStore &store, bool) : Super(parent) { name_ = store.loadReferenceValue(this); if (state_ == ReferenceNeedsToBeResolved && parent && parent->model()) pendingResolution_.insert(this); } Reference::~Reference() { pendingResolution_.remove(this); } void Reference::setName(const QString &name) { if (name != name_) { execute(new FieldSet<QString> (this, name_, name)); target_ = nullptr; setResolutionNeeded(); } } Node* Reference::computeTarget() const { Q_ASSERT(false && "Should not call Reference::computeTarget()"); return nullptr; } bool Reference::resolveHelper(bool indirect) { // TODO this is not multithread friendly. if (state_ != ReferenceNeedsToBeResolved) return isResolved(); state_ = ReferenceIsBeingResolved; auto newTarget = computeTarget(); Q_ASSERT(!newTarget || (newTarget->definesSymbol() && newTarget->symbolName() == name_)); auto oldTarget = target_; target_ = newTarget; if (target_ || !indirect) { // This is needed because of the following situation. // We are resolving a reference A, and during the process we explore reference B, needed for the resolution of A, // and reference C, which is not needed for the resolution of A. All references but A will be explored indirectly. // It could happen that to resolve C properly we need to resolve A first. Therefore when failing to resolve a // reference that is explored indirectly, we shouldn't assume that resolution will fail. pendingResolution_.remove(this); state_ = ReferenceEstablished; } else state_ = ReferenceNeedsToBeResolved; if (oldTarget != target_) targetChanged(oldTarget); return isResolved(); } void Reference::targetChanged(Node*){} void Reference::save(PersistentStore &store) const { store.saveReferenceValue(name_, target_); } void Reference::load(PersistentStore &store) { // TODO: Implement reference loading properly. throw ModelException("Loading references outside a Reference constructor is not properly implemented yet"); if (store.currentNodeType() != typeName()) throw ModelException("Trying to load a Reference node from an incompatible node type " + store.currentNodeType()); setName( store.loadReferenceValue(this) ); } Node* Reference::target() { if (state_ == ReferenceNeedsToBeResolved) resolveHelper(true); return state_ == ReferenceEstablished ? target_ : nullptr; } void Reference::setResolutionNeeded() { state_ = ReferenceNeedsToBeResolved; pendingResolution_.insert(this); } template<class NodeType> void Reference::forAll(Node* subTree, Node* avoid, std::function<void (NodeType*)> function) { if (subTree) { QList<Node*> stack; stack << subTree; while (!stack.isEmpty()) { auto top = stack.takeLast(); if (top == avoid) continue; if (auto node = DCast<NodeType>(top) ) function(node); else stack.append(top->children()); } } } void Reference::unresolveAll(Node* subTree, bool markForResolution) { if (markForResolution) forAll<Reference>(subTree, nullptr, [](Reference* ref) { ref->setResolutionNeeded();}); else forAll<Reference>(subTree, nullptr, [](Reference* ref) { ref->state_ = ReferenceNeedsToBeResolved; }); } void Reference::unresolveNames(Node* subTree, bool markForResolution, const QSet<QString>& names) { if (markForResolution) forAll<Reference>(subTree, nullptr, [=](Reference* ref) { if (names.contains(ref->name())) ref->setResolutionNeeded();}); else forAll<Reference>(subTree, nullptr, [=](Reference* ref) { if (names.contains(ref->name())) ref->state_ = ReferenceNeedsToBeResolved; }); } void Reference::unresolveIfNameIntroduced(Node* subTreeToUnresolve, bool markForResolution, Node* subTreeToLookForNewNames) { QSet<QString> names; forAll<NameText>(subTreeToLookForNewNames, nullptr, [&names](NameText* name){ names.insert(name->get());}); if (names.isEmpty()) return; if (markForResolution) forAll<Reference>(subTreeToUnresolve, subTreeToLookForNewNames, [=](Reference* ref) { if (names.contains(ref->name())) ref->setResolutionNeeded();}); else forAll<Reference>(subTreeToUnresolve, subTreeToLookForNewNames, [=](Reference* ref) { if (names.contains(ref->name())) ref->state_ = ReferenceNeedsToBeResolved; }); } void Reference::resolvePending() { log.debug("Resolving references"); int i = 0; int round = 0; int resolved = 0; auto pending = pendingResolution_; while(!pending.isEmpty()) { log.debug("resolution round " + QString::number(round) + ", " + QString::number(pendingResolution_.size()) + " references pending."); ++round; for (auto r : pending) { if ( r->resolve() ) ++resolved; if (++i % 10000 == 0) log.debug("Processed " + QString::number(i) + " references."); } // As a result of resolution of some references, some other references could have become invalid. pending = pendingResolution_; } log.debug("Resolved a total of " + QString::number(resolved) + " references in " + QString::number(round) + (round > 1 ? " rounds." : " round.")); } } <|endoftext|>
<commit_before>#include <ncurses.h> #include <iostream> #include <unistd.h> #include <algorithm> #include "interface/Display.h" #include "map/Level.h" #include "map/filters/DrunkardsWalkFilter.h" #include "core/Rand.h" #include "entity/ecs.h" void pause_curses(Display& display) { display.pause(); std::cout << "Paused ncurses..." << std::endl; sleep(4); std::cout << "Resuming..." << std::endl; sleep(1); display.resume(); } bool move_pc(Level& level, PositionComponent& pc_pos, int dx, int dy) { int new_x = pc_pos.x + dx; int new_y = pc_pos.y + dy; //Make sure it's in bounds if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight()) { //Make sure it's passable terrain if(level[new_x][new_y].isPassable()) { //Adjust PC's x,y coordinates pc_pos.x += dx; pc_pos.y += dy; return true; } } return false; } void spawn_npc(Level& level, PositionComponent& npc_pos, PositionComponent& pc_pos, int max_dist = 15) { static Rand rand(time(NULL)); int min_x = std::max(0, pc_pos.x - max_dist); int max_x = std::min(level.getWidth()-1, pc_pos.x + max_dist); int min_y = std::max(0, pc_pos.y - max_dist); int max_y = std::min(level.getHeight()-1, pc_pos.y + max_dist); do { npc_pos.x = rand.randInt(min_x, max_x); npc_pos.y = rand.randInt(min_y, max_y); } while(level[npc_pos.x][npc_pos.y] != FloorTile); } int main() { Display display; EntityManager em; //Set up our ComponentManagers PositionManager pos_mgr; SpriteManager sprite_mgr; SkillManager skill_mgr; AttackManager attack_mgr; em.addComponentManager(&pos_mgr); em.addComponentManager(&sprite_mgr); em.addComponentManager(&skill_mgr); em.addComponentManager(&attack_mgr); //We'll also need an AttackSystem, though no setup is necessary AttackSystem sys_attack; XYPair screen = display.getScreenSize(); //Make a map double the screen size int map_y = screen.y * 2; int map_x = screen.x * 2; //Generate a map Level cave(map_x, map_y); DrunkardsWalkFilter walk; walk.setSeed(time(NULL)); walk.apply(cave); //Find a random FloorTile to put our PC on Entity pc = em.createEntity(); PositionComponent pc_pos; SpriteComponent pc_sprite = { '@', 0, 0 }; Rand rand(time(NULL)); do { pc_pos.x = rand.randInt(0, cave.getWidth()-1); pc_pos.y = rand.randInt(0, cave.getHeight()-1); } while(cave[pc_pos.x][pc_pos.y] != FloorTile); pos_mgr.setComponent(pc, pc_pos); sprite_mgr.setComponent(pc, pc_sprite); //Now create a Window and viewport for our level WindowGeometry map_geometry = { {20,3}, {AUTO_SIZE, AUTO_SIZE} }; Window map = display.addWindow(cave, map_geometry); //Geometries for our top and left Windows WindowGeometry top_geometry = { {0,0}, {AUTO_SIZE, 3} }; WindowGeometry left_geometry = { { 0, 3 }, {20, AUTO_SIZE} }; //And now create them Window top = display.addWindow(top_geometry); Window left = display.addWindow(left_geometry); //top.addBorder(); //left.addBorder(); //New set up our RenderSystem RenderSystem render(&display, map); display.add(top, mkXYPair(1,0), "Message Panel"); display.add(left, mkXYPair(1,0), "Stat Panel"); //Center the map viewport on the PC //map.center(pc_pos.x, pc_pos.y); //Let's display some map display stats //Display our view's X and Y coordinates //wm.getWindow(1)->add(1, 2, "View Position:"); //wm.getWindow(1)->add(1, 3, "X: "); //wm.getWindow(1)->addInt(4, 3, map.getViewX()); //wm.getWindow(1)->add(1, 4, "Y: "); //wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Display map size //wm.getWindow(1)->add(1, 6, "Map Size:"); //wm.getWindow(1)->add(1, 7, "W:"); //wm.getWindow(1)->addInt(4, 7, cave.getWidth()); //wm.getWindow(1)->add(1, 8, "H:"); //wm.getWindow(1)->addInt(4, 8, cave.getHeight()); //Display viewport size //wm.getWindow(1)->add(1, 9, "View Size:"); //wm.getWindow(1)->add(1, 10, "W:"); //wm.getWindow(1)->addInt(4, 10, map.getViewWidth()); //wm.getWindow(1)->add(1, 11, "H:"); //wm.getWindow(1)->addInt(4, 11, map.getViewHeight()); //Display PC's location //wm.getWindow(1)->add(1, 12, "PC Position:"); //wm.getWindow(1)->add(1, 13, "X: "); //wm.getWindow(1)->addInt(4, 13, pc_pos.x); //wm.getWindow(1)->add(1, 14, "Y: "); //wm.getWindow(1)->addInt(4, 14, pc_pos.y); //Find a random FloorTile to put our kobold on Entity kobold = em.createEntity(); PositionComponent npc_pos; SpriteComponent npc_sprite = { 'k', 0, 0 }; spawn_npc(cave, npc_pos, pc_pos, 15); pos_mgr.setComponent(kobold, npc_pos); sprite_mgr.setComponent(kobold, npc_sprite); //just another entity Entity goblin = em.createEntity(); PositionComponent npc2_pos; SpriteComponent npc2_sprite = { 'g', 0, 0 }; spawn_npc(cave, npc2_pos, pc_pos, 15); pos_mgr.setComponent(goblin, npc2_pos); sprite_mgr.setComponent(goblin, npc2_sprite); //Attack skills SkillComponent pc_atk = { 13, 0 }; skill_mgr.setComponent(pc, BastardSword, pc_atk); //Defense skills SkillComponent npc_dodge = { 10, 0 }; skill_mgr.setComponent(kobold, Dodge, npc_dodge); SkillComponent npc2_dodge = { 10, 0 }; skill_mgr.setComponent(goblin, Dodge, npc2_dodge); //Now display everything render.execute(em); display.refresh(); //Now we enter the "game loop" int ch; int key_pos = 8; int last_key_pos; int dx, dy; int pc_dx, pc_dy; bool run = true; sleep(2); while(run) { ch = getch(); //Display the key code //wm.getWindow(0)->add(key_pos, 1, " "); //wm.getWindow(0)->addInt(key_pos, 1, ch); dx = 0; dy = 0; pc_dx = 0; pc_dy = 0; //wm.getWindow(0)->add(1, 1, " "); last_key_pos = key_pos; key_pos = 8; switch(ch) { //Viewport movement case KEY_UP: //wm.getWindow(0)->add(1, 1, "Up"); dy = -1; break; case KEY_DOWN: //wm.getWindow(0)->add(1, 1, "Down"); dy = 1; break; case KEY_LEFT: //wm.getWindow(0)->add(1, 1, "Left"); dx = -1; break; case KEY_RIGHT: //wm.getWindow(0)->add(1, 1, "Right"); dx = 1; break; //Orthogonal movement case '8': case 'k': pc_dx = 0; pc_dy = -1; break; case '2': case 'j': pc_dx = 0; pc_dy = 1; break; case '4': case 'h': pc_dx = -1; pc_dy = 0; break; case '6': case 'l': pc_dx = 1; pc_dy = 0; break; //Diagonal movement case '7': case 'y': pc_dx = -1; pc_dy = -1; break; case '9': case 'u': pc_dx = 1; pc_dy = -1; break; case '1': case 'b': pc_dx = -1; pc_dy = 1; break; case '3': case 'n': pc_dx = 1; pc_dy = 1; break; //Other commands case 'c': case 'C': //Center the view on the PC //wm.getWindow(2)->center(pc_pos.x, pc_pos.y); break; case 'p': case 'P': //Pause ncurses (just a useless demo of the ability) pause_curses(display); break; case 'q': case 'Q': //Quit run = false; break; default: key_pos = last_key_pos + 4; if(key_pos > display.getScreenSize().x) { key_pos = 8; } break; } if(pc_dx != 0 || pc_dy != 0) { //Test if the NPC is there if(pos_mgr.isPositionOccupied(pc_pos.x + pc_dx, pc_pos.y + pc_dy)) { //There will be a fight! AttackComponent atk = { pos_mgr.getEntityAtPosition(pc_pos.x + pc_dx, pc_pos.y + pc_dy), BastardSword }; attack_mgr.setComponent(pc, atk); } else { //Move the PC move_pc(cave, pc_pos, pc_dx, pc_dy); pos_mgr.setComponent(pc, pc_pos); } } //Process systems in order sys_attack.execute(em); render.execute(em); //Respawn a fresh kobold if we need to if(!em.isEntityAlive(kobold)) { kobold = em.createEntity(); spawn_npc(cave, npc_pos, pc_pos, 15); pos_mgr.setComponent(kobold, npc_pos); sprite_mgr.setComponent(kobold, npc_sprite); } //Respawn a fresh goblin if we need to if(!em.isEntityAlive(goblin)) { goblin = em.createEntity(); spawn_npc(cave, npc2_pos, pc_pos, 15); pos_mgr.setComponent(goblin, npc2_pos); sprite_mgr.setComponent(goblin, npc2_sprite); } //Move the viewport //map.moveBy(dx, dy); //Display our view's X and Y coordinates //wm.getWindow(1)->add(1, 3, "X: "); //wm.getWindow(1)->addInt(4, 3, map.getViewX()); //wm.getWindow(1)->add(1, 4, "Y: "); //wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Re-display PC's position //wm.getWindow(1)->add(1, 13, "X: "); //wm.getWindow(1)->addInt(4, 13, pc_pos.x); //wm.getWindow(1)->add(1, 14, "Y: "); //wm.getWindow(1)->addInt(4, 14, pc_pos.y); //Display NPC's position //wm.getWindow(1)->add(1, 15, "NPC Position:"); //wm.getWindow(1)->add(1, 16, "X: "); //wm.getWindow(1)->addInt(4, 16, npc_pos.x); //wm.getWindow(1)->add(1, 17, "Y: "); //wm.getWindow(1)->addInt(4, 17, npc_pos.y); //wm.getWindow(1)->addInt(1, 19, pc); //wm.getWindow(1)->addInt(5, 19, sprite_mgr.getComponent(pc).c); //wm.getWindow(1)->addInt(1, 20, kobold); //wm.getWindow(1)->addInt(5, 20, sprite_mgr.getComponent(kobold).c); //wm.getWindow(1)->addInt(1, 21, goblin); //wm.getWindow(1)->addInt(5, 21, sprite_mgr.getComponent(goblin).c); //Refresh the display display.refresh(); } } <commit_msg>InterfaceTest now centers viewport on the PC on startup<commit_after>#include <ncurses.h> #include <iostream> #include <unistd.h> #include <algorithm> #include "interface/Display.h" #include "map/Level.h" #include "map/filters/DrunkardsWalkFilter.h" #include "core/Rand.h" #include "entity/ecs.h" void pause_curses(Display& display) { display.pause(); std::cout << "Paused ncurses..." << std::endl; sleep(4); std::cout << "Resuming..." << std::endl; sleep(1); display.resume(); } bool move_pc(Level& level, PositionComponent& pc_pos, int dx, int dy) { int new_x = pc_pos.x + dx; int new_y = pc_pos.y + dy; //Make sure it's in bounds if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight()) { //Make sure it's passable terrain if(level[new_x][new_y].isPassable()) { //Adjust PC's x,y coordinates pc_pos.x += dx; pc_pos.y += dy; return true; } } return false; } void spawn_npc(Level& level, PositionComponent& npc_pos, PositionComponent& pc_pos, int max_dist = 15) { static Rand rand(time(NULL)); int min_x = std::max(0, pc_pos.x - max_dist); int max_x = std::min(level.getWidth()-1, pc_pos.x + max_dist); int min_y = std::max(0, pc_pos.y - max_dist); int max_y = std::min(level.getHeight()-1, pc_pos.y + max_dist); do { npc_pos.x = rand.randInt(min_x, max_x); npc_pos.y = rand.randInt(min_y, max_y); } while(level[npc_pos.x][npc_pos.y] != FloorTile); } int main() { Display display; EntityManager em; //Set up our ComponentManagers PositionManager pos_mgr; SpriteManager sprite_mgr; SkillManager skill_mgr; AttackManager attack_mgr; em.addComponentManager(&pos_mgr); em.addComponentManager(&sprite_mgr); em.addComponentManager(&skill_mgr); em.addComponentManager(&attack_mgr); //We'll also need an AttackSystem, though no setup is necessary AttackSystem sys_attack; XYPair screen = display.getScreenSize(); //Make a map double the screen size int map_y = screen.y * 2; int map_x = screen.x * 2; //Generate a map Level cave(map_x, map_y); DrunkardsWalkFilter walk; walk.setSeed(time(NULL)); walk.apply(cave); //Find a random FloorTile to put our PC on Entity pc = em.createEntity(); PositionComponent pc_pos; SpriteComponent pc_sprite = { '@', 0, 0 }; Rand rand(time(NULL)); do { pc_pos.x = rand.randInt(0, cave.getWidth()-1); pc_pos.y = rand.randInt(0, cave.getHeight()-1); } while(cave[pc_pos.x][pc_pos.y] != FloorTile); pos_mgr.setComponent(pc, pc_pos); sprite_mgr.setComponent(pc, pc_sprite); //Now create a Window and viewport for our level WindowGeometry map_geometry = { {20,3}, {AUTO_SIZE, AUTO_SIZE} }; Window map = display.addWindow(cave, map_geometry); //Geometries for our top and left Windows WindowGeometry top_geometry = { {0,0}, {AUTO_SIZE, 3} }; WindowGeometry left_geometry = { { 0, 3 }, {20, AUTO_SIZE} }; //And now create them Window top = display.addWindow(top_geometry); Window left = display.addWindow(left_geometry); //top.addBorder(); //left.addBorder(); //New set up our RenderSystem RenderSystem render(&display, map); display.add(top, mkXYPair(1,0), "Message Panel"); display.add(left, mkXYPair(1,0), "Stat Panel"); //Center the map viewport on the PC display.center(map, pc_pos); //Let's display some map display stats //Display our view's X and Y coordinates //wm.getWindow(1)->add(1, 2, "View Position:"); //wm.getWindow(1)->add(1, 3, "X: "); //wm.getWindow(1)->addInt(4, 3, map.getViewX()); //wm.getWindow(1)->add(1, 4, "Y: "); //wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Display map size //wm.getWindow(1)->add(1, 6, "Map Size:"); //wm.getWindow(1)->add(1, 7, "W:"); //wm.getWindow(1)->addInt(4, 7, cave.getWidth()); //wm.getWindow(1)->add(1, 8, "H:"); //wm.getWindow(1)->addInt(4, 8, cave.getHeight()); //Display viewport size //wm.getWindow(1)->add(1, 9, "View Size:"); //wm.getWindow(1)->add(1, 10, "W:"); //wm.getWindow(1)->addInt(4, 10, map.getViewWidth()); //wm.getWindow(1)->add(1, 11, "H:"); //wm.getWindow(1)->addInt(4, 11, map.getViewHeight()); //Display PC's location //wm.getWindow(1)->add(1, 12, "PC Position:"); //wm.getWindow(1)->add(1, 13, "X: "); //wm.getWindow(1)->addInt(4, 13, pc_pos.x); //wm.getWindow(1)->add(1, 14, "Y: "); //wm.getWindow(1)->addInt(4, 14, pc_pos.y); //Find a random FloorTile to put our kobold on Entity kobold = em.createEntity(); PositionComponent npc_pos; SpriteComponent npc_sprite = { 'k', 0, 0 }; spawn_npc(cave, npc_pos, pc_pos, 15); pos_mgr.setComponent(kobold, npc_pos); sprite_mgr.setComponent(kobold, npc_sprite); //just another entity Entity goblin = em.createEntity(); PositionComponent npc2_pos; SpriteComponent npc2_sprite = { 'g', 0, 0 }; spawn_npc(cave, npc2_pos, pc_pos, 15); pos_mgr.setComponent(goblin, npc2_pos); sprite_mgr.setComponent(goblin, npc2_sprite); //Attack skills SkillComponent pc_atk = { 13, 0 }; skill_mgr.setComponent(pc, BastardSword, pc_atk); //Defense skills SkillComponent npc_dodge = { 10, 0 }; skill_mgr.setComponent(kobold, Dodge, npc_dodge); SkillComponent npc2_dodge = { 10, 0 }; skill_mgr.setComponent(goblin, Dodge, npc2_dodge); //Now display everything render.execute(em); display.refresh(); //Now we enter the "game loop" int ch; int key_pos = 8; int last_key_pos; int dx, dy; int pc_dx, pc_dy; bool run = true; sleep(2); while(run) { ch = getch(); //Display the key code //wm.getWindow(0)->add(key_pos, 1, " "); //wm.getWindow(0)->addInt(key_pos, 1, ch); dx = 0; dy = 0; pc_dx = 0; pc_dy = 0; //wm.getWindow(0)->add(1, 1, " "); last_key_pos = key_pos; key_pos = 8; switch(ch) { //Viewport movement case KEY_UP: //wm.getWindow(0)->add(1, 1, "Up"); dy = -1; break; case KEY_DOWN: //wm.getWindow(0)->add(1, 1, "Down"); dy = 1; break; case KEY_LEFT: //wm.getWindow(0)->add(1, 1, "Left"); dx = -1; break; case KEY_RIGHT: //wm.getWindow(0)->add(1, 1, "Right"); dx = 1; break; //Orthogonal movement case '8': case 'k': pc_dx = 0; pc_dy = -1; break; case '2': case 'j': pc_dx = 0; pc_dy = 1; break; case '4': case 'h': pc_dx = -1; pc_dy = 0; break; case '6': case 'l': pc_dx = 1; pc_dy = 0; break; //Diagonal movement case '7': case 'y': pc_dx = -1; pc_dy = -1; break; case '9': case 'u': pc_dx = 1; pc_dy = -1; break; case '1': case 'b': pc_dx = -1; pc_dy = 1; break; case '3': case 'n': pc_dx = 1; pc_dy = 1; break; //Other commands case 'c': case 'C': //Center the view on the PC //wm.getWindow(2)->center(pc_pos.x, pc_pos.y); break; case 'p': case 'P': //Pause ncurses (just a useless demo of the ability) pause_curses(display); break; case 'q': case 'Q': //Quit run = false; break; default: key_pos = last_key_pos + 4; if(key_pos > display.getScreenSize().x) { key_pos = 8; } break; } if(pc_dx != 0 || pc_dy != 0) { //Test if the NPC is there if(pos_mgr.isPositionOccupied(pc_pos.x + pc_dx, pc_pos.y + pc_dy)) { //There will be a fight! AttackComponent atk = { pos_mgr.getEntityAtPosition(pc_pos.x + pc_dx, pc_pos.y + pc_dy), BastardSword }; attack_mgr.setComponent(pc, atk); } else { //Move the PC move_pc(cave, pc_pos, pc_dx, pc_dy); pos_mgr.setComponent(pc, pc_pos); } } //Process systems in order sys_attack.execute(em); render.execute(em); //Respawn a fresh kobold if we need to if(!em.isEntityAlive(kobold)) { kobold = em.createEntity(); spawn_npc(cave, npc_pos, pc_pos, 15); pos_mgr.setComponent(kobold, npc_pos); sprite_mgr.setComponent(kobold, npc_sprite); } //Respawn a fresh goblin if we need to if(!em.isEntityAlive(goblin)) { goblin = em.createEntity(); spawn_npc(cave, npc2_pos, pc_pos, 15); pos_mgr.setComponent(goblin, npc2_pos); sprite_mgr.setComponent(goblin, npc2_sprite); } //Move the viewport //map.moveBy(dx, dy); //Display our view's X and Y coordinates //wm.getWindow(1)->add(1, 3, "X: "); //wm.getWindow(1)->addInt(4, 3, map.getViewX()); //wm.getWindow(1)->add(1, 4, "Y: "); //wm.getWindow(1)->addInt(4, 4, map.getViewY()); //Re-display PC's position //wm.getWindow(1)->add(1, 13, "X: "); //wm.getWindow(1)->addInt(4, 13, pc_pos.x); //wm.getWindow(1)->add(1, 14, "Y: "); //wm.getWindow(1)->addInt(4, 14, pc_pos.y); //Display NPC's position //wm.getWindow(1)->add(1, 15, "NPC Position:"); //wm.getWindow(1)->add(1, 16, "X: "); //wm.getWindow(1)->addInt(4, 16, npc_pos.x); //wm.getWindow(1)->add(1, 17, "Y: "); //wm.getWindow(1)->addInt(4, 17, npc_pos.y); //wm.getWindow(1)->addInt(1, 19, pc); //wm.getWindow(1)->addInt(5, 19, sprite_mgr.getComponent(pc).c); //wm.getWindow(1)->addInt(1, 20, kobold); //wm.getWindow(1)->addInt(5, 20, sprite_mgr.getComponent(kobold).c); //wm.getWindow(1)->addInt(1, 21, goblin); //wm.getWindow(1)->addInt(5, 21, sprite_mgr.getComponent(goblin).c); //Refresh the display display.refresh(); } } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "SoundSystem.h" #include "OpenALAudioModule.h" #include "WavLoader.h" #include "VorbisDecoder.h" #include "RexTypes.h" #include "AssetServiceInterface.h" #include "AssetEvents.h" #include <boost/thread/mutex.hpp> namespace OpenALAudio { const Core::uint DEFAULT_SOUND_CACHE_SIZE = 32 * 1024 * 1024; const Core::f64 CACHE_CHECK_INTERVAL = 1.0; SoundSystem::SoundSystem(Foundation::Framework *framework) : framework_(framework), initialized_(false), context_(0), device_(0), next_channel_id_(0), sound_cache_size_(DEFAULT_SOUND_CACHE_SIZE), update_time_(0), listener_position_(0.0, 0.0, 0.0) { sound_cache_size_ = framework_->GetDefaultConfig().DeclareSetting("SoundSystem", "sound_cache_size", DEFAULT_SOUND_CACHE_SIZE); Initialize(); // Create vorbis decoder thread task and let the framework thread task manager handle it VorbisDecoder* decoder = new VorbisDecoder(); framework_->GetThreadTaskManager()->AddThreadTask(Foundation::ThreadTaskPtr(decoder)); } SoundSystem::~SoundSystem() { Uninitialize(); } void SoundSystem::Initialize() { if (initialized_) return; device_ = alcOpenDevice(NULL); if (!device_) { OpenALAudioModule::LogWarning("Could not open OpenAL sound device"); return; } context_ = alcCreateContext(device_, NULL); if (!context_) { OpenALAudioModule::LogWarning("Could not create OpenAL sound context"); return; } alcMakeContextCurrent(context_); initialized_ = true; mutex.initialize(); } void SoundSystem::Uninitialize() { if (context_) { alcMakeContextCurrent(0); alcDestroyContext(context_); context_ = 0; } if (device_) { alcCloseDevice(device_); device_ = 0; } initialized_ = false; } Foundation::SoundServiceInterface::SoundState SoundSystem::GetSoundState(Core::sound_id_t id) const { SoundChannelMap::const_iterator i = channels_.find(id); if (i == channels_.end()) return Foundation::SoundServiceInterface::Stopped; return i->second->GetState(); } std::vector<Core::sound_id_t> SoundSystem::GetActiveSounds() const { std::vector<Core::sound_id_t> ret; SoundChannelMap::const_iterator i = channels_.begin(); while (i != channels_.end()) { if (i->second->GetState() != Foundation::SoundServiceInterface::Stopped) ret.push_back(i->first); ++i; } return ret; } const std::string& SoundSystem::GetSoundName(Core::sound_id_t id) const { static std::string empty; SoundChannelMap::const_iterator i = channels_.find(id); if (i == channels_.end()) return empty; return i->second->GetSoundName(); } void SoundSystem::Update(Core::f64 frametime) { mutex.lock(); std::vector<SoundChannelMap::iterator> channels_to_delete; // Update listener position/orientation to sound device ALfloat pos[] = {listener_position_.x, listener_position_.y, listener_position_.z}; alListenerfv(AL_POSITION, pos); Core::Vector3df front = listener_orientation_ * Core::Vector3df(0.0f, -1.0f, 0.0f); Core::Vector3df up = listener_orientation_ * Core::Vector3df(0.0f, 0.0f, -1.0f); ALfloat orient[] = {front.x, front.y, front.z, up.x, up.y, up.z}; alListenerfv(AL_ORIENTATION, orient); // Update channel attenuations, check which have stopped SoundChannelMap::iterator i = channels_.begin(); while (i != channels_.end()) { i->second->Update(listener_position_); if (i->second->GetState() == Foundation::SoundServiceInterface::Stopped) channels_to_delete.push_back(i); ++i; } // Remove stopped channels for (Core::uint j = 0; j < channels_to_delete.size(); ++j) channels_.erase(channels_to_delete[j]); mutex.unlock(); // Age the sound cache UpdateCache(frametime); } void SoundSystem::SetListener(const Core::Vector3df& position, const Core::Quaternion& orientation) { if (!initialized_) return; listener_position_ = position; listener_orientation_ = orientation; } Core::sound_id_t SoundSystem::PlaySound(const std::string& name, bool local, Core::sound_id_t channel) { SoundPtr sound = GetSound(name, local); if (!sound) return 0; SoundChannelMap::iterator i = channels_.find(channel); if (i == channels_.end()) { i = channels_.insert( std::pair<Core::sound_id_t, SoundChannelPtr>(GetNextSoundChannelID(), SoundChannelPtr(new SoundChannel()))).first; } i->second->SetPositional(false); i->second->Play(sound); return i->first; } Core::sound_id_t SoundSystem::PlaySound3D(const std::string& name, bool local, Core::Vector3df position, Core::sound_id_t channel) { SoundPtr sound = GetSound(name, local); if (!sound) return 0; SoundChannelMap::iterator i = channels_.find(channel); if (i == channels_.end()) { i = channels_.insert( std::pair<Core::sound_id_t, SoundChannelPtr>(GetNextSoundChannelID(), SoundChannelPtr(new SoundChannel()))).first; } i->second->SetPositional(true); i->second->SetPosition(position); i->second->Play(sound); return i->first; } Core::sound_id_t SoundSystem::PlayAudioData(Core::u8 * buffer, int buffer_size, int sample_rate, int sample_width, bool stereo, Core::sound_id_t channel) { if (!mutex.try_lock()) { int i = (int)((buffer_size*8000 / sample_rate) / sample_width); std::string s_int = boost::lexical_cast<std::string>(i); OpenALAudioModule::LogDebug("Dropped " + s_int + " ms"); return 0; } SoundPtr sound = SoundPtr(new OpenALAudio::Sound("audiobuffer")); if (!sound) return 0; bool sample_width_16bit = true; switch(sample_width) { case 8: sample_width_16bit = false; break; case 16: sample_width_16bit = true; break; default: return 0; // todo: Write log entry } sound->LoadFromBuffer(buffer, buffer_size, sample_rate, sample_width_16bit, stereo); SoundChannelMap::iterator i = channels_.find(channel); if (i == channels_.end()) { SoundChannel* s = new SoundChannel(); if (!s) return 0; i = channels_.insert(std::pair<Core::sound_id_t, SoundChannelPtr>(GetNextSoundChannelID(), SoundChannelPtr(s))).first; } if (!i->second.get()) return 0; i->second->Play(sound); Core::sound_id_t this_channel_id = i->first; mutex.unlock(); return this_channel_id; } void SoundSystem::StopSound(Core::sound_id_t id) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->Stop(); } void SoundSystem::SetPitch(Core::sound_id_t id, Core::Real pitch) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetPitch(pitch); } void SoundSystem::SetGain(Core::sound_id_t id, Core::Real gain) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetGain(gain); } void SoundSystem::SetLooped(Core::sound_id_t id, bool looped) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetLooped(looped); } void SoundSystem::SetPositional(Core::sound_id_t id, bool positional) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetPositional(positional); } void SoundSystem::SetPosition(Core::sound_id_t id, Core::Vector3df position) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetPosition(position); } void SoundSystem::SetRange(Core::sound_id_t id, Core::Real inner_radius, Core::Real outer_radius, Core::Real rolloff) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetRange(inner_radius, outer_radius, rolloff); } Core::sound_id_t SoundSystem::GetNextSoundChannelID() { for (;;) { next_channel_id_++; if (!next_channel_id_) next_channel_id_ = 1; // Must be currently unused if (channels_.find(next_channel_id_) == channels_.end()) break; } return next_channel_id_; } SoundPtr SoundSystem::GetSound(const std::string& name, bool local) { SoundMap::iterator i = sounds_.find(name); if (i != sounds_.end()) { i->second->ResetAge(); return i->second; } if (local) { // Loading of local wav sound std::string name_lower = name; boost::algorithm::to_lower(name_lower); if (name_lower.find(".wav") != std::string::npos) { SoundPtr new_sound(new Sound(name)); if (WavLoader::LoadFromFile(new_sound.get(), name)) { sounds_[name] = new_sound; return new_sound; } } // Loading of local ogg sound if (name_lower.find(".ogg") != std::string::npos) { SoundPtr new_sound(new Sound(name)); // See if the file exists. If it does, read it and post a decode request if (DecodeLocalOggFile(new_sound.get(), name)) { // Now the sound exists in cache with no data yet. We'll fill in later sounds_[name] = new_sound; return new_sound; } } } else { // Loading of sound from assetdata, assumed to be vorbis compressed stream boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock(); if (asset_service) { SoundPtr new_sound(new Sound(name)); sounds_[name] = new_sound; // The sound will be filled with data later asset_service->RequestAsset(name, RexTypes::ASSETTYPENAME_SOUNDVORBIS); return new_sound; } } return SoundPtr(); } void SoundSystem::UpdateCache(Core::f64 frametime) { update_time_ += frametime; if (update_time_ < CACHE_CHECK_INTERVAL) return; Core::uint total_size = 0; SoundMap::iterator oldest_sound = sounds_.end(); Core::f64 oldest_age = 0.0; SoundMap::iterator i = sounds_.begin(); while (i != sounds_.end()) { i->second->AddAge(update_time_); total_size += i->second->GetSize(); // Don't erase zero size sounds, because they haven't been created yet and are probably waiting for assetdata if ((i->second->GetAge() >= oldest_age) && (i->second->GetSize())) { oldest_age = i->second->GetAge(); oldest_sound = i; } ++i; } if (total_size > sound_cache_size_) { if (oldest_sound != sounds_.end()) sounds_.erase(oldest_sound); } update_time_ = 0.0; } bool SoundSystem::DecodeLocalOggFile(Sound* sound, const std::string& name) { boost::filesystem::path file_path(name); std::ifstream file(file_path.native_directory_string().c_str(), std::ios::in | std::ios::binary); if (!file.is_open()) { OpenALAudioModule::LogError("Could not open file: " + name + "."); return false; } VorbisDecodeRequestPtr new_request(new VorbisDecodeRequest()); new_request->name_ = name; std::filebuf *pbuf = file.rdbuf(); size_t size = pbuf->pubseekoff(0, std::ios::end, std::ios::in); new_request->buffer_.resize(size); pbuf->pubseekpos(0, std::ios::in); pbuf->sgetn((char *)&new_request->buffer_[0], size); file.close(); framework_->GetThreadTaskManager()->AddRequest("VorbisDecoder", new_request); return true; } bool SoundSystem::HandleTaskEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id != Task::Events::REQUEST_COMPLETED) return false; VorbisDecodeResult* result = dynamic_cast<VorbisDecodeResult*>(data); if (!result || result->task_description_ != "VorbisDecoder") return false; // If we can find the sound from our cache, and the result contains data, stuff the data into the sound SoundMap::iterator i = sounds_.find(result->name_); if (i == sounds_.end()) return false; if (!result->buffer_.size()) return true; i->second->LoadFromBuffer(&result->buffer_[0], result->buffer_.size(), result->frequency_, true, result->stereo_); return true; } bool SoundSystem::HandleAssetEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id != Asset::Events::ASSET_READY) return false; Asset::Events::AssetReady *event_data = checked_static_cast<Asset::Events::AssetReady*>(data); if (event_data->asset_type_ == RexTypes::ASSETTYPENAME_SOUNDVORBIS) { if (!event_data->asset_) return false; // Find the sound from our cache SoundMap::iterator i = sounds_.find(event_data->asset_id_); if (i == sounds_.end()) return false; // If sound already has data, do not queue another decode request if (i->second->GetSize() != 0) return false; VorbisDecodeRequestPtr new_request(new VorbisDecodeRequest()); new_request->name_ = event_data->asset_id_; new_request->buffer_.resize(event_data->asset_->GetSize()); //! \todo use asset data directly instead of copying to decode request buffer memcpy(&new_request->buffer_[0], event_data->asset_->GetData(), event_data->asset_->GetSize()); framework_->GetThreadTaskManager()->AddRequest("VorbisDecoder", new_request); } return false; } } <commit_msg>take out boost mutex initialize() call (doesn't exist on posix and doesn't seem part of public interface)<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "SoundSystem.h" #include "OpenALAudioModule.h" #include "WavLoader.h" #include "VorbisDecoder.h" #include "RexTypes.h" #include "AssetServiceInterface.h" #include "AssetEvents.h" #include <boost/thread/mutex.hpp> namespace OpenALAudio { const Core::uint DEFAULT_SOUND_CACHE_SIZE = 32 * 1024 * 1024; const Core::f64 CACHE_CHECK_INTERVAL = 1.0; SoundSystem::SoundSystem(Foundation::Framework *framework) : framework_(framework), initialized_(false), context_(0), device_(0), next_channel_id_(0), sound_cache_size_(DEFAULT_SOUND_CACHE_SIZE), update_time_(0), listener_position_(0.0, 0.0, 0.0) { sound_cache_size_ = framework_->GetDefaultConfig().DeclareSetting("SoundSystem", "sound_cache_size", DEFAULT_SOUND_CACHE_SIZE); Initialize(); // Create vorbis decoder thread task and let the framework thread task manager handle it VorbisDecoder* decoder = new VorbisDecoder(); framework_->GetThreadTaskManager()->AddThreadTask(Foundation::ThreadTaskPtr(decoder)); } SoundSystem::~SoundSystem() { Uninitialize(); } void SoundSystem::Initialize() { if (initialized_) return; device_ = alcOpenDevice(NULL); if (!device_) { OpenALAudioModule::LogWarning("Could not open OpenAL sound device"); return; } context_ = alcCreateContext(device_, NULL); if (!context_) { OpenALAudioModule::LogWarning("Could not create OpenAL sound context"); return; } alcMakeContextCurrent(context_); initialized_ = true; } void SoundSystem::Uninitialize() { if (context_) { alcMakeContextCurrent(0); alcDestroyContext(context_); context_ = 0; } if (device_) { alcCloseDevice(device_); device_ = 0; } initialized_ = false; } Foundation::SoundServiceInterface::SoundState SoundSystem::GetSoundState(Core::sound_id_t id) const { SoundChannelMap::const_iterator i = channels_.find(id); if (i == channels_.end()) return Foundation::SoundServiceInterface::Stopped; return i->second->GetState(); } std::vector<Core::sound_id_t> SoundSystem::GetActiveSounds() const { std::vector<Core::sound_id_t> ret; SoundChannelMap::const_iterator i = channels_.begin(); while (i != channels_.end()) { if (i->second->GetState() != Foundation::SoundServiceInterface::Stopped) ret.push_back(i->first); ++i; } return ret; } const std::string& SoundSystem::GetSoundName(Core::sound_id_t id) const { static std::string empty; SoundChannelMap::const_iterator i = channels_.find(id); if (i == channels_.end()) return empty; return i->second->GetSoundName(); } void SoundSystem::Update(Core::f64 frametime) { mutex.lock(); std::vector<SoundChannelMap::iterator> channels_to_delete; // Update listener position/orientation to sound device ALfloat pos[] = {listener_position_.x, listener_position_.y, listener_position_.z}; alListenerfv(AL_POSITION, pos); Core::Vector3df front = listener_orientation_ * Core::Vector3df(0.0f, -1.0f, 0.0f); Core::Vector3df up = listener_orientation_ * Core::Vector3df(0.0f, 0.0f, -1.0f); ALfloat orient[] = {front.x, front.y, front.z, up.x, up.y, up.z}; alListenerfv(AL_ORIENTATION, orient); // Update channel attenuations, check which have stopped SoundChannelMap::iterator i = channels_.begin(); while (i != channels_.end()) { i->second->Update(listener_position_); if (i->second->GetState() == Foundation::SoundServiceInterface::Stopped) channels_to_delete.push_back(i); ++i; } // Remove stopped channels for (Core::uint j = 0; j < channels_to_delete.size(); ++j) channels_.erase(channels_to_delete[j]); mutex.unlock(); // Age the sound cache UpdateCache(frametime); } void SoundSystem::SetListener(const Core::Vector3df& position, const Core::Quaternion& orientation) { if (!initialized_) return; listener_position_ = position; listener_orientation_ = orientation; } Core::sound_id_t SoundSystem::PlaySound(const std::string& name, bool local, Core::sound_id_t channel) { SoundPtr sound = GetSound(name, local); if (!sound) return 0; SoundChannelMap::iterator i = channels_.find(channel); if (i == channels_.end()) { i = channels_.insert( std::pair<Core::sound_id_t, SoundChannelPtr>(GetNextSoundChannelID(), SoundChannelPtr(new SoundChannel()))).first; } i->second->SetPositional(false); i->second->Play(sound); return i->first; } Core::sound_id_t SoundSystem::PlaySound3D(const std::string& name, bool local, Core::Vector3df position, Core::sound_id_t channel) { SoundPtr sound = GetSound(name, local); if (!sound) return 0; SoundChannelMap::iterator i = channels_.find(channel); if (i == channels_.end()) { i = channels_.insert( std::pair<Core::sound_id_t, SoundChannelPtr>(GetNextSoundChannelID(), SoundChannelPtr(new SoundChannel()))).first; } i->second->SetPositional(true); i->second->SetPosition(position); i->second->Play(sound); return i->first; } Core::sound_id_t SoundSystem::PlayAudioData(Core::u8 * buffer, int buffer_size, int sample_rate, int sample_width, bool stereo, Core::sound_id_t channel) { if (!mutex.try_lock()) { int i = (int)((buffer_size*8000 / sample_rate) / sample_width); std::string s_int = boost::lexical_cast<std::string>(i); OpenALAudioModule::LogDebug("Dropped " + s_int + " ms"); return 0; } SoundPtr sound = SoundPtr(new OpenALAudio::Sound("audiobuffer")); if (!sound) return 0; bool sample_width_16bit = true; switch(sample_width) { case 8: sample_width_16bit = false; break; case 16: sample_width_16bit = true; break; default: return 0; // todo: Write log entry } sound->LoadFromBuffer(buffer, buffer_size, sample_rate, sample_width_16bit, stereo); SoundChannelMap::iterator i = channels_.find(channel); if (i == channels_.end()) { SoundChannel* s = new SoundChannel(); if (!s) return 0; i = channels_.insert(std::pair<Core::sound_id_t, SoundChannelPtr>(GetNextSoundChannelID(), SoundChannelPtr(s))).first; } if (!i->second.get()) return 0; i->second->Play(sound); Core::sound_id_t this_channel_id = i->first; mutex.unlock(); return this_channel_id; } void SoundSystem::StopSound(Core::sound_id_t id) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->Stop(); } void SoundSystem::SetPitch(Core::sound_id_t id, Core::Real pitch) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetPitch(pitch); } void SoundSystem::SetGain(Core::sound_id_t id, Core::Real gain) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetGain(gain); } void SoundSystem::SetLooped(Core::sound_id_t id, bool looped) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetLooped(looped); } void SoundSystem::SetPositional(Core::sound_id_t id, bool positional) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetPositional(positional); } void SoundSystem::SetPosition(Core::sound_id_t id, Core::Vector3df position) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetPosition(position); } void SoundSystem::SetRange(Core::sound_id_t id, Core::Real inner_radius, Core::Real outer_radius, Core::Real rolloff) { SoundChannelMap::iterator i = channels_.find(id); if (i == channels_.end()) return; i->second->SetRange(inner_radius, outer_radius, rolloff); } Core::sound_id_t SoundSystem::GetNextSoundChannelID() { for (;;) { next_channel_id_++; if (!next_channel_id_) next_channel_id_ = 1; // Must be currently unused if (channels_.find(next_channel_id_) == channels_.end()) break; } return next_channel_id_; } SoundPtr SoundSystem::GetSound(const std::string& name, bool local) { SoundMap::iterator i = sounds_.find(name); if (i != sounds_.end()) { i->second->ResetAge(); return i->second; } if (local) { // Loading of local wav sound std::string name_lower = name; boost::algorithm::to_lower(name_lower); if (name_lower.find(".wav") != std::string::npos) { SoundPtr new_sound(new Sound(name)); if (WavLoader::LoadFromFile(new_sound.get(), name)) { sounds_[name] = new_sound; return new_sound; } } // Loading of local ogg sound if (name_lower.find(".ogg") != std::string::npos) { SoundPtr new_sound(new Sound(name)); // See if the file exists. If it does, read it and post a decode request if (DecodeLocalOggFile(new_sound.get(), name)) { // Now the sound exists in cache with no data yet. We'll fill in later sounds_[name] = new_sound; return new_sound; } } } else { // Loading of sound from assetdata, assumed to be vorbis compressed stream boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock(); if (asset_service) { SoundPtr new_sound(new Sound(name)); sounds_[name] = new_sound; // The sound will be filled with data later asset_service->RequestAsset(name, RexTypes::ASSETTYPENAME_SOUNDVORBIS); return new_sound; } } return SoundPtr(); } void SoundSystem::UpdateCache(Core::f64 frametime) { update_time_ += frametime; if (update_time_ < CACHE_CHECK_INTERVAL) return; Core::uint total_size = 0; SoundMap::iterator oldest_sound = sounds_.end(); Core::f64 oldest_age = 0.0; SoundMap::iterator i = sounds_.begin(); while (i != sounds_.end()) { i->second->AddAge(update_time_); total_size += i->second->GetSize(); // Don't erase zero size sounds, because they haven't been created yet and are probably waiting for assetdata if ((i->second->GetAge() >= oldest_age) && (i->second->GetSize())) { oldest_age = i->second->GetAge(); oldest_sound = i; } ++i; } if (total_size > sound_cache_size_) { if (oldest_sound != sounds_.end()) sounds_.erase(oldest_sound); } update_time_ = 0.0; } bool SoundSystem::DecodeLocalOggFile(Sound* sound, const std::string& name) { boost::filesystem::path file_path(name); std::ifstream file(file_path.native_directory_string().c_str(), std::ios::in | std::ios::binary); if (!file.is_open()) { OpenALAudioModule::LogError("Could not open file: " + name + "."); return false; } VorbisDecodeRequestPtr new_request(new VorbisDecodeRequest()); new_request->name_ = name; std::filebuf *pbuf = file.rdbuf(); size_t size = pbuf->pubseekoff(0, std::ios::end, std::ios::in); new_request->buffer_.resize(size); pbuf->pubseekpos(0, std::ios::in); pbuf->sgetn((char *)&new_request->buffer_[0], size); file.close(); framework_->GetThreadTaskManager()->AddRequest("VorbisDecoder", new_request); return true; } bool SoundSystem::HandleTaskEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id != Task::Events::REQUEST_COMPLETED) return false; VorbisDecodeResult* result = dynamic_cast<VorbisDecodeResult*>(data); if (!result || result->task_description_ != "VorbisDecoder") return false; // If we can find the sound from our cache, and the result contains data, stuff the data into the sound SoundMap::iterator i = sounds_.find(result->name_); if (i == sounds_.end()) return false; if (!result->buffer_.size()) return true; i->second->LoadFromBuffer(&result->buffer_[0], result->buffer_.size(), result->frequency_, true, result->stereo_); return true; } bool SoundSystem::HandleAssetEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id != Asset::Events::ASSET_READY) return false; Asset::Events::AssetReady *event_data = checked_static_cast<Asset::Events::AssetReady*>(data); if (event_data->asset_type_ == RexTypes::ASSETTYPENAME_SOUNDVORBIS) { if (!event_data->asset_) return false; // Find the sound from our cache SoundMap::iterator i = sounds_.find(event_data->asset_id_); if (i == sounds_.end()) return false; // If sound already has data, do not queue another decode request if (i->second->GetSize() != 0) return false; VorbisDecodeRequestPtr new_request(new VorbisDecodeRequest()); new_request->name_ = event_data->asset_id_; new_request->buffer_.resize(event_data->asset_->GetSize()); //! \todo use asset data directly instead of copying to decode request buffer memcpy(&new_request->buffer_[0], event_data->asset_->GetData(), event_data->asset_->GetSize()); framework_->GetThreadTaskManager()->AddRequest("VorbisDecoder", new_request); } return false; } } <|endoftext|>
<commit_before>#include <QDebug> #include <memory> #include "kernel.h" #include "ilwisdata.h" #include "mastercatalog.h" #include "iooptions.h" #include "uicontextmodel.h" #include "coveragelayermodel.h" #include "coverage.h" #include "visualizationmanager.h" using namespace Ilwis; LayerManager::LayerManager(QObject *parent) : QObject(parent) { } LayerManager::LayerManager(QObject *parent, UIContextModel *context) : QObject(parent), _uicontext(context) { IlwisTypes metatype = itCOLLECTION | itCATALOGVIEW; Resource res("Global Layer", metatype); CoverageLayerModel * model = new CoverageLayerModel(_layers.size(), res,0, this); model->iconPath("layers.png"); _layers.append(model); } void LayerManager::addVisualizationModel(CoverageLayerModel *newmodel) { _layers.insert(1,newmodel); } void LayerManager::addDataSource(const QUrl &url, IlwisTypes tp, Ilwis::Geodrawer::DrawerInterface *drawer) { try{ if ( tp == itUNKNOWN) return; Resource resource = mastercatalog()->name2Resource(url.toString(),tp); if ( !resource.isValid()) return; //IIlwisObject obj(resource); auto layer = new CoverageLayerModel(_layers.size(), resource, drawer, this); if ( _layers.size() == 1) _layers.push_back(layer); else _layers.insert(1,new CoverageLayerModel(_layers.size(), resource, drawer, this)); emit layerChanged(); } catch(const ErrorObject& ){ } catch(const std::exception& ex){ kernel()->issues()->log(ex.what()); } } bool LayerManager::zoomInMode() const { return _zoomInMode; } void LayerManager::setZoomInMode(bool yesno) { _zoomInMode = yesno; } bool LayerManager::hasSelectionDrawer() const { return _hasSelectionDrawer; } void LayerManager::setHasSelectionDrawer(bool yesno) { _hasSelectionDrawer = yesno; } void LayerManager::layersView(LayersViewCommandInterface *view) { _layersView = view; } QQmlListProperty<CoverageLayerModel> LayerManager::layers() { return QQmlListProperty<CoverageLayerModel>(this, _layers); } CoverageLayerModel *LayerManager::layer(quint32 layerIndex){ if ( layerIndex < _layers.size()) return _layers[layerIndex]; return 0; } QString LayerManager::layerInfo(const Coordinate &crd, const QString& attrName) const { std::vector<QString> texts; for(CoverageLayerModel *layer : _layers){ if ( layer->object().isValid() && hasType(layer->object()->ilwisType(), itCOVERAGE)){ ICoverage cov = layer->object().as<Coverage>(); QVariant value = cov->coord2value(crd); if ( value.isValid()){ texts.push_back(value.toString()); } } } QString outtext; for(auto txt : texts){ if ( outtext.size() != 0) outtext += "; "; outtext += txt; } if ( outtext == "") outtext = "?"; return outtext; } void LayerManager::init() { } <commit_msg>passes the correct attribute to coord2value in layerinfo<commit_after>#include <QDebug> #include <memory> #include "kernel.h" #include "ilwisdata.h" #include "mastercatalog.h" #include "iooptions.h" #include "uicontextmodel.h" #include "coveragelayermodel.h" #include "coverage.h" #include "visualizationmanager.h" using namespace Ilwis; LayerManager::LayerManager(QObject *parent) : QObject(parent) { } LayerManager::LayerManager(QObject *parent, UIContextModel *context) : QObject(parent), _uicontext(context) { IlwisTypes metatype = itCOLLECTION | itCATALOGVIEW; Resource res("Global Layer", metatype); CoverageLayerModel * model = new CoverageLayerModel(_layers.size(), res,0, this); model->iconPath("layers.png"); _layers.append(model); } void LayerManager::addVisualizationModel(CoverageLayerModel *newmodel) { _layers.insert(1,newmodel); } void LayerManager::addDataSource(const QUrl &url, IlwisTypes tp, Ilwis::Geodrawer::DrawerInterface *drawer) { try{ if ( tp == itUNKNOWN) return; Resource resource = mastercatalog()->name2Resource(url.toString(),tp); if ( !resource.isValid()) return; //IIlwisObject obj(resource); auto layer = new CoverageLayerModel(_layers.size(), resource, drawer, this); if ( _layers.size() == 1) _layers.push_back(layer); else _layers.insert(1,new CoverageLayerModel(_layers.size(), resource, drawer, this)); emit layerChanged(); } catch(const ErrorObject& ){ } catch(const std::exception& ex){ kernel()->issues()->log(ex.what()); } } bool LayerManager::zoomInMode() const { return _zoomInMode; } void LayerManager::setZoomInMode(bool yesno) { _zoomInMode = yesno; } bool LayerManager::hasSelectionDrawer() const { return _hasSelectionDrawer; } void LayerManager::setHasSelectionDrawer(bool yesno) { _hasSelectionDrawer = yesno; } void LayerManager::layersView(LayersViewCommandInterface *view) { _layersView = view; } QQmlListProperty<CoverageLayerModel> LayerManager::layers() { return QQmlListProperty<CoverageLayerModel>(this, _layers); } CoverageLayerModel *LayerManager::layer(quint32 layerIndex){ if ( layerIndex < _layers.size()) return _layers[layerIndex]; return 0; } QString LayerManager::layerInfo(const Coordinate &crd, const QString& attrName) const { std::vector<QString> texts; for(CoverageLayerModel *layer : _layers){ if ( layer->object().isValid() && hasType(layer->object()->ilwisType(), itCOVERAGE)){ ICoverage cov = layer->object().as<Coverage>(); QVariant value = cov->coord2value(crd,layer->activeAttribute()); if ( value.isValid()){ texts.push_back(value.toString()); } } } QString outtext; for(auto txt : texts){ if ( outtext.size() != 0) outtext += "; "; outtext += txt; } if ( outtext == "") outtext = "?"; return outtext; } void LayerManager::init() { } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "dialogopen.h" #include "dialognew.h" #include <QDirModel> #include <QFileDialog> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), folderHistory(new QStack<QString>), folderForwardHistory(new QStack<QString>) { // Setup the UI ui->setupUi(this); // Create the partition safe instance psInstance = new PartitionSafe(); // Temporary initializeVault("/tmp/marc.vault", "/tmp/marc.keystore"); // Show path in status bar this->setPath(); } MainWindow::~MainWindow() { delete ui; delete folderHistory; delete folderForwardHistory; delete model; delete modelDirs; } void MainWindow::on_treeViewExplorer_doubleClicked(const QModelIndex &index) { // We should get the selected item Entry* item = model->getFile(index); // Only continue if it's a directory if(!item->isDirectory()) return; // Get the path QString path = QString(item->getFullPath().c_str()); // Add history to stack folderHistory->append(model->getCurrentDirectory()); // Set directory model->setCurrentDirectory(path); // clear forward if it doesn't contain dir // else pop from ForwardHistory if (!folderForwardHistory->contains(path)) folderForwardHistory->clear(); else folderForwardHistory->pop(); // Show path in status bar this->setPath(); } void MainWindow::on_treeViewFiles_clicked(const QModelIndex &index) { // this->on_treeViewExplorer_doubleClicked(index); } void MainWindow::on_buttonBack_clicked() { // More than only the home item if(folderHistory->size() > 0) { // Get the first item of the stack QString dir = folderHistory->pop(); // Add to folderForwardHistory folderForwardHistory->append(model->getCurrentDirectory()); // Set directory model->setCurrentDirectory(dir); } // Show path in status bar this->setPath(); } void MainWindow::on_buttonForward_clicked() { // If there is a Forward if(folderForwardHistory->size() > 0) { // Get first item of the forward stack QString dir = folderForwardHistory->pop(); // Append dir to folderHistory folderHistory->append(model->getCurrentDirectory()); // Set directory model->setCurrentDirectory(dir); } // Show path in status bar this->setPath(); } void MainWindow::on_actionOpen_triggered() { DialogOpen *open = new DialogOpen(this); open->exec(); } void MainWindow::on_actionNew_triggered() { DialogNew *newDialog = new DialogNew(this); newDialog->exec(); } void MainWindow::on_buttonExport_clicked() { exportFiles(); } void MainWindow::on_buttonImport_clicked() { importFiles(); } void MainWindow::on_actionFolder_triggered() { importFolder(); } void MainWindow::on_actionFile_triggered() { importFiles(); } void MainWindow::on_actionExport_triggered() { exportFiles(); } void MainWindow::importFiles() { QFileDialog qFile; // Allow selecting of multiple files qFile.setFileMode(QFileDialog::Directory); // Open File dialog qFile.exec(); qDebug() << qFile.directory().entryList(); foreach (QString filePath, qFile.selectedFiles()) { qDebug() << filePath; // TODO: import file from filePath } } void MainWindow::importFolder(){ qDebug() << "importFolder() called"; } void MainWindow::exportFiles() { QModelIndexList selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows(); foreach (QModelIndex index, selectedRowsList) { // qDebug() << modelDirs->filePath(index); // TODO: Export selected file. } } void MainWindow::initializeVault(const QString vaultPath, const QString keyStorePath) { // Convert names const char *cVaultPath = vaultPath.toStdString().c_str(); const char *cKeyStorePath = keyStorePath.toStdString().c_str(); // Setup vault psInstance->init(cVaultPath, cKeyStorePath); psInstance->open(); // Create file system models model = new PSFileSystemModel(this, psInstance); modelDirs = new PSFileSystemModel(this, psInstance); // Set models in views ui->treeViewExplorer->setModel(model); ui->treeViewFiles->setModel(modelDirs); } void MainWindow::setPath() { // Show message ui->statusBar->showMessage(model->getCurrentDirectory()); // At last item? Disable back button. ui->buttonBack->setEnabled(folderHistory->size() > 0); // At last forward item? Disable forward button. ui->buttonForward->setEnabled(folderForwardHistory->size() > 0); } <commit_msg>changed file paths to latin1<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "dialogopen.h" #include "dialognew.h" #include <QDirModel> #include <QFileDialog> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), folderHistory(new QStack<QString>), folderForwardHistory(new QStack<QString>) { // Setup the UI ui->setupUi(this); // Create the partition safe instance psInstance = new PartitionSafe(); // Temporary initializeVault("/tmp/marc.vault", "/tmp/marc.keystore"); // Show path in status bar this->setPath(); } MainWindow::~MainWindow() { delete ui; delete folderHistory; delete folderForwardHistory; delete model; delete modelDirs; } void MainWindow::on_treeViewExplorer_doubleClicked(const QModelIndex &index) { // We should get the selected item Entry* item = model->getFile(index); // Only continue if it's a directory if(!item->isDirectory()) return; // Get the path QString path = QString(item->getFullPath().c_str()); // Add history to stack folderHistory->append(model->getCurrentDirectory()); // Set directory model->setCurrentDirectory(path); // clear forward if it doesn't contain dir // else pop from ForwardHistory if (!folderForwardHistory->contains(path)) folderForwardHistory->clear(); else folderForwardHistory->pop(); // Show path in status bar this->setPath(); } void MainWindow::on_treeViewFiles_clicked(const QModelIndex &index) { // this->on_treeViewExplorer_doubleClicked(index); } void MainWindow::on_buttonBack_clicked() { // More than only the home item if(folderHistory->size() > 0) { // Get the first item of the stack QString dir = folderHistory->pop(); // Add to folderForwardHistory folderForwardHistory->append(model->getCurrentDirectory()); // Set directory model->setCurrentDirectory(dir); } // Show path in status bar this->setPath(); } void MainWindow::on_buttonForward_clicked() { // If there is a Forward if(folderForwardHistory->size() > 0) { // Get first item of the forward stack QString dir = folderForwardHistory->pop(); // Append dir to folderHistory folderHistory->append(model->getCurrentDirectory()); // Set directory model->setCurrentDirectory(dir); } // Show path in status bar this->setPath(); } void MainWindow::on_actionOpen_triggered() { DialogOpen *open = new DialogOpen(this); open->exec(); } void MainWindow::on_actionNew_triggered() { DialogNew *newDialog = new DialogNew(this); newDialog->exec(); } void MainWindow::on_buttonExport_clicked() { exportFiles(); } void MainWindow::on_buttonImport_clicked() { importFiles(); } void MainWindow::on_actionFolder_triggered() { importFolder(); } void MainWindow::on_actionFile_triggered() { importFiles(); } void MainWindow::on_actionExport_triggered() { exportFiles(); } void MainWindow::importFiles() { QFileDialog qFile; // Allow selecting of multiple files qFile.setFileMode(QFileDialog::Directory); // Open File dialog qFile.exec(); qDebug() << qFile.directory().entryList(); foreach (QString filePath, qFile.selectedFiles()) { qDebug() << filePath; // TODO: import file from filePath } } void MainWindow::importFolder(){ qDebug() << "importFolder() called"; } void MainWindow::exportFiles() { QModelIndexList selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows(); foreach (QModelIndex index, selectedRowsList) { // qDebug() << modelDirs->filePath(index); // TODO: Export selected file. } } void MainWindow::initializeVault(const QString vaultPath, const QString keyStorePath) { // Convert names const char *cVaultPath = vaultPath.toLatin1().data(); const char *cKeyStorePath = keyStorePath.toLatin1().data(); // Setup vault psInstance->init(cVaultPath, cKeyStorePath); psInstance->open(); // Create file system models model = new PSFileSystemModel(this, psInstance); modelDirs = new PSFileSystemModel(this, psInstance); // Set models in views ui->treeViewExplorer->setModel(model); ui->treeViewFiles->setModel(modelDirs); } void MainWindow::setPath() { // Show message ui->statusBar->showMessage(model->getCurrentDirectory()); // At last item? Disable back button. ui->buttonBack->setEnabled(folderHistory->size() > 0); // At last forward item? Disable forward button. ui->buttonForward->setEnabled(folderForwardHistory->size() > 0); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TestSenderAndReceiver.h" #include <decaf/lang/Thread.h> #include <decaf/util/Random.h> #include <bitset> #include <stdio.h> using namespace std; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace cmstemplate; //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::onMessage(const string& message) { int index = (int) message.find(";"); if (index <= 0) { // i for invalid message printf("%c", 105); } else { // Smiley face for good message printf("%c", 2); } } //////////////////////////////////////////////////////////////////////////////// TestSenderAndReceiver::TestSenderAndReceiver(const string& url, const string& queueOrTopicName, bool isTopic, bool isDeliveryPersistent, int timeToLive, int receiveTimeout) : sender(), receiver(), senderThread(), closing(false), sendIndex(0), receiveIndex(0) { sender.reset(new Sender(url, queueOrTopicName, isTopic, isDeliveryPersistent, timeToLive)); receiver.reset(new Receiver(url, queueOrTopicName, isTopic, receiveTimeout, true)); ErrorCode errorCode = CMS_SUCCESS; receiver->registerMessageListener(this, errorCode); } //////////////////////////////////////////////////////////////////////////////// TestSenderAndReceiver::~TestSenderAndReceiver() { try { close(); } catch(...) {} } //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::initialize() { senderThread.reset(new Thread(this, "TestSenderAndReceiver")); senderThread->start(); } //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::run() { ErrorCode errorReturn; Random random; int i, j; j = (int) ((random.nextInt() * 50) / RAND_MAX); while (!closing) { std::stringstream str; str << sendIndex; string message; str >> message; message.append(";"); // Add variable payload j = (int) ((rand() * 1024) / RAND_MAX); for (i = 0; i < j; i++) { message += string(1, (char) (65 + ((rand() * 26) / RAND_MAX))); } errorReturn = CMS_SUCCESS; sender->SendMessage(message, errorReturn); if (errorReturn == CMS_SUCCESS) { sendIndex++; } else { // Exclamation point for error printf("%c", 33); } // Sleep for up to 1 second between sends Thread::sleep(((random.nextInt() * 1000) / RAND_MAX)); } } //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::close() { if (!closing) { closing = true; try { if (senderThread.get() != NULL) { senderThread->join(); } } catch (Exception& ex) {} try { if (receiver.get() != NULL) { receiver->close(); } } catch (Exception& ex) {} } } <commit_msg>Use the Random class properly to get consistent behavior cross platform. <commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TestSenderAndReceiver.h" #include <decaf/lang/Thread.h> #include <decaf/util/Random.h> #include <bitset> #include <stdio.h> using namespace std; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace cmstemplate; //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::onMessage(const string& message) { int index = (int) message.find(";"); if (index <= 0) { // i for invalid message printf("%c", 105); } else { // Smiley face for good message printf("%c", 2); } } //////////////////////////////////////////////////////////////////////////////// TestSenderAndReceiver::TestSenderAndReceiver(const string& url, const string& queueOrTopicName, bool isTopic, bool isDeliveryPersistent, int timeToLive, int receiveTimeout) : sender(), receiver(), senderThread(), closing(false), sendIndex(0), receiveIndex(0) { sender.reset(new Sender(url, queueOrTopicName, isTopic, isDeliveryPersistent, timeToLive)); receiver.reset(new Receiver(url, queueOrTopicName, isTopic, receiveTimeout, true)); ErrorCode errorCode = CMS_SUCCESS; receiver->registerMessageListener(this, errorCode); } //////////////////////////////////////////////////////////////////////////////// TestSenderAndReceiver::~TestSenderAndReceiver() { try { close(); } catch(...) {} } //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::initialize() { senderThread.reset(new Thread(this, "TestSenderAndReceiver")); senderThread->start(); } //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::run() { ErrorCode errorReturn; Random random; int i, j; j = random.nextInt(100); while (!closing) { std::stringstream str; str << sendIndex; string message; str >> message; message.append(";"); // Add variable payload j = (int) ((rand() * 1024) / RAND_MAX); for (i = 0; i < j; i++) { message += string(1, (char) (65 + ((rand() * 26) / RAND_MAX))); } errorReturn = CMS_SUCCESS; sender->SendMessage(message, errorReturn); if (errorReturn == CMS_SUCCESS) { sendIndex++; } else { // Exclamation point for error printf("%c", 33); } // Sleep for up to 1 second between sends Thread::sleep(random.nextInt(500)); } } //////////////////////////////////////////////////////////////////////////////// void TestSenderAndReceiver::close() { if (!closing) { closing = true; try { if (senderThread.get() != NULL) { senderThread->join(); } } catch (Exception& ex) {} try { if (receiver.get() != NULL) { receiver->close(); } } catch (Exception& ex) {} } } <|endoftext|>
<commit_before>/* Copyright 2015 Brain Research Institute, Melbourne, Australia Written by Rami Tabbara, 18/02/15. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "gui/mrview/mode/lightbox.h" namespace MR { namespace GUI { namespace MRView { namespace Mode { bool LightBox::show_grid_lines(true); size_t LightBox::n_rows(3); size_t LightBox::n_cols(4); float LightBox::slice_focus_increment(1.f); LightBox::LightBox(Window &parent) : Slice(parent), layout_is_dirty(true), current_slice_index((n_rows*n_cols) / 2), slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f)) { image_changed_event(); } void LightBox::set_rows(size_t rows) { n_rows = rows; layout_is_dirty = true; updateGL(); } void LightBox::set_cols(size_t cols) { n_cols = cols; layout_is_dirty = true; updateGL(); } void LightBox::set_slice_increment(float inc) { slice_focus_increment = inc; update_slices_focusdelta(); updateGL(); } void LightBox::set_show_grid(bool show_grid) { show_grid_lines = show_grid; updateGL(); } inline void LightBox::update_layout() { // Can't use std::vector resize() because Projection needs to be assignable slices_proj_focusdelta = std::vector<proj_focusdelta>( n_cols * n_rows, proj_focusdelta(projection, 0.f)); set_current_slice_index((n_rows * n_cols) / 2); update_slices_focusdelta(); frame_VB.clear(); frame_VAO.clear(); } void LightBox::set_current_slice_index(size_t slice_index) { size_t prev_index = current_slice_index; current_slice_index = slice_index; if(prev_index != current_slice_index) { const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first; float focus_delta = slices_proj_focusdelta[current_slice_index].second; const Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj); set_focus(focus() + slice_focus); update_slices_focusdelta(); } } void LightBox::update_slices_focusdelta() { const int current_slice_index_int = current_slice_index; for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) { slices_proj_focusdelta[i].second = slice_focus_increment * (i - current_slice_index_int); } } void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection) { image()->render3D (shader_program, with_projection, with_projection.depth_of (focus())); render_tools (with_projection, false, axis, slice (axis)); } void LightBox::paint(Projection&) { // Setup OpenGL environment: gl::Disable (gl::BLEND); gl::Disable (gl::DEPTH_TEST); gl::DepthMask (gl::FALSE_); gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_); GLint x = projection.x_position(), y = projection.y_position(); GLint w = projection.width(), h = projection.height(); GLint dw = w / n_cols, dh = h / n_rows; const Point<> orig_focus = window.focus(); if(layout_is_dirty) { update_layout(); layout_is_dirty = false; } size_t slice_idx = 0; for(size_t row = 0; row < n_rows; ++row) { for(size_t col = 0; col < n_cols; ++col, ++slice_idx) { Projection& slice_proj = slices_proj_focusdelta[slice_idx].first; // Place the first slice in the top-left corner slice_proj.set_viewport(window, x + dw * col, y + h - (dh * (row+1)), dw, dh); // We need to setup the modelview/proj matrices before we set the new focus // because move_in_out_displacement is reliant on MVP setup_draw(plane(), slice_proj); float focus_delta = slices_proj_focusdelta[slice_idx].second; Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj); set_focus(orig_focus + slice_focus); draw_plane_primitive(plane(), slice_shader, slice_proj); if(slice_idx == current_slice_index) { // Drawing plane may alter the depth test state // so need to ensure that crosshairs/labels will be visible gl::Disable (gl::DEPTH_TEST); draw_crosshairs(slice_proj); draw_orientation_labels(slice_proj); } } } // Restore view state set_focus(orig_focus); projection.set_viewport(window, x, y, w, h); // Users may want to screen capture without grid lines if(show_grid_lines) { gl::Disable(gl::DEPTH_TEST); draw_grid(); } } void LightBox::draw_grid() { if(n_cols < 1 && n_rows < 1) return; size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4; GL::mat4 MV = GL::identity(); GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0); projection.set (MV, P); gl::LineWidth (2.0); if (!frame_VB || !frame_VAO) { frame_VB.gen(); frame_VAO.gen(); frame_VB.bind (gl::ARRAY_BUFFER); frame_VAO.bind(); gl::EnableVertexAttribArray (0); gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0); GLfloat data[num_points]; // Grid line stride float x_inc = 2.f / n_cols; float y_inc = 2.f / n_rows; size_t pt_idx = 0; // Row grid lines for(size_t row = 1; row < n_rows; ++row, pt_idx += 4) { float y_pos = (y_inc * row) - 1.f; data[pt_idx] = -1.f; data[pt_idx+1] = y_pos; data[pt_idx+2] = 1.f; data[pt_idx+3] = y_pos; } // Column grid lines for(size_t col = 1; col < n_cols; ++col, pt_idx += 4) { float x_pos = (x_inc * col) - 1.f; data[pt_idx] = x_pos; data[pt_idx+1] = -1.f; data[pt_idx+2] = x_pos; data[pt_idx+3] = 1.f; } gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW); } else frame_VAO.bind(); if (!frame_program) { GL::Shader::Vertex vertex_shader ( "layout(location=0) in vec2 pos;\n" "void main () {\n" " gl_Position = vec4 (pos, 0.0, 1.0);\n" "}\n"); GL::Shader::Fragment fragment_shader ( "out vec3 color;\n" "void main () {\n" " color = vec3 (0.1);\n" "}\n"); frame_program.attach (vertex_shader); frame_program.attach (fragment_shader); frame_program.link(); } frame_program.start(); gl::DrawArrays (gl::LINES, 0, num_points / 2); frame_program.stop(); } void LightBox::mouse_press_event() { GLint x = projection.x_position(), y = projection.y_position(); GLint w = projection.width(), h = projection.height(); GLint dw = w / n_cols, dh = h / n_rows; const auto& mouse_pos = window.mouse_position(); size_t col = (mouse_pos.x() - x) / dw; size_t row = n_rows - (mouse_pos.y() - y) / dh - 1; if(col < n_cols && row < n_rows) { set_current_slice_index(slice_index(row, col)); } } // Called when we get a mouse move event void LightBox::set_focus_event() { Base::set_focus_event(); mouse_press_event(); } void LightBox::image_changed_event() { Base::image_changed_event(); if(image()) { const auto& header = image()->header(); float slice_inc = std::pow (header.vox(0)*header.vox(1)*header.vox(2), 1.f/3.f); set_slice_increment(slice_inc); emit slice_increment_reset(); } } } } } } <commit_msg>LightBox: Changing default grid dimensions to 3 x 5<commit_after>/* Copyright 2015 Brain Research Institute, Melbourne, Australia Written by Rami Tabbara, 18/02/15. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "gui/mrview/mode/lightbox.h" namespace MR { namespace GUI { namespace MRView { namespace Mode { bool LightBox::show_grid_lines(true); size_t LightBox::n_rows(3); size_t LightBox::n_cols(5); float LightBox::slice_focus_increment(1.f); LightBox::LightBox(Window &parent) : Slice(parent), layout_is_dirty(true), current_slice_index((n_rows*n_cols) / 2), slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f)) { image_changed_event(); } void LightBox::set_rows(size_t rows) { n_rows = rows; layout_is_dirty = true; updateGL(); } void LightBox::set_cols(size_t cols) { n_cols = cols; layout_is_dirty = true; updateGL(); } void LightBox::set_slice_increment(float inc) { slice_focus_increment = inc; update_slices_focusdelta(); updateGL(); } void LightBox::set_show_grid(bool show_grid) { show_grid_lines = show_grid; updateGL(); } inline void LightBox::update_layout() { // Can't use std::vector resize() because Projection needs to be assignable slices_proj_focusdelta = std::vector<proj_focusdelta>( n_cols * n_rows, proj_focusdelta(projection, 0.f)); set_current_slice_index((n_rows * n_cols) / 2); update_slices_focusdelta(); frame_VB.clear(); frame_VAO.clear(); } void LightBox::set_current_slice_index(size_t slice_index) { size_t prev_index = current_slice_index; current_slice_index = slice_index; if(prev_index != current_slice_index) { const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first; float focus_delta = slices_proj_focusdelta[current_slice_index].second; const Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj); set_focus(focus() + slice_focus); update_slices_focusdelta(); } } void LightBox::update_slices_focusdelta() { const int current_slice_index_int = current_slice_index; for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) { slices_proj_focusdelta[i].second = slice_focus_increment * (i - current_slice_index_int); } } void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection) { image()->render3D (shader_program, with_projection, with_projection.depth_of (focus())); render_tools (with_projection, false, axis, slice (axis)); } void LightBox::paint(Projection&) { // Setup OpenGL environment: gl::Disable (gl::BLEND); gl::Disable (gl::DEPTH_TEST); gl::DepthMask (gl::FALSE_); gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_); GLint x = projection.x_position(), y = projection.y_position(); GLint w = projection.width(), h = projection.height(); GLint dw = w / n_cols, dh = h / n_rows; const Point<> orig_focus = window.focus(); if(layout_is_dirty) { update_layout(); layout_is_dirty = false; } size_t slice_idx = 0; for(size_t row = 0; row < n_rows; ++row) { for(size_t col = 0; col < n_cols; ++col, ++slice_idx) { Projection& slice_proj = slices_proj_focusdelta[slice_idx].first; // Place the first slice in the top-left corner slice_proj.set_viewport(window, x + dw * col, y + h - (dh * (row+1)), dw, dh); // We need to setup the modelview/proj matrices before we set the new focus // because move_in_out_displacement is reliant on MVP setup_draw(plane(), slice_proj); float focus_delta = slices_proj_focusdelta[slice_idx].second; Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj); set_focus(orig_focus + slice_focus); draw_plane_primitive(plane(), slice_shader, slice_proj); if(slice_idx == current_slice_index) { // Drawing plane may alter the depth test state // so need to ensure that crosshairs/labels will be visible gl::Disable (gl::DEPTH_TEST); draw_crosshairs(slice_proj); draw_orientation_labels(slice_proj); } } } // Restore view state set_focus(orig_focus); projection.set_viewport(window, x, y, w, h); // Users may want to screen capture without grid lines if(show_grid_lines) { gl::Disable(gl::DEPTH_TEST); draw_grid(); } } void LightBox::draw_grid() { if(n_cols < 1 && n_rows < 1) return; size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4; GL::mat4 MV = GL::identity(); GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0); projection.set (MV, P); gl::LineWidth (2.0); if (!frame_VB || !frame_VAO) { frame_VB.gen(); frame_VAO.gen(); frame_VB.bind (gl::ARRAY_BUFFER); frame_VAO.bind(); gl::EnableVertexAttribArray (0); gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0); GLfloat data[num_points]; // Grid line stride float x_inc = 2.f / n_cols; float y_inc = 2.f / n_rows; size_t pt_idx = 0; // Row grid lines for(size_t row = 1; row < n_rows; ++row, pt_idx += 4) { float y_pos = (y_inc * row) - 1.f; data[pt_idx] = -1.f; data[pt_idx+1] = y_pos; data[pt_idx+2] = 1.f; data[pt_idx+3] = y_pos; } // Column grid lines for(size_t col = 1; col < n_cols; ++col, pt_idx += 4) { float x_pos = (x_inc * col) - 1.f; data[pt_idx] = x_pos; data[pt_idx+1] = -1.f; data[pt_idx+2] = x_pos; data[pt_idx+3] = 1.f; } gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW); } else frame_VAO.bind(); if (!frame_program) { GL::Shader::Vertex vertex_shader ( "layout(location=0) in vec2 pos;\n" "void main () {\n" " gl_Position = vec4 (pos, 0.0, 1.0);\n" "}\n"); GL::Shader::Fragment fragment_shader ( "out vec3 color;\n" "void main () {\n" " color = vec3 (0.1);\n" "}\n"); frame_program.attach (vertex_shader); frame_program.attach (fragment_shader); frame_program.link(); } frame_program.start(); gl::DrawArrays (gl::LINES, 0, num_points / 2); frame_program.stop(); } void LightBox::mouse_press_event() { GLint x = projection.x_position(), y = projection.y_position(); GLint w = projection.width(), h = projection.height(); GLint dw = w / n_cols, dh = h / n_rows; const auto& mouse_pos = window.mouse_position(); size_t col = (mouse_pos.x() - x) / dw; size_t row = n_rows - (mouse_pos.y() - y) / dh - 1; if(col < n_cols && row < n_rows) { set_current_slice_index(slice_index(row, col)); } } // Called when we get a mouse move event void LightBox::set_focus_event() { Base::set_focus_event(); mouse_press_event(); } void LightBox::image_changed_event() { Base::image_changed_event(); if(image()) { const auto& header = image()->header(); float slice_inc = std::pow (header.vox(0)*header.vox(1)*header.vox(2), 1.f/3.f); set_slice_increment(slice_inc); emit slice_increment_reset(); } } } } } } <|endoftext|>
<commit_before>//shit to do //Do checks to make sure it doesn't crash (make sure creators exists, that the resource creation didn't fail) //Make AddType Template in the .inl file//And creators isn't attached to anything. You're supposed to be initialising the static creators in ResourceFactory. //And finally, you don't need to put static in definitions //////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef RESOURCE_FACTORY_HPP #define RESOURCE_FACTORY_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <ResourceMananger/BaseResource.hpp> #include <ResourceManager/ResourceCreator.hpp> #include <ResourceManager/ResourceManager.hpp> #include <map> //////////////////////////////////////////////////////////// /// \breif Resource Factory that serves as the creation location /// for all resources /// //////////////////////////////////////////////////////////// namespace rm { class ResourceFactory { public: //////////////////////////////////////////////////////////// /// \brief Looks up the ResouceCreatorInterface needed to create /// The resource based on the type and calls create on it to make a /// A new resource of the specified type /// /// \parma string to path location of the file and string for file /// Type to determine how it is loaded /// /// \return Shared Pointer of the newly Created Resouce /// //////////////////////////////////////////////////////////// static std::shared_ptr<BaseResource> createResource(const std::string& path, const std::string& type); //////////////////////////////////////////////////////////// /// \brief Creates a new ResouceCreatorInterface based on the passed /// resource type. Gets the type name from the resourceType class and stores /// The created resourceCreatorInterface is stored in creators /// //////////////////////////////////////////////////////////// template <class T> static void addType(); private: //////////////////////////////////////////////////////////// /// \brief A Strandard Map to hold all the resource type /// classes that define how they are created /// /// Example: It could hold a image ResourceCreatorInterface /// that will define how to create an image /// //////////////////////////////////////////////////////////// std::map<std::string, std::shared_ptr<ResourceCreatorInterface>> creators; }; } #endif //RESOURCE_FACTORY_HPP<commit_msg>Fixed some Resource Factory typos<commit_after>//shit to do //Do checks to make sure it doesn't crash (make sure creators exists, that the resource creation didn't fail) //Make AddType Template in the .inl file//And creators isn't attached to anything. You're supposed to be initialising the static creators in ResourceFactory. //And finally, you don't need to put static in definitions //////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2014 stevehalliwell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef RESOURCE_FACTORY_HPP #define RESOURCE_FACTORY_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <ResourceManager/BaseResource.hpp> #include <ResourceManager/ResourceCreator.hpp> #include <ResourceManager/ResourceManager.hpp> #include <map> //////////////////////////////////////////////////////////// /// \breif Resource Factory that serves as the creation location /// for all resources /// //////////////////////////////////////////////////////////// namespace rm { class ResourceFactory { public: //////////////////////////////////////////////////////////// /// \brief Looks up the ResouceCreatorInterface needed to create /// The resource based on the type and calls create on it to make a /// A new resource of the specified type /// /// \parma string to path location of the file and string for file /// Type to determine how it is loaded /// /// \return Shared Pointer of the newly Created Resource /// //////////////////////////////////////////////////////////// static std::shared_ptr<BaseResource> createResource(const std::string& path, const std::string& type); //////////////////////////////////////////////////////////// /// \brief Creates a new ResouceCreatorInterface based on the passed /// resource type. Gets the type name from the resourceType class and stores /// The created resourceCreatorInterface is stored in creators /// //////////////////////////////////////////////////////////// template <class T> static void addType(); private: //////////////////////////////////////////////////////////// /// \brief A Standard Map to hold all the resource type /// classes that define how they are created /// /// Example: It could hold a image ResourceCreatorInterface /// that will define how to create an image /// //////////////////////////////////////////////////////////// std::map<std::string, std::shared_ptr<ResourceCreatorInterface>> creators; }; } #endif //RESOURCE_FACTORY_HPP<|endoftext|>
<commit_before>#ifndef AUTOCHECK_GENERATOR_COMBINATORS_HPP #define AUTOCHECK_GENERATOR_COMBINATORS_HPP #include <type_traits> #include <limits> namespace autocheck { namespace detail { /* Wrappers used by combinators. */ template <typename Func, typename Gen> class mapped_generator { public: typedef typename std::result_of< Func(typename Gen::result_type&&, size_t) >::type result_type; private: Func func; Gen gen; public: mapped_generator(const Func& func, const Gen& gen) : func(func), gen(gen) {} result_type operator() (size_t size = 0) { return func(gen(size), size); } }; template <typename Pred, typename Gen> class filtered_generator { public: typedef typename Gen::result_type result_type; private: Pred pred; Gen gen; public: filtered_generator(const Pred& pred, const Gen& gen) : pred(pred), gen(gen) {} result_type operator() (size_t size = 0) { while (true) { result_type rv(gen(size)); if (pred(rv)) return rv; } } }; template <typename Resize, typename Gen> class resized_generator { public: typedef typename Gen::result_type result_type; private: Resize resizer; Gen gen; public: resized_generator(const Resize& resizer, const Gen& gen) : resizer(resizer), gen(gen) {} result_type operator() (size_t size = 0) { return gen(resizer(size)); } }; template <typename Gen> class fixed_size_generator { private: size_t size; Gen gen; public: typedef typename Gen::result_type result_type; fixed_size_generator(size_t size, const Gen& gen) : size(size), gen(gen) {} result_type operator() (size_t = 0) { return gen(size); } }; } /* Generator combinators. */ template <typename Func, typename Gen> detail::mapped_generator<Func, Gen> map(const Func& func, const Gen& gen) { return detail::mapped_generator<Func, Gen>(func, gen); } template <typename Pred, typename Gen> detail::filtered_generator<Pred, Gen> such_that(const Pred& pred, const Gen& gen) { return detail::filtered_generator<Pred, Gen>(pred, gen); } template <typename Resize, typename Gen> detail::resized_generator<Resize, Gen> resize(const Resize& resizer, const Gen& gen) { return detail::resized_generator<Resize, Gen>(resizer, gen); } template <typename Gen> detail::fixed_size_generator<Gen> fix(size_t size, const Gen& gen) { return detail::fixed_size_generator<Gen>(size, gen); } } #endif <commit_msg>Removed superfluous header.<commit_after>#ifndef AUTOCHECK_GENERATOR_COMBINATORS_HPP #define AUTOCHECK_GENERATOR_COMBINATORS_HPP #include <type_traits> namespace autocheck { namespace detail { /* Wrappers used by combinators. */ template <typename Func, typename Gen> class mapped_generator { public: typedef typename std::result_of< Func(typename Gen::result_type&&, size_t) >::type result_type; private: Func func; Gen gen; public: mapped_generator(const Func& func, const Gen& gen) : func(func), gen(gen) {} result_type operator() (size_t size = 0) { return func(gen(size), size); } }; template <typename Pred, typename Gen> class filtered_generator { public: typedef typename Gen::result_type result_type; private: Pred pred; Gen gen; public: filtered_generator(const Pred& pred, const Gen& gen) : pred(pred), gen(gen) {} result_type operator() (size_t size = 0) { while (true) { result_type rv(gen(size)); if (pred(rv)) return rv; } } }; template <typename Resize, typename Gen> class resized_generator { public: typedef typename Gen::result_type result_type; private: Resize resizer; Gen gen; public: resized_generator(const Resize& resizer, const Gen& gen) : resizer(resizer), gen(gen) {} result_type operator() (size_t size = 0) { return gen(resizer(size)); } }; template <typename Gen> class fixed_size_generator { private: size_t size; Gen gen; public: typedef typename Gen::result_type result_type; fixed_size_generator(size_t size, const Gen& gen) : size(size), gen(gen) {} result_type operator() (size_t = 0) { return gen(size); } }; } /* Generator combinators. */ template <typename Func, typename Gen> detail::mapped_generator<Func, Gen> map(const Func& func, const Gen& gen) { return detail::mapped_generator<Func, Gen>(func, gen); } template <typename Pred, typename Gen> detail::filtered_generator<Pred, Gen> such_that(const Pred& pred, const Gen& gen) { return detail::filtered_generator<Pred, Gen>(pred, gen); } template <typename Resize, typename Gen> detail::resized_generator<Resize, Gen> resize(const Resize& resizer, const Gen& gen) { return detail::resized_generator<Resize, Gen>(resizer, gen); } template <typename Gen> detail::fixed_size_generator<Gen> fix(size_t size, const Gen& gen) { return detail::fixed_size_generator<Gen>(size, gen); } } #endif <|endoftext|>
<commit_before>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Which headers should be forwarded to/from remote HTTP servers? */ #pragma once #include "http/Status.h" #include <beng-proxy/Headers.hxx> struct HeaderForwardSettings { BengProxy::HeaderForwardMode modes[size_t(BengProxy::HeaderGroup::MAX)]; HeaderForwardSettings() = default; static constexpr HeaderForwardSettings AllNo() noexcept { static_assert(BengProxy::HeaderForwardMode::NO == BengProxy::HeaderForwardMode(), "Wrong default value"); return HeaderForwardSettings{BengProxy::HeaderForwardMode::NO}; } constexpr auto &operator[](BengProxy::HeaderGroup group) noexcept { return modes[size_t(group)]; } constexpr const auto &operator[](BengProxy::HeaderGroup group) const noexcept { return modes[size_t(group)]; } }; struct pool; class StringMap; struct RealmSession; /** * @param exclude_host suppress the "Host" header? The "Host" request * header must not be forwarded to another HTTP server, because we * need to generate a new one * @param forward_range forward the "Range" request header? */ StringMap forward_request_headers(struct pool &pool, const StringMap &src, const char *local_host, const char *remote_host, bool exclude_host, bool with_body, bool forward_charset, bool forward_encoding, bool forward_range, const HeaderForwardSettings &settings, const char *session_cookie, const RealmSession *session, const char *host_and_port, const char *uri) noexcept; StringMap forward_response_headers(struct pool &pool, http_status_t status, const StringMap &src, const char *local_host, const char *session_cookie, const char *(*relocate)(const char *uri, void *ctx), void *relocate_ctx, const HeaderForwardSettings &settings) noexcept; /** * Generate a X-CM4all-BENG-User header (if available)_. */ void forward_reveal_user(StringMap &headers, const RealmSession *session) noexcept; <commit_msg>bp/ForwardHeaders: add `using` declarations<commit_after>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Which headers should be forwarded to/from remote HTTP servers? */ #pragma once #include "http/Status.h" #include <beng-proxy/Headers.hxx> struct HeaderForwardSettings { using Group = BengProxy::HeaderGroup; using Mode = BengProxy::HeaderForwardMode; Mode modes[size_t(Group::MAX)]; HeaderForwardSettings() = default; static constexpr HeaderForwardSettings AllNo() noexcept { static_assert(Mode::NO == Mode(), "Wrong default value"); return HeaderForwardSettings{Mode::NO}; } constexpr auto &operator[](Group group) noexcept { return modes[size_t(group)]; } constexpr const auto &operator[](Group group) const noexcept { return modes[size_t(group)]; } }; struct pool; class StringMap; struct RealmSession; /** * @param exclude_host suppress the "Host" header? The "Host" request * header must not be forwarded to another HTTP server, because we * need to generate a new one * @param forward_range forward the "Range" request header? */ StringMap forward_request_headers(struct pool &pool, const StringMap &src, const char *local_host, const char *remote_host, bool exclude_host, bool with_body, bool forward_charset, bool forward_encoding, bool forward_range, const HeaderForwardSettings &settings, const char *session_cookie, const RealmSession *session, const char *host_and_port, const char *uri) noexcept; StringMap forward_response_headers(struct pool &pool, http_status_t status, const StringMap &src, const char *local_host, const char *session_cookie, const char *(*relocate)(const char *uri, void *ctx), void *relocate_ctx, const HeaderForwardSettings &settings) noexcept; /** * Generate a X-CM4all-BENG-User header (if available)_. */ void forward_reveal_user(StringMap &headers, const RealmSession *session) noexcept; <|endoftext|>
<commit_before><commit_msg>proper -l flag formatting. currently trying to repair -laR flag<commit_after><|endoftext|>
<commit_before>#include "TGLViewer.h" namespace Alieve { class MUONData; class Event; } Alieve::MUONData* g_muon_data = 0; Alieve::Event* g_muon_last_event = 0; Int_t g_currentEvent = -1; Bool_t g_fromRaw = kFALSE; void MUON_digits(Bool_t fromRaw = kFALSE, Bool_t showTracks = kTRUE) { TTree* dt = 0; if (Alieve::gEvent == 0) { printf("No alieve event: use alieve_init(...) \n"); return; } if (g_currentEvent == Alieve::gEvent->GetEventId()) { if (g_fromRaw == fromRaw) { printf("Same event... \n"); return; } else { if (g_fromRaw) { printf("Same event with digits.\n"); Alieve::gEvent->GotoEvent(g_currentEvent); } else { printf("Same event with raw.\n"); Alieve::gEvent->GotoEvent(g_currentEvent); } } } g_fromRaw = fromRaw; AliRunLoader* rl = Alieve::Event::AssertRunLoader(); TString fileName = rl->GetFileName(); Int_t length = fileName.Length(); fileName.Resize(length-11); fileName.Append("raw.root"); g_muon_data = new Alieve::MUONData; if (!fromRaw) { rl->LoadDigits("MUON"); dt = rl->GetTreeD("MUON", false); if (dt == 0) { cout << "No digits produced!" << endl; } else { cout << "Display aliroot digits!" << endl; g_muon_data->LoadDigits(dt); } } else { if (gSystem->AccessPathName(fileName.Data(),kFileExists)) { cout << "No raw data produced!" << endl; } else { cout << "Display raw digits!" << endl; g_muon_data->LoadRaw(fileName.Data()); } } g_muon_last_event = Alieve::gEvent; g_currentEvent = g_muon_last_event->GetEventId(); gStyle->SetPalette(1, 0); gReve->DisableRedraw(); Reve::RenderElementList* l = new Reve::RenderElementList("MUONChambers"); l->SetTitle("MUON chambers"); l->SetMainColor(Color_t(2)); gReve->AddRenderElement(l); for (Int_t ic = 0; ic < 14; ic++) { Alieve::MUONChamber* mucha = new Alieve::MUONChamber(); mucha->SetFrameColor(2); mucha->SetChamberID(ic); mucha->SetDataSource(g_muon_data); gReve->AddRenderElement(l,mucha); } if (showTracks) MUON_tracks(); gReve->EnableRedraw(); TGLViewer* view = dynamic_cast<TGLViewer*>(gReve->GetGLCanvas()->GetViewer3D()); view->ResetCamerasAfterNextUpdate(); gReve->GetGLCanvas()->Modified(); gReve->GetGLCanvas()->Update(); } //_____________________________________________________________________________ void MUON_tracks() { AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadTracks("MUON"); TTree* tt = rl->GetTreeT("MUON", false); TClonesArray *tracks = 0; tt->SetBranchAddress("MUONTrack",&tracks); tt->GetEntry(0); Int_t ntracks = tracks->GetEntriesFast(); //printf("Found %d tracks. \n",ntracks); Reve::TrackList* lt = new Reve::TrackList("M-Tracks"); lt->SetMainColor(Color_t(6)); gReve->AddRenderElement(lt); TMatrixD smatrix(2,2); TMatrixD sums(2,1); TMatrixD res(2,1); Float_t xRec, xRec0; Float_t yRec, yRec0; Float_t zRec, zRec0; Float_t zg[4] = { -1603.5, -1620.5, -1703.5, -1720.5 }; AliMUONTrack *mt; Reve::RecTrack rt; Int_t count; for (Int_t n = 0; n < ntracks; n++) { count = 0; mt = (AliMUONTrack*) tracks->At(n); //printf("Match trigger %d \n",mt->GetMatchTrigger()); rt.label = n; Reve::Track* track = new Reve::Track(&rt, lt->GetRnrStyle()); //PH The line below is replaced waiting for a fix in Root //PH which permits to use variable siza arguments in CINT //PH on some platforms (alphalinuxgcc, solariscc5, etc.) char form[1000]; if (mt->GetMatchTrigger()) { //PH track->SetName(Form("MUONTrack %2d (MT)", rt.label)); sprintf(form,"MUONTrack %2d (MT)", rt.label); track->SetName(form); track->SetLineColor(7); } else { //PH track->SetName(Form("MUONTrack %2d ", rt.label)); sprintf(form,"MUONTrack %2d ", rt.label); track->SetName(form); track->SetLineColor(6); } AliMUONTrackParam *trackParam = mt->GetTrackParamAtVertex(); xRec0 = trackParam->GetNonBendingCoor(); yRec0 = trackParam->GetBendingCoor(); zRec0 = trackParam->GetZ(); track->SetPoint(count,xRec0,yRec0,zRec0); count++; Float_t xr[20], yr[20], zr[20]; for (Int_t i = 0; i < 10; i++) xr[i]=yr[i]=zr[i]=0.0; Int_t nTrackHits = mt->GetNTrackHits(); //printf("Nhits = %d \n",nTrackHits); TClonesArray* trackParamAtHit; for (Int_t iHit = 0; iHit < nTrackHits; iHit++){ trackParamAtHit = mt->GetTrackParamAtHit(); trackParam = (AliMUONTrackParam*) trackParamAtHit->At(iHit); xRec = trackParam->GetNonBendingCoor(); yRec = trackParam->GetBendingCoor(); zRec = trackParam->GetZ(); //printf("Hit %d x %f y %f z %f \n",iHit,xRec,yRec,zRec); xr[iHit] = xRec; yr[iHit] = yRec; zr[iHit] = zRec; track->SetPoint(count,xRec,yRec,zRec); count++; } Float_t xrc[20], yrc[20], zrc[20]; Int_t nrc = 0; if (mt->GetMatchTrigger() && 1) { for (Int_t i = 0; i < nTrackHits; i++) { if (TMath::Abs(zr[i]) > 1000.0) { //printf("Hit %d x %f y %f z %f \n",iHit,xr[i],yr[i],zr[i]); xrc[nrc] = xr[i]; yrc[nrc] = yr[i]; zrc[nrc] = zr[i]; nrc++; } } Double_t xv, yv; Float_t ax, bx, ay, by; if (nrc < 2) continue; // fit x-z smatrix.Zero(); sums.Zero(); for (Int_t i = 0; i < nrc; i++) { xv = (Double_t)zrc[i]; yv = (Double_t)xrc[i]; //printf("x-z: xv %f yv %f \n",xv,yv); smatrix(0,0) += 1.0; smatrix(1,1) += xv*xv; smatrix(0,1) += xv; smatrix(1,0) += xv; sums(0,0) += yv; sums(1,0) += xv*yv; } res = smatrix.Invert() * sums; ax = res(0,0); bx = res(1,0); // fit y-z smatrix.Zero(); sums.Zero(); for (Int_t i = 0; i < nrc; i++) { xv = (Double_t)zrc[i]; yv = (Double_t)yrc[i]; //printf("y-z: xv %f yv %f \n",xv,yv); smatrix(0,0) += 1.0; smatrix(1,1) += xv*xv; smatrix(0,1) += xv; smatrix(1,0) += xv; sums(0,0) += yv; sums(1,0) += xv*yv; } res = smatrix.Invert() * sums; ay = res(0,0); by = res(1,0); Float_t xtc, ytc, ztc; for (Int_t ii = 0; ii < 4; ii++) { ztc = zg[ii]; ytc = ay+by*zg[ii]; xtc = ax+bx*zg[ii]; //printf("tc: x %f y %f z %f \n",xtc,ytc,ztc); track->SetPoint(count,xtc,ytc,ztc); count++; } } // end match trigger gReve->AddRenderElement(lt, track); } } <commit_msg>From Bogdan: removed macro file.<commit_after><|endoftext|>
<commit_before>#ifndef GUARD_MLOPEN_OCL_KERNEL_HPP_ #define GUARD_MLOPEN_OCL_KERNEL_HPP_ #include <sstream> #include <array> #include <utility> #include <vector> #include <mlopen.h> #include <cassert> #include <functional> #include <array> #include <memory> #include <algorithm> #include <mlopen/errors.hpp> #include <mlopen/each_args.hpp> #include <mlopen/clhelper.hpp> namespace mlopen { using SharedKernelPtr = std::shared_ptr<typename std::remove_pointer<cl_kernel>::type>; using SharedProgramPtr = std::shared_ptr<typename std::remove_pointer<cl_program>::type>; struct LocalMemArg { LocalMemArg(size_t _size) : size(_size) {} size_t GetSize() const { return size; } private: size_t size; }; struct OCLSetKernelArg { template<class I, class T> void operator()(cl_kernel kernel, I i, const T& x) const { cl_int status = clSetKernelArg(kernel, i, sizeof(T), reinterpret_cast<const void*>(&x)); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } template<class I> void operator()(cl_kernel kernel, I i, const LocalMemArg& lmem) const { cl_int status = clSetKernelArg(kernel, i, lmem.GetSize(), NULL); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } }; struct OCLKernelInvoke { cl_command_queue queue; SharedKernelPtr kernel; size_t work_dim; std::array<size_t, 3> global_work_offset; std::array<size_t, 3> global_work_dim; std::array<size_t, 3> local_work_dim; std::function<void(cl_event&)> callback; template<class... Ts> void operator()(const Ts&... xs) const { each_args_i(std::bind(OCLSetKernelArg{}, kernel.get(), std::placeholders::_1, std::placeholders::_2), xs...); run(); } void run() const; }; class OCLKernel { public: OCLKernel() {} OCLKernel(ClKernelPtr k) : kernel(std::move(k)) {} OCLKernel(ClKernelPtr k, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : kernel(std::move(k)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(ldims.size() == gdims.size()); assert(!ldims.empty() && ldims.size() <= 3); } OCLKernel(SharedProgramPtr p, const std::string& kernel_name, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : program(p), kernel(CreateKernel(p.get(), kernel_name)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(!gdims.empty() && gdims.size() <= 3); assert(!ldims.empty() && ldims.size() <= 3); if(std::accumulate(ldims.begin(), ldims.end(), 1, std::multiplies<size_t>{}) > 256) { std::fill(ldims.begin(), ldims.end(), 0); } } OCLKernelInvoke Invoke(cl_command_queue q, std::function<void(cl_event&)> callback=nullptr); cl_kernel GetKernel() { return kernel.get(); } std::string GetName() const; inline const std::vector<size_t>& GetLocalDims() const { return ldims; } inline const std::vector<size_t>& GetGlobalDims() const { return gdims; } private: SharedProgramPtr program; SharedKernelPtr kernel; std::vector<size_t> ldims; std::vector<size_t> gdims; }; } // namespace mlopen #endif // GUARD_MLOPEN_OCL_KERNEL_HPP_ <commit_msg>added numeric header<commit_after>#ifndef GUARD_MLOPEN_OCL_KERNEL_HPP_ #define GUARD_MLOPEN_OCL_KERNEL_HPP_ #include <sstream> #include <array> #include <utility> #include <vector> #include <mlopen.h> #include <cassert> #include <functional> #include <array> #include <memory> #include <algorithm> #include <numeric> #include <mlopen/errors.hpp> #include <mlopen/each_args.hpp> #include <mlopen/clhelper.hpp> namespace mlopen { using SharedKernelPtr = std::shared_ptr<typename std::remove_pointer<cl_kernel>::type>; using SharedProgramPtr = std::shared_ptr<typename std::remove_pointer<cl_program>::type>; struct LocalMemArg { LocalMemArg(size_t _size) : size(_size) {} size_t GetSize() const { return size; } private: size_t size; }; struct OCLSetKernelArg { template<class I, class T> void operator()(cl_kernel kernel, I i, const T& x) const { cl_int status = clSetKernelArg(kernel, i, sizeof(T), reinterpret_cast<const void*>(&x)); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } template<class I> void operator()(cl_kernel kernel, I i, const LocalMemArg& lmem) const { cl_int status = clSetKernelArg(kernel, i, lmem.GetSize(), NULL); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } }; struct OCLKernelInvoke { cl_command_queue queue; SharedKernelPtr kernel; size_t work_dim; std::array<size_t, 3> global_work_offset; std::array<size_t, 3> global_work_dim; std::array<size_t, 3> local_work_dim; std::function<void(cl_event&)> callback; template<class... Ts> void operator()(const Ts&... xs) const { each_args_i(std::bind(OCLSetKernelArg{}, kernel.get(), std::placeholders::_1, std::placeholders::_2), xs...); run(); } void run() const; }; class OCLKernel { public: OCLKernel() {} OCLKernel(ClKernelPtr k) : kernel(std::move(k)) {} OCLKernel(ClKernelPtr k, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : kernel(std::move(k)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(ldims.size() == gdims.size()); assert(!ldims.empty() && ldims.size() <= 3); } OCLKernel(SharedProgramPtr p, const std::string& kernel_name, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : program(p), kernel(CreateKernel(p.get(), kernel_name)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(!gdims.empty() && gdims.size() <= 3); assert(!ldims.empty() && ldims.size() <= 3); if(std::accumulate(ldims.begin(), ldims.end(), 1, std::multiplies<size_t>{}) > 256) { std::fill(ldims.begin(), ldims.end(), 0); } } OCLKernelInvoke Invoke(cl_command_queue q, std::function<void(cl_event&)> callback=nullptr); cl_kernel GetKernel() { return kernel.get(); } std::string GetName() const; inline const std::vector<size_t>& GetLocalDims() const { return ldims; } inline const std::vector<size_t>& GetGlobalDims() const { return gdims; } private: SharedProgramPtr program; SharedKernelPtr kernel; std::vector<size_t> ldims; std::vector<size_t> gdims; }; } // namespace mlopen #endif // GUARD_MLOPEN_OCL_KERNEL_HPP_ <|endoftext|>
<commit_before><commit_msg>Flick the switch back to PATCH_PROTOCOL while sorting out a few failing unit tests on the builder.<commit_after><|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../StroikaPreComp.h" #include "Instruments/LoadAverage.h" #include "Instruments/MountedFilesystemUsage.h" #include "Instruments/NetworkInterfaces.h" #include "Instruments/ProcessDetails.h" #include "Instruments/SystemTimes.h" #include "AllInstruments.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; /* ******************************************************************************** ******************* SystemPerformance::GetAllInstruments *********************** ******************************************************************************** */ InstrumentSet SystemPerformance::GetAllInstruments () { // OK to cache - copyable - but construct AFTER main (only when called here) static InstrumentSet kInstruments_ = { #if qSupport_SystemPerformance_Instruments_LoadAverage Instruments::LoadAverage::GetInstrument (), #endif #if qSupport_SystemPerformance_Instruments_SystemTimes Instruments::SystemTimes::GetInstrument (), #endif Instruments::NetworkInterfaces::GetInstrument (), Instruments::ProcessDetails::GetInstrument (), Instruments::MountedFilesystemUsage::GetInstrument (), }; return kInstruments_; } <commit_msg>include Instruments::SystemCPU::GetInstrument () in AllInstruments<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../StroikaPreComp.h" #include "Instruments/LoadAverage.h" #include "Instruments/MountedFilesystemUsage.h" #include "Instruments/NetworkInterfaces.h" #include "Instruments/ProcessDetails.h" #include "Instruments/SystemCPU.h" #include "Instruments/SystemTimes.h" #include "AllInstruments.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; /* ******************************************************************************** ******************* SystemPerformance::GetAllInstruments *********************** ******************************************************************************** */ InstrumentSet SystemPerformance::GetAllInstruments () { // OK to cache - copyable - but construct AFTER main (only when called here) static InstrumentSet kInstruments_ = { #if qSupport_SystemPerformance_Instruments_LoadAverage Instruments::LoadAverage::GetInstrument (), #endif #if qSupport_SystemPerformance_Instruments_SystemTimes Instruments::SystemTimes::GetInstrument (), #endif Instruments::NetworkInterfaces::GetInstrument (), Instruments::ProcessDetails::GetInstrument (), Instruments::MountedFilesystemUsage::GetInstrument (), Instruments::SystemCPU::GetInstrument (), }; return kInstruments_; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: GridWrapper.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 17:18:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_GRIDWRAPPER_HXX #define CHART_GRIDWRAPPER_HXX #include "WrappedPropertySet.hxx" #include "ServiceMacros.hxx" #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_ #include <com/sun/star/chart2/XDiagram.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #include <boost/shared_ptr.hpp> namespace chart { namespace wrapper { class Chart2ModelContact; class GridWrapper : public ::cppu::ImplInheritanceHelper2< WrappedPropertySet , com::sun::star::lang::XComponent , com::sun::star::lang::XServiceInfo > { public: enum tGridType { X_MAIN_GRID, Y_MAIN_GRID, Z_MAIN_GRID, X_SUB_GRID, Y_SUB_GRID, Z_SUB_GRID, }; GridWrapper( tGridType eType, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact ); virtual ~GridWrapper(); static void getDimensionAndSubGridBool( tGridType eType, sal_Int32& rnDimensionIndex, bool& rbSubGrid ); /// XServiceInfo declarations APPHELPER_XSERVICEINFO_DECL() // ____ XComponent ____ virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); protected: // ____ WrappedPropertySet ____ virtual const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& getPropertySequence(); virtual const std::vector< WrappedProperty* > createWrappedProperties(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getInnerPropertySet(); private: ::boost::shared_ptr< Chart2ModelContact > m_spChart2ModelContact; ::cppu::OInterfaceContainerHelper m_aEventListenerContainer; tGridType m_eType; }; } // namespace wrapper } // namespace chart // CHART_GRIDWRAPPER_HXX #endif <commit_msg>INTEGRATION: CWS chart11 (1.2.38); FILE MERGED 2007/08/01 06:10:36 bm 1.2.38.1: #i79522# warning removed (unxsoli4)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: GridWrapper.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2007-09-18 14:52:46 $ * * 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 CHART_GRIDWRAPPER_HXX #define CHART_GRIDWRAPPER_HXX #include "WrappedPropertySet.hxx" #include "ServiceMacros.hxx" #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_ #include <com/sun/star/chart2/XDiagram.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #include <boost/shared_ptr.hpp> namespace chart { namespace wrapper { class Chart2ModelContact; class GridWrapper : public ::cppu::ImplInheritanceHelper2< WrappedPropertySet , com::sun::star::lang::XComponent , com::sun::star::lang::XServiceInfo > { public: enum tGridType { X_MAIN_GRID, Y_MAIN_GRID, Z_MAIN_GRID, X_SUB_GRID, Y_SUB_GRID, Z_SUB_GRID }; GridWrapper( tGridType eType, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact ); virtual ~GridWrapper(); static void getDimensionAndSubGridBool( tGridType eType, sal_Int32& rnDimensionIndex, bool& rbSubGrid ); /// XServiceInfo declarations APPHELPER_XSERVICEINFO_DECL() // ____ XComponent ____ virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); protected: // ____ WrappedPropertySet ____ virtual const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& getPropertySequence(); virtual const std::vector< WrappedProperty* > createWrappedProperties(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getInnerPropertySet(); private: ::boost::shared_ptr< Chart2ModelContact > m_spChart2ModelContact; ::cppu::OInterfaceContainerHelper m_aEventListenerContainer; tGridType m_eType; }; } // namespace wrapper } // namespace chart // CHART_GRIDWRAPPER_HXX #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MultipleChartConverters.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:24:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART2_MULTIPLECHARTCONVERTERS_HXX #define CHART2_MULTIPLECHARTCONVERTERS_HXX #include "MultipleItemConverter.hxx" #ifndef _COM_SUN_STAR_AWT_SIZE_HPP_ #include <com/sun/star/awt/Size.hpp> #endif #include <memory> class SdrModel; namespace chart { namespace wrapper { class AllAxisItemConverter : public ::comphelper::MultipleItemConverter { public: AllAxisItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize = ::std::auto_ptr< ::com::sun::star::awt::Size >() ); virtual ~AllAxisItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllGridItemConverter : public ::comphelper::MultipleItemConverter { public: AllGridItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel ); virtual ~AllGridItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllDataLabelItemConverter : public ::comphelper::MultipleItemConverter { public: AllDataLabelItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize = ::std::auto_ptr< ::com::sun::star::awt::Size >() ); virtual ~AllDataLabelItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllTitleItemConverter : public ::comphelper::MultipleItemConverter { public: AllTitleItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize = ::std::auto_ptr< ::com::sun::star::awt::Size >() ); virtual ~AllTitleItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllSeriesStatisticsConverter : public ::comphelper::MultipleItemConverter { public: AllSeriesStatisticsConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool ); virtual ~AllSeriesStatisticsConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; } // namespace wrapper } // namespace chart // CHART2_MULTIPLECHARTCONVERTERS_HXX #endif <commit_msg>INTEGRATION: CWS chart2mst3 (1.4.4); FILE MERGED 2005/10/07 11:26:57 bm 1.4.4.2: RESYNC: (1.4-1.5); FILE MERGED 2005/07/12 12:56:59 bm 1.4.4.1: use named properties for gradients etc. in chart model<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MultipleChartConverters.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-05-22 17:54:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART2_MULTIPLECHARTCONVERTERS_HXX #define CHART2_MULTIPLECHARTCONVERTERS_HXX #include "MultipleItemConverter.hxx" #ifndef _COM_SUN_STAR_AWT_SIZE_HPP_ #include <com/sun/star/awt/Size.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #include <memory> class SdrModel; namespace chart { namespace wrapper { class AllAxisItemConverter : public ::comphelper::MultipleItemConverter { public: AllAxisItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory, ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize = ::std::auto_ptr< ::com::sun::star::awt::Size >() ); virtual ~AllAxisItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllGridItemConverter : public ::comphelper::MultipleItemConverter { public: AllGridItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory ); virtual ~AllGridItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllDataLabelItemConverter : public ::comphelper::MultipleItemConverter { public: AllDataLabelItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory, ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize = ::std::auto_ptr< ::com::sun::star::awt::Size >() ); virtual ~AllDataLabelItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllTitleItemConverter : public ::comphelper::MultipleItemConverter { public: AllTitleItemConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool, SdrModel& rDrawModel, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory, ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize = ::std::auto_ptr< ::com::sun::star::awt::Size >() ); virtual ~AllTitleItemConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; class AllSeriesStatisticsConverter : public ::comphelper::MultipleItemConverter { public: AllSeriesStatisticsConverter( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel, SfxItemPool& rItemPool ); virtual ~AllSeriesStatisticsConverter(); protected: virtual const USHORT * GetWhichPairs() const; }; } // namespace wrapper } // namespace chart // CHART2_MULTIPLECHARTCONVERTERS_HXX #endif <|endoftext|>
<commit_before>// Copyright 2014 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/android/compositor/layer/content_layer.h" #include "cc/layers/layer.h" #include "cc/layers/layer_lists.h" #include "chrome/browser/android/compositor/layer/thumbnail_layer.h" #include "chrome/browser/android/compositor/tab_content_manager.h" #include "ui/gfx/geometry/size.h" namespace chrome { namespace android { // static scoped_refptr<ContentLayer> ContentLayer::Create( TabContentManager* tab_content_manager) { return make_scoped_refptr(new ContentLayer(tab_content_manager)); } static void SetOpacityOnLeaf(scoped_refptr<cc::Layer> layer, float alpha) { const cc::LayerList& children = layer->children(); if (children.size() > 0) { layer->SetOpacity(1.0f); for (uint i = 0; i < children.size(); ++i) SetOpacityOnLeaf(children[i], alpha); } else { layer->SetOpacity(alpha); } } static bool DoesLeafDrawContents(scoped_refptr<cc::Layer> layer) { if (!layer.get()) return false; // TODO: Remove the need for this logic. We can't really guess from // an opaque layer type whether it has valid live contents, or for example // just a background color placeholder. Need to get this from somewhere else // like ContentViewCore or RWHV. if (layer->DrawsContent() && !layer->hide_layer_and_subtree() && !layer->background_color()) { return true; } const cc::LayerList& children = layer->children(); for (unsigned i = 0; i < children.size(); i++) { if (DoesLeafDrawContents(children[i])) return true; } return false; } static gfx::Size GetLeafBounds(scoped_refptr<cc::Layer> layer) { if (layer->children().size() > 0) return GetLeafBounds(layer->children()[0]); return layer->bounds(); } void ContentLayer::SetProperties(int id, bool can_use_live_layer, bool can_use_ntp_fallback, float static_to_view_blend, bool should_override_content_alpha, float content_alpha_override, float saturation, const gfx::Rect& desired_bounds, const gfx::Size& content_size) { scoped_refptr<cc::Layer> content_layer = tab_content_manager_->GetLiveLayer(id); ClipContentLayer(content_layer, desired_bounds, content_size); bool content_layer_draws = DoesLeafDrawContents(content_layer); scoped_refptr<ThumbnailLayer> static_layer = tab_content_manager_->GetStaticLayer(id, !content_layer_draws); ClipStaticLayer(static_layer, desired_bounds); // Reset the attachment logic if the number of children doesn't match the // boolean flags. At some point while a tab is in the background one or more // layers may be removed from this tree. // Note that this needs to be checked *after* we access TabContentManager, as // that class might remove layers internally, messing up our own tracking. unsigned int expected_layers = 0; expected_layers += content_attached_ ? 1 : 0; expected_layers += static_attached_ ? 1 : 0; if (layer_->children().size() != expected_layers) { content_attached_ = false; static_attached_ = false; const cc::LayerList& layer_children = layer_->children(); for (unsigned i = 0; i < layer_children.size(); i++) layer_children[i]->RemoveFromParent(); } gfx::Size content_bounds(0, 0); if (!content_layer.get() || !can_use_live_layer) { SetContentLayer(nullptr); SetStaticLayer(static_layer); if (static_layer.get()) content_bounds = static_layer->layer()->bounds(); else content_bounds.set_width(content_size.width()); } else { SetContentLayer(content_layer); content_bounds = content_layer->bounds(); if (static_to_view_blend == 0.0f && !content_layer_draws) static_to_view_blend = 1.0f; if (static_to_view_blend != 0.0f && static_layer.get()) { static_layer->layer()->SetOpacity(static_to_view_blend); SetStaticLayer(static_layer); if (content_bounds.GetArea() == 0 || !content_layer_draws) content_bounds = static_layer->layer()->bounds(); } else { SetStaticLayer(nullptr); } } if (should_override_content_alpha) { for (unsigned int i = 0; i < layer_->children().size(); ++i) SetOpacityOnLeaf(layer_->children()[i], content_alpha_override); } if (!content_layer_draws && !static_attached_) content_bounds = gfx::Size(0, 0); layer_->SetBounds(content_bounds); // Only worry about saturation on the static layer if (static_layer.get()) { if (saturation != saturation_) { saturation_ = saturation; cc::FilterOperations filters; if (saturation_ < 1.0f) filters.Append(cc::FilterOperation::CreateSaturateFilter(saturation_)); static_layer->layer()->SetFilters(filters); } } } gfx::Size ContentLayer::GetContentSize() { if (content_attached_ && DoesLeafDrawContents(layer()->children()[0])) return layer_->children()[0]->bounds(); return gfx::Size(0, 0); } scoped_refptr<cc::Layer> ContentLayer::layer() { return layer_; } ContentLayer::ContentLayer(TabContentManager* tab_content_manager) : layer_(cc::Layer::Create()), content_attached_(false), static_attached_(false), saturation_(1.0f), tab_content_manager_(tab_content_manager) { } ContentLayer::~ContentLayer() { } void ContentLayer::SetContentLayer(scoped_refptr<cc::Layer> layer) { // Check indices // content_attached_, expect at least 1 child. DCHECK(!content_attached_ || layer_->children().size() > 0); if (!layer.get()) { if (content_attached_) layer_->child_at(0)->RemoveFromParent(); content_attached_ = false; return; } bool new_layer = false; if (content_attached_ && layer_->child_at(0)->id() != layer->id()) { layer_->ReplaceChild(layer_->child_at(0), layer); new_layer = true; } else if (!content_attached_) { layer_->InsertChild(layer, 0); new_layer = true; } // If this is a new layer, reset it's opacity. if (new_layer) SetOpacityOnLeaf(layer, 1.0f); content_attached_ = true; } void ContentLayer::SetStaticLayer( scoped_refptr<ThumbnailLayer> new_static_layer) { // Make sure child access will be valid. // !content_attached_ AND !static_attached_, expect 0 children. // content_attached_ XOR static_attached_, expect 1 child. // content_attached_ AND static_attached_, expect 2 children. DCHECK((!content_attached_ && !static_attached_) || (content_attached_ != static_attached_ && layer_->children().size() >= 1) || (content_attached_ && static_attached_ && layer_->children().size() >= 2)); if (!new_static_layer.get()) { if (static_layer_.get()) { static_layer_->layer()->RemoveFromParent(); static_layer_ = nullptr; } static_attached_ = false; return; } static_layer_ = new_static_layer; static_layer_->AddSelfToParentOrReplaceAt(layer_, content_attached_ ? 1 : 0); saturation_ = -1.0f; static_layer_->layer()->SetIsDrawable(true); static_attached_ = true; } void ContentLayer::ClipContentLayer(scoped_refptr<cc::Layer> content_layer, gfx::Rect clipping, gfx::Size content_size) { if (!content_layer.get()) return; gfx::Size bounds(GetLeafBounds(content_layer)); content_layer->SetMasksToBounds(true); gfx::Size clamped_bounds(bounds); clamped_bounds.SetToMin(clipping.size()); content_layer->SetBounds(clamped_bounds); if (content_layer->children().size() > 0) { gfx::PointF offset( std::min(content_size.width() - bounds.width() - clipping.x(), 0), std::min(content_size.height() - bounds.height() - clipping.y(), 0)); content_layer->children()[0]->SetPosition(offset); } } void ContentLayer::ClipStaticLayer(scoped_refptr<ThumbnailLayer> static_layer, gfx::Rect clipping) { if (!static_layer.get()) return; static_layer->Clip(clipping); } } // namespace android } // namespace chrome <commit_msg>Set force_disk_read when live layer isn't valid<commit_after>// Copyright 2014 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/android/compositor/layer/content_layer.h" #include "cc/layers/layer.h" #include "cc/layers/layer_lists.h" #include "chrome/browser/android/compositor/layer/thumbnail_layer.h" #include "chrome/browser/android/compositor/tab_content_manager.h" #include "ui/gfx/geometry/size.h" namespace chrome { namespace android { // static scoped_refptr<ContentLayer> ContentLayer::Create( TabContentManager* tab_content_manager) { return make_scoped_refptr(new ContentLayer(tab_content_manager)); } static void SetOpacityOnLeaf(scoped_refptr<cc::Layer> layer, float alpha) { const cc::LayerList& children = layer->children(); if (children.size() > 0) { layer->SetOpacity(1.0f); for (uint i = 0; i < children.size(); ++i) SetOpacityOnLeaf(children[i], alpha); } else { layer->SetOpacity(alpha); } } static bool DoesLeafDrawContents(scoped_refptr<cc::Layer> layer) { if (!layer.get()) return false; // TODO: Remove the need for this logic. We can't really guess from // an opaque layer type whether it has valid live contents, or for example // just a background color placeholder. Need to get this from somewhere else // like ContentViewCore or RWHV. if (layer->DrawsContent() && !layer->hide_layer_and_subtree() && !layer->background_color()) { return true; } const cc::LayerList& children = layer->children(); for (unsigned i = 0; i < children.size(); i++) { if (DoesLeafDrawContents(children[i])) return true; } return false; } static gfx::Size GetLeafBounds(scoped_refptr<cc::Layer> layer) { if (layer->children().size() > 0) return GetLeafBounds(layer->children()[0]); return layer->bounds(); } void ContentLayer::SetProperties(int id, bool can_use_live_layer, bool can_use_ntp_fallback, float static_to_view_blend, bool should_override_content_alpha, float content_alpha_override, float saturation, const gfx::Rect& desired_bounds, const gfx::Size& content_size) { scoped_refptr<cc::Layer> content_layer = tab_content_manager_->GetLiveLayer(id); ClipContentLayer(content_layer, desired_bounds, content_size); bool content_layer_draws = DoesLeafDrawContents(content_layer); scoped_refptr<ThumbnailLayer> static_layer = tab_content_manager_->GetStaticLayer( id, !(can_use_live_layer && content_layer_draws)); ClipStaticLayer(static_layer, desired_bounds); // Reset the attachment logic if the number of children doesn't match the // boolean flags. At some point while a tab is in the background one or more // layers may be removed from this tree. // Note that this needs to be checked *after* we access TabContentManager, as // that class might remove layers internally, messing up our own tracking. unsigned int expected_layers = 0; expected_layers += content_attached_ ? 1 : 0; expected_layers += static_attached_ ? 1 : 0; if (layer_->children().size() != expected_layers) { content_attached_ = false; static_attached_ = false; const cc::LayerList& layer_children = layer_->children(); for (unsigned i = 0; i < layer_children.size(); i++) layer_children[i]->RemoveFromParent(); } gfx::Size content_bounds(0, 0); if (!content_layer.get() || !can_use_live_layer) { SetContentLayer(nullptr); SetStaticLayer(static_layer); if (static_layer.get()) content_bounds = static_layer->layer()->bounds(); else content_bounds.set_width(content_size.width()); } else { SetContentLayer(content_layer); content_bounds = content_layer->bounds(); if (static_to_view_blend == 0.0f && !content_layer_draws) static_to_view_blend = 1.0f; if (static_to_view_blend != 0.0f && static_layer.get()) { static_layer->layer()->SetOpacity(static_to_view_blend); SetStaticLayer(static_layer); if (content_bounds.GetArea() == 0 || !content_layer_draws) content_bounds = static_layer->layer()->bounds(); } else { SetStaticLayer(nullptr); } } if (should_override_content_alpha) { for (unsigned int i = 0; i < layer_->children().size(); ++i) SetOpacityOnLeaf(layer_->children()[i], content_alpha_override); } if (!content_layer_draws && !static_attached_) content_bounds = gfx::Size(0, 0); layer_->SetBounds(content_bounds); // Only worry about saturation on the static layer if (static_layer.get()) { if (saturation != saturation_) { saturation_ = saturation; cc::FilterOperations filters; if (saturation_ < 1.0f) filters.Append(cc::FilterOperation::CreateSaturateFilter(saturation_)); static_layer->layer()->SetFilters(filters); } } } gfx::Size ContentLayer::GetContentSize() { if (content_attached_ && DoesLeafDrawContents(layer()->children()[0])) return layer_->children()[0]->bounds(); return gfx::Size(0, 0); } scoped_refptr<cc::Layer> ContentLayer::layer() { return layer_; } ContentLayer::ContentLayer(TabContentManager* tab_content_manager) : layer_(cc::Layer::Create()), content_attached_(false), static_attached_(false), saturation_(1.0f), tab_content_manager_(tab_content_manager) { } ContentLayer::~ContentLayer() { } void ContentLayer::SetContentLayer(scoped_refptr<cc::Layer> layer) { // Check indices // content_attached_, expect at least 1 child. DCHECK(!content_attached_ || layer_->children().size() > 0); if (!layer.get()) { if (content_attached_) layer_->child_at(0)->RemoveFromParent(); content_attached_ = false; return; } bool new_layer = false; if (content_attached_ && layer_->child_at(0)->id() != layer->id()) { layer_->ReplaceChild(layer_->child_at(0), layer); new_layer = true; } else if (!content_attached_) { layer_->InsertChild(layer, 0); new_layer = true; } // If this is a new layer, reset it's opacity. if (new_layer) SetOpacityOnLeaf(layer, 1.0f); content_attached_ = true; } void ContentLayer::SetStaticLayer( scoped_refptr<ThumbnailLayer> new_static_layer) { // Make sure child access will be valid. // !content_attached_ AND !static_attached_, expect 0 children. // content_attached_ XOR static_attached_, expect 1 child. // content_attached_ AND static_attached_, expect 2 children. DCHECK((!content_attached_ && !static_attached_) || (content_attached_ != static_attached_ && layer_->children().size() >= 1) || (content_attached_ && static_attached_ && layer_->children().size() >= 2)); if (!new_static_layer.get()) { if (static_layer_.get()) { static_layer_->layer()->RemoveFromParent(); static_layer_ = nullptr; } static_attached_ = false; return; } static_layer_ = new_static_layer; static_layer_->AddSelfToParentOrReplaceAt(layer_, content_attached_ ? 1 : 0); saturation_ = -1.0f; static_layer_->layer()->SetIsDrawable(true); static_attached_ = true; } void ContentLayer::ClipContentLayer(scoped_refptr<cc::Layer> content_layer, gfx::Rect clipping, gfx::Size content_size) { if (!content_layer.get()) return; gfx::Size bounds(GetLeafBounds(content_layer)); content_layer->SetMasksToBounds(true); gfx::Size clamped_bounds(bounds); clamped_bounds.SetToMin(clipping.size()); content_layer->SetBounds(clamped_bounds); if (content_layer->children().size() > 0) { gfx::PointF offset( std::min(content_size.width() - bounds.width() - clipping.x(), 0), std::min(content_size.height() - bounds.height() - clipping.y(), 0)); content_layer->children()[0]->SetPosition(offset); } } void ContentLayer::ClipStaticLayer(scoped_refptr<ThumbnailLayer> static_layer, gfx::Rect clipping) { if (!static_layer.get()) return; static_layer->Clip(clipping); } } // namespace android } // namespace chrome <|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 <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" // A mock implementation of ExtensionsServiceFrontendInterface for testing the // backend. class ExtensionsServiceTestFrontend : public ExtensionsServiceFrontendInterface { public: ~ExtensionsServiceTestFrontend() { for (ExtensionList::iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { delete *iter; } } std::vector<std::string>* errors() { return &errors_; } ExtensionList* extensions() { return &extensions_; } // ExtensionsServiceFrontendInterface virtual MessageLoop* GetMessageLoop() { return &message_loop_; } virtual void OnExtensionLoadError(const std::string& message) { errors_.push_back(message); } virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) { extensions_.insert(extensions_.end(), new_extensions->begin(), new_extensions->end()); delete new_extensions; } private: MessageLoop message_loop_; ExtensionList extensions_; std::vector<std::string> errors_; }; // make the test a PlatformTest to setup autorelease pools properly on mac typedef PlatformTest ExtensionsServiceTest; // Test loading extensions from the profile directory. TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) { std::wstring extensions_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir)); FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append( FILE_PATH_LITERAL("extensions")); scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend); scoped_refptr<ExtensionsServiceTestFrontend> frontend( new ExtensionsServiceTestFrontend); std::vector<Extension*> extensions; EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path, scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get()))); frontend->GetMessageLoop()->RunAllPending(); // Note: There can be more errors if there are extra directories, like .svn // directories. EXPECT_TRUE(frontend->errors()->size() >= 2u); EXPECT_EQ(2u, frontend->extensions()->size()); EXPECT_EQ(std::wstring(L"com.google.myextension1"), frontend->extensions()->at(0)->id()); EXPECT_EQ(std::wstring(L"My extension 1"), frontend->extensions()->at(0)->name()); EXPECT_EQ(std::wstring(L"The first extension that I made."), frontend->extensions()->at(0)->description()); EXPECT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size()); EXPECT_EQ(std::wstring(L"script1.user.js"), frontend->extensions()->at(0)->content_scripts().at(0)); EXPECT_EQ(std::wstring(L"script2.user.js"), frontend->extensions()->at(0)->content_scripts().at(1)); EXPECT_EQ(std::wstring(L"com.google.myextension2"), frontend->extensions()->at(1)->id()); EXPECT_EQ(std::wstring(L"My extension 2"), frontend->extensions()->at(1)->name()); EXPECT_EQ(std::wstring(L""), frontend->extensions()->at(1)->description()); EXPECT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size()); }; <commit_msg>Fix extensions_service_unittest on Linux.<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 <algorithm> #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/extensions/extension.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" namespace { struct ExtensionsOrder { bool operator()(const Extension* a, const Extension* b) { return a->name() < b->name(); } }; } // namespace // A mock implementation of ExtensionsServiceFrontendInterface for testing the // backend. class ExtensionsServiceTestFrontend : public ExtensionsServiceFrontendInterface { public: ~ExtensionsServiceTestFrontend() { for (ExtensionList::iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { delete *iter; } } std::vector<std::string>* errors() { return &errors_; } ExtensionList* extensions() { return &extensions_; } // ExtensionsServiceFrontendInterface virtual MessageLoop* GetMessageLoop() { return &message_loop_; } virtual void OnExtensionLoadError(const std::string& message) { errors_.push_back(message); } virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) { extensions_.insert(extensions_.end(), new_extensions->begin(), new_extensions->end()); delete new_extensions; // In the tests we rely on extensions being in particular order, // which is not always the case (and is not guaranteed by used APIs). std::stable_sort(extensions_.begin(), extensions_.end(), ExtensionsOrder()); } private: MessageLoop message_loop_; ExtensionList extensions_; std::vector<std::string> errors_; }; // make the test a PlatformTest to setup autorelease pools properly on mac typedef PlatformTest ExtensionsServiceTest; // Test loading extensions from the profile directory. TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) { std::wstring extensions_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir)); FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append( FILE_PATH_LITERAL("extensions")); scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend); scoped_refptr<ExtensionsServiceTestFrontend> frontend( new ExtensionsServiceTestFrontend); std::vector<Extension*> extensions; EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path, scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get()))); frontend->GetMessageLoop()->RunAllPending(); // Note: There can be more errors if there are extra directories, like .svn // directories. EXPECT_TRUE(frontend->errors()->size() >= 2u); ASSERT_EQ(2u, frontend->extensions()->size()); EXPECT_EQ(std::wstring(L"com.google.myextension1"), frontend->extensions()->at(0)->id()); EXPECT_EQ(std::wstring(L"My extension 1"), frontend->extensions()->at(0)->name()); EXPECT_EQ(std::wstring(L"The first extension that I made."), frontend->extensions()->at(0)->description()); ASSERT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size()); EXPECT_EQ(std::wstring(L"script1.user.js"), frontend->extensions()->at(0)->content_scripts().at(0)); EXPECT_EQ(std::wstring(L"script2.user.js"), frontend->extensions()->at(0)->content_scripts().at(1)); EXPECT_EQ(std::wstring(L"com.google.myextension2"), frontend->extensions()->at(1)->id()); EXPECT_EQ(std::wstring(L"My extension 2"), frontend->extensions()->at(1)->name()); EXPECT_EQ(std::wstring(L""), frontend->extensions()->at(1)->description()); ASSERT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size()); }; <|endoftext|>
<commit_before>/** * \file * \brief StaticRawMessageQueue class header * * \author Copyright (C) 2015-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #define INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #include "distortos/RawMessageQueue.hpp" #include "distortos/internal/memory/dummyDeleter.hpp" namespace distortos { /** * \brief StaticRawMessageQueue class is a variant of RawMessageQueue that has automatic storage for queue's contents. * * This class is a replacement for StaticRawMessageQueue with old API and removed StaticRawMessageQueueFromSize. To use * this new API modify your code in following way: * - old `"StaticRawMessageQueue<T, QueueSize>"` -> `"StaticRawMessageQueue<sizeof(T), QueueSize>"`; * - removed `"StaticRawMessageQueueFromSize<ElementSize, QueueSize>"` -> * `"StaticRawMessageQueue<ElementSize, QueueSize>"`; * * Transition schedule: * 1. v0.5.0 - `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>` are * converted to deprecated aliases to `StaticRawMessageQueue2<ElementSize, QueueSize>`; * 2. v0.6.0 - "old" `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>` * aliases are removed, `StaticRawMessageQueue2<ElementSize, QueueSize>` is renamed to * `StaticRawMessageQueue<ElementSize, QueueSize>`, deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is * added; * 3. v0.7.0 - deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is removed; * * \tparam ElementSize is the size of single queue element, bytes * \tparam QueueSize is the maximum number of elements in queue * * \ingroup queues */ template<size_t ElementSize, size_t QueueSize> class StaticRawMessageQueue : public RawMessageQueue { public: /** * \brief StaticRawMessageQueue's constructor */ explicit StaticRawMessageQueue() : RawMessageQueue{{entryStorage_.data(), internal::dummyDeleter<EntryStorage>}, {valueStorage_.data(), internal::dummyDeleter<uint8_t>}, ElementSize, QueueSize} { } private: /// storage for queue's entries std::array<EntryStorage, QueueSize> entryStorage_; /// storage for queue's contents std::array<uint8_t, ElementSize * QueueSize> valueStorage_; }; /** * \brief StaticRawMessageQueue2 class is a variant of RawMessageQueue that has automatic storage for queue's contents. * * \deprecated scheduled to be removed after v0.6.0, use `StaticRawMessageQueue<ElementSize, QueueSize>` * * \tparam ElementSize is the size of single queue element, bytes * \tparam QueueSize is the maximum number of elements in queue * * \ingroup queues */ template<size_t ElementSize, size_t QueueSize> using StaticRawMessageQueue2 __attribute__ ((deprecated("Use StaticRawMessageQueue<ElementSize, QueueSize>"))) = StaticRawMessageQueue<ElementSize, QueueSize>; } // namespace distortos #endif // INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ <commit_msg>Add constexpr static StaticRawMessageQueue::getElementSize()<commit_after>/** * \file * \brief StaticRawMessageQueue class header * * \author Copyright (C) 2015-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #define INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ #include "distortos/RawMessageQueue.hpp" #include "distortos/internal/memory/dummyDeleter.hpp" namespace distortos { /** * \brief StaticRawMessageQueue class is a variant of RawMessageQueue that has automatic storage for queue's contents. * * This class is a replacement for StaticRawMessageQueue with old API and removed StaticRawMessageQueueFromSize. To use * this new API modify your code in following way: * - old `"StaticRawMessageQueue<T, QueueSize>"` -> `"StaticRawMessageQueue<sizeof(T), QueueSize>"`; * - removed `"StaticRawMessageQueueFromSize<ElementSize, QueueSize>"` -> * `"StaticRawMessageQueue<ElementSize, QueueSize>"`; * * Transition schedule: * 1. v0.5.0 - `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>` are * converted to deprecated aliases to `StaticRawMessageQueue2<ElementSize, QueueSize>`; * 2. v0.6.0 - "old" `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>` * aliases are removed, `StaticRawMessageQueue2<ElementSize, QueueSize>` is renamed to * `StaticRawMessageQueue<ElementSize, QueueSize>`, deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is * added; * 3. v0.7.0 - deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is removed; * * \tparam ElementSize is the size of single queue element, bytes * \tparam QueueSize is the maximum number of elements in queue * * \ingroup queues */ template<size_t ElementSize, size_t QueueSize> class StaticRawMessageQueue : public RawMessageQueue { public: /** * \brief StaticRawMessageQueue's constructor */ explicit StaticRawMessageQueue() : RawMessageQueue{{entryStorage_.data(), internal::dummyDeleter<EntryStorage>}, {valueStorage_.data(), internal::dummyDeleter<uint8_t>}, ElementSize, QueueSize} { } /** * \return size of single queue element, bytes */ constexpr static size_t getElementSize() { return ElementSize; } private: /// storage for queue's entries std::array<EntryStorage, QueueSize> entryStorage_; /// storage for queue's contents std::array<uint8_t, ElementSize * QueueSize> valueStorage_; }; /** * \brief StaticRawMessageQueue2 class is a variant of RawMessageQueue that has automatic storage for queue's contents. * * \deprecated scheduled to be removed after v0.6.0, use `StaticRawMessageQueue<ElementSize, QueueSize>` * * \tparam ElementSize is the size of single queue element, bytes * \tparam QueueSize is the maximum number of elements in queue * * \ingroup queues */ template<size_t ElementSize, size_t QueueSize> using StaticRawMessageQueue2 __attribute__ ((deprecated("Use StaticRawMessageQueue<ElementSize, QueueSize>"))) = StaticRawMessageQueue<ElementSize, QueueSize>; } // namespace distortos #endif // INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_ <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_dll_resource.h" #include "chrome/test/automated_ui_tests/automated_ui_test_base.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #if defined(OS_MACOSX) // The window pops up, but doesn't close. #define MAYBE_IncognitoWindow DISABLED_IncognitoWindow #define MAYBE_OpenCloseBrowserWindowWithAccelerator \ DISABLED_OpenCloseBrowserWindowWithAccelerator #else // http://code.google.com/p/chromium/issues/detail?id=14731 #define MAYBE_IncognitoWindow DISABLED_IncognitoWindow #define MAYBE_OpenCloseBrowserWindowWithAccelerator \ OpenCloseBrowserWindowWithAccelerator #endif // http://code.google.com/p/chromium/issues/detail?id=14774 #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_CloseTab DISABLED_CloseTab #define MAYBE_CloseBrowserWindow DISABLED_CloseBrowserWindow #else #define MAYBE_CloseTab CloseTab #define MAYBE_CloseBrowserWindow CloseBrowserWindow #endif TEST_F(AutomatedUITestBase, NewTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, DuplicateTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, DISABLED_RestoreTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL test_url = net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html")); GetActiveTab()->NavigateToURL(test_url); CloseActiveTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); RestoreTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } TEST_F(AutomatedUITestBase, MAYBE_CloseTab) { int num_browser_windows; int tab_count; NewTab(); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); num_browser_windows = 0; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); // The browser window is closed by closing this tab. ASSERT_TRUE(CloseActiveTab()); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); // Active_browser_ is now the first created window. active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); // The last tab should not be closed. ASSERT_FALSE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); } TEST_F(AutomatedUITestBase, OpenBrowserWindow) { int num_browser_windows; int tab_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); scoped_refptr<BrowserProxy> browser_1; ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_1)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); scoped_refptr<BrowserProxy> browser_2; ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_2)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(3, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); browser_2->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); bool application_closed; CloseBrowser(browser_1.get(), &application_closed); ASSERT_FALSE(application_closed); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); CloseBrowser(browser_2.get(), &application_closed); ASSERT_FALSE(application_closed); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, MAYBE_CloseBrowserWindow) { int tab_count; NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(4, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); if (tab_count == 2) { ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } else { ASSERT_EQ(3, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } ASSERT_FALSE(CloseActiveWindow()); } TEST_F(AutomatedUITestBase, MAYBE_IncognitoWindow) { int num_browser_windows; int num_normal_browser_windows; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); ASSERT_TRUE(GoOffTheRecord()); ASSERT_TRUE(GoOffTheRecord()); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); // There is only one normal window so it will not be closed. ASSERT_FALSE(CloseActiveWindow()); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, MAYBE_OpenCloseBrowserWindowWithAccelerator) { // Note: we don't use RunCommand(IDC_OPEN/CLOSE_WINDOW) to open/close // browser window in automated ui tests. Instead we use // OpenAndActivateNewBrowserWindow and CloseActiveWindow. // There are other parts of UI test that use the accelerators. This is // a unit test for those usage. ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); int num_browser_windows; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(7, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(6, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, Navigate) { FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL url1(net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html"))); GURL url2(net::FilePathToFileURL(path_prefix.AppendASCII("bot2.html"))); GURL url3(net::FilePathToFileURL(path_prefix.AppendASCII("bot3.html"))); GURL url; ASSERT_TRUE(Navigate(url1)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(Navigate(url2)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(Navigate(url3)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url3, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(ForwardButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(ReloadPage()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); } <commit_msg>Mark AutomatedUITestBase.OpenCloseBrowserWindowWithAccelerator as a flakey crash, as it has been failing on vista debug bots consistently.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_dll_resource.h" #include "chrome/test/automated_ui_tests/automated_ui_test_base.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #if defined(OS_MACOSX) // The window pops up, but doesn't close. #define MAYBE_IncognitoWindow DISABLED_IncognitoWindow #define MAYBE_OpenCloseBrowserWindowWithAccelerator \ DISABLED_OpenCloseBrowserWindowWithAccelerator #else // http://code.google.com/p/chromium/issues/detail?id=14731 #define MAYBE_IncognitoWindow DISABLED_IncognitoWindow // http://crbug.com/19394 #define MAYBE_OpenCloseBrowserWindowWithAccelerator \ DISABLED_OpenCloseBrowserWindowWithAccelerator #endif // http://code.google.com/p/chromium/issues/detail?id=14774 #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_CloseTab DISABLED_CloseTab #define MAYBE_CloseBrowserWindow DISABLED_CloseBrowserWindow #else #define MAYBE_CloseTab CloseTab #define MAYBE_CloseBrowserWindow CloseBrowserWindow #endif TEST_F(AutomatedUITestBase, NewTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, DuplicateTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, DISABLED_RestoreTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL test_url = net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html")); GetActiveTab()->NavigateToURL(test_url); CloseActiveTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); RestoreTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } TEST_F(AutomatedUITestBase, MAYBE_CloseTab) { int num_browser_windows; int tab_count; NewTab(); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); num_browser_windows = 0; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); // The browser window is closed by closing this tab. ASSERT_TRUE(CloseActiveTab()); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); // Active_browser_ is now the first created window. active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); // The last tab should not be closed. ASSERT_FALSE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); } TEST_F(AutomatedUITestBase, OpenBrowserWindow) { int num_browser_windows; int tab_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); scoped_refptr<BrowserProxy> browser_1; ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_1)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); scoped_refptr<BrowserProxy> browser_2; ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_2)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(3, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); browser_2->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); bool application_closed; CloseBrowser(browser_1.get(), &application_closed); ASSERT_FALSE(application_closed); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); CloseBrowser(browser_2.get(), &application_closed); ASSERT_FALSE(application_closed); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, MAYBE_CloseBrowserWindow) { int tab_count; NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(4, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); if (tab_count == 2) { ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } else { ASSERT_EQ(3, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } ASSERT_FALSE(CloseActiveWindow()); } TEST_F(AutomatedUITestBase, MAYBE_IncognitoWindow) { int num_browser_windows; int num_normal_browser_windows; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); ASSERT_TRUE(GoOffTheRecord()); ASSERT_TRUE(GoOffTheRecord()); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); // There is only one normal window so it will not be closed. ASSERT_FALSE(CloseActiveWindow()); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, MAYBE_OpenCloseBrowserWindowWithAccelerator) { // Note: we don't use RunCommand(IDC_OPEN/CLOSE_WINDOW) to open/close // browser window in automated ui tests. Instead we use // OpenAndActivateNewBrowserWindow and CloseActiveWindow. // There are other parts of UI test that use the accelerators. This is // a unit test for those usage. ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); int num_browser_windows; ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(7, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(6, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows)); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, Navigate) { FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL url1(net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html"))); GURL url2(net::FilePathToFileURL(path_prefix.AppendASCII("bot2.html"))); GURL url3(net::FilePathToFileURL(path_prefix.AppendASCII("bot3.html"))); GURL url; ASSERT_TRUE(Navigate(url1)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(Navigate(url2)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(Navigate(url3)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url3, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(ForwardButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(ReloadPage()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); } <|endoftext|>
<commit_before>#ifndef INC_AL_UTIL_CUBE_MAP_FBO_HPP #define INC_AL_UTIL_CUBE_MAP_FBO_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: A collection of utilities that are specific to OpenGL File author(s): Graham Wakefield, 2010, grrrwaaa@gmail.com */ #include "allocore/graphics/al_Graphics.hpp" #include "allocore/graphics/al_DisplayList.hpp" #include "alloutil/al_TextureGL.hpp" #include <stdio.h> /*! */ namespace al { class CubeMapFBO : public CubeMapTexture { public: CubeMapFBO(int resolution=1024) : CubeMapTexture(resolution), mFboId(0), mRboId(0), mClearColor(0) {} virtual ~CubeMapFBO() {} virtual void onCreate() { CubeMapTexture::onCreate(); // one FBO to rule them all... glGenFramebuffersEXT(1, &mFboId); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId); //Attach one of the faces of the Cubemap texture to this FBO glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, id(), 0); glGenRenderbuffersEXT(1, &mRboId); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRboId); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, mResolution, mResolution); // Attach depth buffer to FBO glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, mRboId); // ...and in the darkness bind them: for (unsigned face=0; face<6; face++) { glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+face, GL_TEXTURE_CUBE_MAP_POSITIVE_X+face, id(), 0); } //Does the GPU support current FBO configuration? GLenum status; status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { printf("GPU does not support required FBO configuration\n"); exit(0); } // cleanup: glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } virtual void onDestroy() { glDeleteRenderbuffersEXT(1, &mRboId); glDeleteFramebuffersEXT(1, &mFboId); mRboId = mFboId = 0; CubeMapTexture::onDestroy(); } void capture(Graphics& gl, const Camera& cam, const Pose& pose, Drawable& draw) { validate(); glPushAttrib(GL_ALL_ATTRIB_BITS); Vec3d pos = pose.pos(); Vec3d ux, uy, uz; pose.unitVectors(ux, uy, uz); mProjection = Matrix4d::perspective(90, 1, cam.near(), cam.far()); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId); for (int face=0; face<6; face++) { glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT+face); gl.viewport(0, 0, resolution(), resolution()); gl.clearColor(clearColor()); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); switch (face) { case 0: // GL_TEXTURE_CUBE_MAP_POSITIVE_X mModelView = Matrix4d::lookAt(uz, uy, -ux, pos); break; case 1: // GL_TEXTURE_CUBE_MAP_NEGATIVE_X mModelView = Matrix4d::lookAt(-uz, uy, ux, pos); break; case 2: // GL_TEXTURE_CUBE_MAP_POSITIVE_Y mModelView = Matrix4d::lookAt(ux, -uz, uy, pos); break; case 3: // GL_TEXTURE_CUBE_MAP_NEGATIVE_Y mModelView = Matrix4d::lookAt(ux, uz, -uy, pos); break; case 4: // GL_TEXTURE_CUBE_MAP_POSITIVE_Z mModelView = Matrix4d::lookAt(ux, uy, uz, pos); break; default: // GL_TEXTURE_CUBE_MAP_NEGATIVE_Z mModelView = Matrix4d::lookAt(-ux, uy, -uz, pos); break; } // apply camera transform: gl.pushMatrix(gl.PROJECTION); gl.loadMatrix(mProjection); gl.pushMatrix(gl.MODELVIEW); gl.loadMatrix(mModelView); draw.onDraw(gl); gl.popMatrix(gl.PROJECTION); gl.popMatrix(gl.MODELVIEW); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glPopAttrib(); } Color clearColor() const { return mClearColor; } Matrix4d projection() const { return mProjection; } Matrix4d modelView() const { return mModelView; } GLuint fbo() { return mFboId; } GLuint rbo() { return mRboId; } CubeMapFBO& clearColor(const Color& c) { mClearColor = c; return *this; } protected: GLuint mFboId, mRboId; Color mClearColor; Matrix4d mProjection; Matrix4d mModelView; }; } // al:: #endif<commit_msg>cubefbo tweak<commit_after>#ifndef INC_AL_UTIL_CUBE_MAP_FBO_HPP #define INC_AL_UTIL_CUBE_MAP_FBO_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: A collection of utilities that are specific to OpenGL File author(s): Graham Wakefield, 2010, grrrwaaa@gmail.com */ #include "allocore/graphics/al_Graphics.hpp" #include "allocore/graphics/al_Lens.hpp" #include "allocore/graphics/al_DisplayList.hpp" #include "alloutil/al_TextureGL.hpp" #include <stdio.h> /*! */ namespace al { class CubeMapFBO : public CubeMapTexture { public: CubeMapFBO(int resolution=1024) : CubeMapTexture(resolution), mFboId(0), mRboId(0), mClearColor(0) {} virtual ~CubeMapFBO() {} virtual void onCreate() { CubeMapTexture::onCreate(); // one FBO to rule them all... glGenFramebuffersEXT(1, &mFboId); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId); //Attach one of the faces of the Cubemap texture to this FBO glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, id(), 0); glGenRenderbuffersEXT(1, &mRboId); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRboId); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, mResolution, mResolution); // Attach depth buffer to FBO glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, mRboId); // ...and in the darkness bind them: for (unsigned face=0; face<6; face++) { glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+face, GL_TEXTURE_CUBE_MAP_POSITIVE_X+face, id(), 0); } //Does the GPU support current FBO configuration? GLenum status; status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { printf("GPU does not support required FBO configuration\n"); exit(0); } // cleanup: glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } virtual void onDestroy() { glDeleteRenderbuffersEXT(1, &mRboId); glDeleteFramebuffersEXT(1, &mFboId); mRboId = mFboId = 0; CubeMapTexture::onDestroy(); } void capture(Graphics& gl, const Lens& cam, const Pose& pose, Drawable& draw) { validate(); glPushAttrib(GL_ALL_ATTRIB_BITS); Vec3d pos = pose.pos(); Vec3d ux, uy, uz; pose.unitVectors(ux, uy, uz); mProjection = Matrix4d::perspective(90, 1, cam.near(), cam.far()); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId); for (int face=0; face<6; face++) { glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT+face); gl.viewport(0, 0, resolution(), resolution()); gl.clearColor(clearColor()); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); switch (face) { case 0: // GL_TEXTURE_CUBE_MAP_POSITIVE_X mModelView = Matrix4d::lookAt(uz, uy, -ux, pos); break; case 1: // GL_TEXTURE_CUBE_MAP_NEGATIVE_X mModelView = Matrix4d::lookAt(-uz, uy, ux, pos); break; case 2: // GL_TEXTURE_CUBE_MAP_POSITIVE_Y mModelView = Matrix4d::lookAt(ux, -uz, uy, pos); break; case 3: // GL_TEXTURE_CUBE_MAP_NEGATIVE_Y mModelView = Matrix4d::lookAt(ux, uz, -uy, pos); break; case 4: // GL_TEXTURE_CUBE_MAP_POSITIVE_Z mModelView = Matrix4d::lookAt(ux, uy, uz, pos); break; default: // GL_TEXTURE_CUBE_MAP_NEGATIVE_Z mModelView = Matrix4d::lookAt(-ux, uy, -uz, pos); break; } // apply camera transform: gl.pushMatrix(gl.PROJECTION); gl.loadMatrix(mProjection); gl.pushMatrix(gl.MODELVIEW); gl.loadMatrix(mModelView); draw.onDraw(gl); gl.popMatrix(gl.PROJECTION); gl.popMatrix(gl.MODELVIEW); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glPopAttrib(); } Color clearColor() const { return mClearColor; } Matrix4d projection() const { return mProjection; } Matrix4d modelView() const { return mModelView; } GLuint fbo() { return mFboId; } GLuint rbo() { return mRboId; } CubeMapFBO& clearColor(const Color& c) { mClearColor = c; return *this; } protected: GLuint mFboId, mRboId; Color mClearColor; Matrix4d mProjection; Matrix4d mModelView; }; } // al:: #endif<|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #include <string> #include <boost/assign.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include <searcher.hpp> std::string path_to_string(Graph::Path_type& path) { std::stringstream s; s << "["; BOOST_FOREACH (Graph::Node_type node, path) { s << node; if (node != path.back()) s << " -> "; } s << "]"; return s.str(); } void check_path(Graph::Path_type& expected_path, Graph::Path_type &path) { BOOST_REQUIRE_EQUAL(expected_path.size(), path.size()); for (unsigned int i = 0; i < expected_path.size(); i++) if (expected_path.at(i) != path.at(i)) BOOST_FAIL("Incorrect path: Expected " << path_to_string(expected_path) << " but got " << path_to_string(path) << "."); } struct Small_graph { Small_graph() { using namespace boost::assign; graph[1] = list_of(2)(3); graph[2] = list_of(1)(4); graph[3] = list_of(1)(6); graph[4] = list_of(2)(5)(6); graph[5] = list_of(4); graph[6] = list_of(3)(4)(7); graph[7] = list_of(6); } ~Small_graph() {} Graph::Graph_type graph; }; struct Large_graph { Large_graph() { using namespace boost::assign; graph[1] = list_of(2)(3)(5)(6)(9); graph[2] = list_of(1)(4)(5)(10); graph[3] = list_of(1)(4)(7); graph[4] = list_of(2)(3)(5)(8)(10); graph[5] = list_of(1)(2)(4); graph[6] = list_of(1)(9); graph[7] = list_of(3)(8)(16); graph[8] = list_of(4)(7); graph[9] = list_of(1)(6)(11); graph[10] = list_of(2)(4)(13); graph[11] = list_of(9)(14); graph[12] = list_of(8)(14)(15); graph[13] = list_of(10); graph[14] = list_of(11)(12); graph[15] = list_of(12); graph[16] = list_of(7); } ~Large_graph() {} Graph::Graph_type graph; }; BOOST_FIXTURE_TEST_CASE(test_simple_path, Small_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(1, 7, 5); BOOST_REQUIRE_MESSAGE(path.size() > 0, "No path was found."); using namespace boost::assign; Graph::Path_type expected_path = list_of(1)(3)(6)(7); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_impossible_path, Small_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(1, 1000, 5); BOOST_REQUIRE_MESSAGE(path.size() == 0, "A path was found, although there can't be one."); } BOOST_FIXTURE_TEST_CASE(test_complex1, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(15, 16, 5); using namespace boost::assign; Graph::Path_type expected_path = list_of(15)(12)(8)(7)(16); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_complex2, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(1, 14, 5); using namespace boost::assign; Graph::Path_type expected_path = list_of(1)(9)(11)(14); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_complex3, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(13, 5, 5); using namespace boost::assign; Graph::Path_type expected_path = list_of(13)(10)(2)(5); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_complex4, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(2, 14, 5); using namespace boost::assign; // 2 -> 4 -> 8 -> 12 -> 14 would be correct as well Graph::Path_type expected_path = list_of(2)(1)(9)(11)(14); check_path(expected_path, path); } <commit_msg>Refactored searcher test case.<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #include <string> #include <boost/assign.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include <searcher.hpp> std::string path_to_string(Graph::Path_type& path) { std::stringstream s; s << "["; BOOST_FOREACH (Graph::Node_type node, path) { s << node; if (node != path.back()) s << " -> "; } s << "]"; return s.str(); } void check_path(Graph::Path_type& expected_path, Graph::Path_type &path) { BOOST_REQUIRE_EQUAL(expected_path.size(), path.size()); for (unsigned int i = 0; i < expected_path.size(); i++) if (expected_path.at(i) != path.at(i)) BOOST_FAIL("Incorrect path: Expected " << path_to_string(expected_path) << " but got " << path_to_string(path) << "."); } struct Small_graph { Graph::Graph_type graph; Small_graph() { using namespace boost::assign; graph[1] = list_of(2)(3); graph[2] = list_of(1)(4); graph[3] = list_of(1)(6); graph[4] = list_of(2)(5)(6); graph[5] = list_of(4); graph[6] = list_of(3)(4)(7); graph[7] = list_of(6); } }; struct Large_graph { Graph::Graph_type graph; Large_graph() { using namespace boost::assign; graph[1] = list_of(2)(3)(5)(6)(9); graph[2] = list_of(1)(4)(5)(10); graph[3] = list_of(1)(4)(7); graph[4] = list_of(2)(3)(5)(8)(10); graph[5] = list_of(1)(2)(4); graph[6] = list_of(1)(9); graph[7] = list_of(3)(8)(16); graph[8] = list_of(4)(7); graph[9] = list_of(1)(6)(11); graph[10] = list_of(2)(4)(13); graph[11] = list_of(9)(14); graph[12] = list_of(8)(14)(15); graph[13] = list_of(10); graph[14] = list_of(11)(12); graph[15] = list_of(12); graph[16] = list_of(7); } }; BOOST_FIXTURE_TEST_CASE(test_simple_path, Small_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(1, 7, 5); BOOST_REQUIRE_MESSAGE(path.size() > 0, "No path was found."); using namespace boost::assign; Graph::Path_type expected_path = list_of(1)(3)(6)(7); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_impossible_path, Small_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(1, 1000, 5); BOOST_REQUIRE_MESSAGE(path.size() == 0, "A path was found, although there can't be one."); } BOOST_FIXTURE_TEST_CASE(test_complex1, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(15, 16, 5); using namespace boost::assign; Graph::Path_type expected_path = list_of(15)(12)(8)(7)(16); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_complex2, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(1, 14, 5); using namespace boost::assign; Graph::Path_type expected_path = list_of(1)(9)(11)(14); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_complex3, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(13, 5, 5); using namespace boost::assign; Graph::Path_type expected_path = list_of(13)(10)(2)(5); check_path(expected_path, path); } BOOST_FIXTURE_TEST_CASE(test_complex4, Large_graph) { Searcher s(graph); Graph::Path_type path = s.find_shortest_path(2, 14, 5); using namespace boost::assign; // 2 -> 4 -> 8 -> 12 -> 14 would be correct as well Graph::Path_type expected_path = list_of(2)(1)(9)(11)(14); check_path(expected_path, path); } <|endoftext|>
<commit_before>#include "eventblock.h" #include <ctime> #include <iostream> #include <cstdlib> using namespace std; // Constructor & Destructor EventBlock::EventBlock(QGameItem * parent) : Block(parent) { } EventBlock::~EventBlock() { } // Methods void EventBlock::enter(Player* player) { } void EventBlock::checkEvent(Player* player) { // 이벤트 블럭을 밟을시 실행하여 랜덤한 이벤트 발생 srand((unsigned)time(NULL)); int value = rand() % 7; switch(value) { case 0: drink(player); break; case 1: cc(player); break; case 2: takeSubject(player); break; case 3: loseSubject(player); break; case 4: lol(player); break; case 5: eatChicken(player); break; case 6: photoGenic(); break; } } //전체적으로 수정 바람. void EventBlock::drink(Player* player) { // 음주칸으로 이동 player->setEnergy(player->getEnergy() - 100); // } void EventBlock::cc(Player* player) { // 행동력 감소 + 일정 확률로 휴학 또는 61콜 이동 if(getType()!=CharacterType::OUTSIDER) { player->setEnergy(player->getEnergy() - 100); // } } void EventBlock::takeSubject(Player* player) { // 플레이어가 과목을 하나 선택한 후 buyBlock을 실행한다 //player->buyBlock(); } void EventBlock::loseSubject(Player* player) { // 플레이어가 과목 하나를 잃는다. (랜덤 or 선택) //player->sellBlock(); } void EventBlock::lol(Player* player) { // 50:50으로 행동력 증가 또는 감소, lol타입 캐릭터의 경우 항상 증가 if(getType()==CharacterType::LOL) player->setEnergy(player->getEnergy() +50); // else { int outcome; outcome=rand()%2; if(outcome==0) player->setEnergy(player->getEnergy()+50); else player->setEnergy(player->getEnergy()-100); } } void EventBlock::eatChicken(Player* player) { // 치느님을 영접하여 행동력 증가 player->setEnergy(player->getEnergy() + 100); } void EventBlock::photoGenic() { //팀원 사진 띄우기 } <commit_msg>CC does not neded pay for itself / drink need fix<commit_after>#include "eventblock.h" #include <ctime> #include <iostream> #include <cstdlib> using namespace std; // Constructor & Destructor EventBlock::EventBlock(QGameItem * parent) : Block(parent) { } EventBlock::~EventBlock() { } // Methods void EventBlock::enter(Player* player) { } void EventBlock::checkEvent(Player* player) { // 이벤트 블럭을 밟을시 실행하여 랜덤한 이벤트 발생 srand((unsigned)time(NULL)); int value = rand() % 7; switch(value) { case 0: drink(player); break; case 1: cc(player); break; case 2: takeSubject(player); break; case 3: loseSubject(player); break; case 4: lol(player); break; case 5: eatChicken(player); break; case 6: photoGenic(); break; } } //전체적으로 수정 바람. void EventBlock::drink(Player* player) { // 음주칸으로 이동 player->setEnergy(player->getEnergy() - 100); // } void EventBlock::cc(Player* player) { // 행동력 감소 + 일정 확률로 휴학 또는 61콜 이동 if(getType()!=CharacterType::OUTSIDER) { } } void EventBlock::takeSubject(Player* player) { // 플레이어가 과목을 하나 선택한 후 buyBlock을 실행한다 //player->buyBlock(); } void EventBlock::loseSubject(Player* player) { // 플레이어가 과목 하나를 잃는다. (랜덤 or 선택) //player->sellBlock(); } void EventBlock::lol(Player* player) { // 50:50으로 행동력 증가 또는 감소, lol타입 캐릭터의 경우 항상 증가 if(getType()==CharacterType::LOL) player->setEnergy(player->getEnergy() +50); // else { int outcome; outcome=rand()%2; if(outcome==0) player->setEnergy(player->getEnergy()+50); else player->setEnergy(player->getEnergy()-100); } } void EventBlock::eatChicken(Player* player) { // 치느님을 영접하여 행동력 증가 player->setEnergy(player->getEnergy() + 100); } void EventBlock::photoGenic() { //팀원 사진 띄우기 } <|endoftext|>
<commit_before>// Copyright (C) 2010-2014 Joshua Boyce. // See the file COPYING for copying permission. #pragma once #include <type_traits> #include <utility> #include <hadesmem/config.hpp> namespace hadesmem { namespace detail { template <typename T> class Optional { public: HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT { } explicit Optional(T const& t) { Construct(t); } explicit Optional(T&& t) { Construct(std::move(t)); } Optional(Optional const& other) { if (other.valid_) { Construct(other.Get()); } } Optional& operator=(Optional const& other) { Optional tmp{other}; *this = std::move(tmp); return *this; } Optional(Optional&& other) { if (other.valid_) { Construct(std::move(other.Get())); } other.valid_ = false; } Optional& operator=(Optional&& other) { Destroy(); if (other.valid_) { Construct(std::move(other.Get())); } other.valid_ = false; return *this; } Optional& operator=(T const& t) { Destroy(); Construct(t); return *this; } Optional& operator=(T&& t) { Destroy(); Construct(std::move(t)); return *this; } ~Optional() { Destroy(); } explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT { return valid_; } T& Get() HADESMEM_DETAIL_NOEXCEPT { return *GetPtr(); } T const& Get() const HADESMEM_DETAIL_NOEXCEPT { return *GetPtr(); } T& operator*() HADESMEM_DETAIL_NOEXCEPT { return Get(); } T const& operator*() const HADESMEM_DETAIL_NOEXCEPT { return Get(); } T* GetPtr() HADESMEM_DETAIL_NOEXCEPT { return static_cast<T*>(static_cast<void*>(&t_)); } T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT { return static_cast<T const*>(static_cast<void const*>(&t_)); } T* operator->() HADESMEM_DETAIL_NOEXCEPT { return GetPtr(); } T const* operator->() const HADESMEM_DETAIL_NOEXCEPT { return GetPtr(); } private: template <typename U> void Construct(U&& u) { if (valid_) { Destroy(); } new (&t_) T(std::forward<U>(u)); valid_ = true; } void Destroy() HADESMEM_DETAIL_NOEXCEPT { if (valid_) { GetPtr()->~T(); valid_ = false; } } std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_{}; bool valid_{false}; }; template <typename T> inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs) { return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs); } template <typename T> inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs) { return !(lhs == rhs); } template <typename T> inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs) { return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs); } } } <commit_msg>* [Optional] Avoid new overloads.<commit_after>// Copyright (C) 2010-2014 Joshua Boyce. // See the file COPYING for copying permission. #pragma once #include <type_traits> #include <utility> #include <hadesmem/config.hpp> namespace hadesmem { namespace detail { template <typename T> class Optional { public: HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT { } explicit Optional(T const& t) { Construct(t); } explicit Optional(T&& t) { Construct(std::move(t)); } Optional(Optional const& other) { if (other.valid_) { Construct(other.Get()); } } Optional& operator=(Optional const& other) { Optional tmp{other}; *this = std::move(tmp); return *this; } Optional(Optional&& other) { if (other.valid_) { Construct(std::move(other.Get())); } other.valid_ = false; } Optional& operator=(Optional&& other) { Destroy(); if (other.valid_) { Construct(std::move(other.Get())); } other.valid_ = false; return *this; } Optional& operator=(T const& t) { Destroy(); Construct(t); return *this; } Optional& operator=(T&& t) { Destroy(); Construct(std::move(t)); return *this; } ~Optional() { Destroy(); } explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT { return valid_; } T& Get() HADESMEM_DETAIL_NOEXCEPT { return *GetPtr(); } T const& Get() const HADESMEM_DETAIL_NOEXCEPT { return *GetPtr(); } T& operator*() HADESMEM_DETAIL_NOEXCEPT { return Get(); } T const& operator*() const HADESMEM_DETAIL_NOEXCEPT { return Get(); } T* GetPtr() HADESMEM_DETAIL_NOEXCEPT { return static_cast<T*>(static_cast<void*>(&t_)); } T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT { return static_cast<T const*>(static_cast<void const*>(&t_)); } T* operator->() HADESMEM_DETAIL_NOEXCEPT { return GetPtr(); } T const* operator->() const HADESMEM_DETAIL_NOEXCEPT { return GetPtr(); } private: template <typename U> void Construct(U&& u) { if (valid_) { Destroy(); } // Avoid picking up placement new overloads ::new (static_cast<void*>(&t_)) T(std::forward<U>(u)); valid_ = true; } void Destroy() HADESMEM_DETAIL_NOEXCEPT { if (valid_) { GetPtr()->~T(); valid_ = false; } } std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_{}; bool valid_{false}; }; template <typename T> inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs) { return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs); } template <typename T> inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs) { return !(lhs == rhs); } template <typename T> inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs) { return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs); } } } <|endoftext|>
<commit_before>/** * response_status.hpp * * Created on: 28 авг. 2015 г. * Author: zmij */ #ifndef TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ #define TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ namespace tip { namespace http { /** The status of the reply. * [RFC 2616 Fielding, et al.](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) */ enum class response_status { /** Informational */ continue_ = 100, switching_protocols = 101, /** Successful */ ok = 200, created = 201, accepted = 202, non_authoritative_information = 203, no_content = 204, reset_content = 205, partial_content = 206, /** Redirection */ multiple_choices = 300, moved_permanently = 301, found = 302, see_other = 303, not_modified = 304, use_proxy = 305, temporary_redirect = 307, /** Client error */ bad_request = 400, unauthorized = 401, payment_required = 402, forbidden = 403, not_found = 404, method_not_allowed = 405, not_acceptable = 406, proxy_authentication_required = 407, request_timeout = 408, conflict = 409, gone = 410, length_required = 411, precondition_failed = 412, request_entity_too_large = 413, request_uri_too_long = 414, unsupported_media_type = 415, requested_range_not_satisfiable = 416, expectation_failed = 417, /** Server error */ internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503, gateway_timeout = 504, http_version_not_supported = 505 }; // enum response_status enum class response_class { informational = 0x01, successful = 0x02, redirection = 0x04, client_error = 0x08, server_error = 0x10 }; inline response_class status_class(response_status s) { return static_cast< response_class >( static_cast< int >(s) / 100 ); } inline bool is_error(response_status s) { return static_cast< int >(s) / 100 >= 4; } inline bool is_error(response_class c) { return c >= response_class::client_error; } inline ::std::ostream& operator << (::std::ostream& os, response_status const& val) { std::ostream::sentry s(os); if (s) { os << static_cast<int>(val); } return os; } } // namespace http } // namespace tip #endif /* TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ */ <commit_msg>Fix missing include<commit_after>/** * response_status.hpp * * Created on: 28 авг. 2015 г. * Author: zmij */ #ifndef TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ #define TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ #include <iostream> namespace tip { namespace http { /** The status of the reply. * [RFC 2616 Fielding, et al.](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) */ enum class response_status { /** Informational */ continue_ = 100, switching_protocols = 101, /** Successful */ ok = 200, created = 201, accepted = 202, non_authoritative_information = 203, no_content = 204, reset_content = 205, partial_content = 206, /** Redirection */ multiple_choices = 300, moved_permanently = 301, found = 302, see_other = 303, not_modified = 304, use_proxy = 305, temporary_redirect = 307, /** Client error */ bad_request = 400, unauthorized = 401, payment_required = 402, forbidden = 403, not_found = 404, method_not_allowed = 405, not_acceptable = 406, proxy_authentication_required = 407, request_timeout = 408, conflict = 409, gone = 410, length_required = 411, precondition_failed = 412, request_entity_too_large = 413, request_uri_too_long = 414, unsupported_media_type = 415, requested_range_not_satisfiable = 416, expectation_failed = 417, /** Server error */ internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503, gateway_timeout = 504, http_version_not_supported = 505 }; // enum response_status enum class response_class { informational = 0x01, successful = 0x02, redirection = 0x04, client_error = 0x08, server_error = 0x10 }; inline response_class status_class(response_status s) { return static_cast< response_class >( static_cast< int >(s) / 100 ); } inline bool is_error(response_status s) { return static_cast< int >(s) / 100 >= 4; } inline bool is_error(response_class c) { return c >= response_class::client_error; } inline ::std::ostream& operator << (::std::ostream& os, response_status const& val) { std::ostream::sentry s(os); if (s) { os << static_cast<int>(val); } return os; } } // namespace http } // namespace tip #endif /* TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ */ <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstddef> #include <type_traits> #include <utility> #include <visionaray/math/limits.h> #include <visionaray/math/ray.h> #include <visionaray/intersector.h> #include <visionaray/update_if.h> #include "../exit_traversal.h" #include "../multi_hit.h" #include "../stack.h" #include "../tags.h" #include "../traversal_result.h" #include "hit_record.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // Ray / BVH intersection // template < detail::traversal_type Traversal, size_t MultiHitMax = 1, // Max hits for multi-hit traversal typename T, typename BVH, typename = typename std::enable_if<is_any_bvh<BVH>::value>::type, typename Intersector, typename Cond = is_closer_t > VSNRAY_FUNC inline auto intersect( basic_ray<T> const& ray, BVH const& b, Intersector& isect, T max_t = numeric_limits<T>::max(), Cond update_cond = Cond() ) -> typename detail::traversal_result< hit_record_bvh< basic_ray<T>, decltype( isect(ray, std::declval<typename BVH::primitive_type>()) ) >, Traversal, MultiHitMax>::type { using namespace detail; using HR = hit_record_bvh< basic_ray<T>, decltype( isect(ray, std::declval<typename BVH::primitive_type>()) ) >; using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type; RT result; stack<64> st; st.push(0); // address of root node auto inv_dir = T(1.0) / ray.dir; // while ray not terminated next: while (!st.empty()) { auto node = b.node(st.pop()); // while node does not contain primitives // traverse to the next node while (!is_leaf(node)) { auto children = &b.node(node.get_child(0)); auto hr1 = isect(ray, children[0].get_bounds(), inv_dir); auto hr2 = isect(ray, children[1].get_bounds(), inv_dir); auto b1 = any( is_closer(hr1, result, max_t) ); auto b2 = any( is_closer(hr2, result, max_t) ); if (b1 && b2) { unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1; st.push(node.get_child(!near_addr)); node = b.node(node.get_child(near_addr)); } else if (b1) { node = b.node(node.get_child(0)); } else if (b2) { node = b.node(node.get_child(1)); } else { goto next; } } // while node contains untested primitives // perform a ray-primitive intersection test for (auto i = node.get_indices().first; i != node.get_indices().last; ++i) { auto prim = b.primitive(i); auto hr = HR(isect(ray, prim), i); auto closer = update_cond(hr, result, max_t); #ifndef __CUDA_ARCH__ if (!any(closer)) { continue; } #endif update_if(result, hr, closer); exit_traversal<Traversal> early_exit; if (early_exit.check(result)) { return result; } } } return result; } //------------------------------------------------------------------------------------------------- // Default intersect returns closest hit! // // overload w/ custom intersector ------------------------- template < typename T, typename BVH, typename = typename std::enable_if<is_any_bvh<BVH>::value>::type, typename Intersector, typename Cond = is_closer_t > VSNRAY_FUNC inline auto intersect( basic_ray<T> const& ray, BVH const& b, Intersector& isect, Cond update_cond = Cond() ) -> hit_record_bvh< basic_ray<T>, decltype( isect(ray, std::declval<typename BVH::primitive_type>()) ) > { return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond); } // overload w/ default intersector ------------------------ template < typename T, typename BVH, typename = typename std::enable_if<is_any_bvh<BVH>::value>::type, typename Cond = is_closer_t > VSNRAY_FUNC inline auto intersect( basic_ray<T> const& ray, BVH const& b, Cond update_cond = Cond() ) -> hit_record_bvh< basic_ray<T>, decltype( intersect(ray, std::declval<typename BVH::primitive_type>()) ) > { default_intersector isect; return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond); } } // visionaray <commit_msg>Revert "Use a 64 entry stack for BVH traversal"<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstddef> #include <type_traits> #include <utility> #include <visionaray/math/limits.h> #include <visionaray/math/ray.h> #include <visionaray/intersector.h> #include <visionaray/update_if.h> #include "../exit_traversal.h" #include "../multi_hit.h" #include "../stack.h" #include "../tags.h" #include "../traversal_result.h" #include "hit_record.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // Ray / BVH intersection // template < detail::traversal_type Traversal, size_t MultiHitMax = 1, // Max hits for multi-hit traversal typename T, typename BVH, typename = typename std::enable_if<is_any_bvh<BVH>::value>::type, typename Intersector, typename Cond = is_closer_t > VSNRAY_FUNC inline auto intersect( basic_ray<T> const& ray, BVH const& b, Intersector& isect, T max_t = numeric_limits<T>::max(), Cond update_cond = Cond() ) -> typename detail::traversal_result< hit_record_bvh< basic_ray<T>, decltype( isect(ray, std::declval<typename BVH::primitive_type>()) ) >, Traversal, MultiHitMax>::type { using namespace detail; using HR = hit_record_bvh< basic_ray<T>, decltype( isect(ray, std::declval<typename BVH::primitive_type>()) ) >; using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type; RT result; stack<32> st; st.push(0); // address of root node auto inv_dir = T(1.0) / ray.dir; // while ray not terminated next: while (!st.empty()) { auto node = b.node(st.pop()); // while node does not contain primitives // traverse to the next node while (!is_leaf(node)) { auto children = &b.node(node.get_child(0)); auto hr1 = isect(ray, children[0].get_bounds(), inv_dir); auto hr2 = isect(ray, children[1].get_bounds(), inv_dir); auto b1 = any( is_closer(hr1, result, max_t) ); auto b2 = any( is_closer(hr2, result, max_t) ); if (b1 && b2) { unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1; st.push(node.get_child(!near_addr)); node = b.node(node.get_child(near_addr)); } else if (b1) { node = b.node(node.get_child(0)); } else if (b2) { node = b.node(node.get_child(1)); } else { goto next; } } // while node contains untested primitives // perform a ray-primitive intersection test for (auto i = node.get_indices().first; i != node.get_indices().last; ++i) { auto prim = b.primitive(i); auto hr = HR(isect(ray, prim), i); auto closer = update_cond(hr, result, max_t); #ifndef __CUDA_ARCH__ if (!any(closer)) { continue; } #endif update_if(result, hr, closer); exit_traversal<Traversal> early_exit; if (early_exit.check(result)) { return result; } } } return result; } //------------------------------------------------------------------------------------------------- // Default intersect returns closest hit! // // overload w/ custom intersector ------------------------- template < typename T, typename BVH, typename = typename std::enable_if<is_any_bvh<BVH>::value>::type, typename Intersector, typename Cond = is_closer_t > VSNRAY_FUNC inline auto intersect( basic_ray<T> const& ray, BVH const& b, Intersector& isect, Cond update_cond = Cond() ) -> hit_record_bvh< basic_ray<T>, decltype( isect(ray, std::declval<typename BVH::primitive_type>()) ) > { return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond); } // overload w/ default intersector ------------------------ template < typename T, typename BVH, typename = typename std::enable_if<is_any_bvh<BVH>::value>::type, typename Cond = is_closer_t > VSNRAY_FUNC inline auto intersect( basic_ray<T> const& ray, BVH const& b, Cond update_cond = Cond() ) -> hit_record_bvh< basic_ray<T>, decltype( intersect(ray, std::declval<typename BVH::primitive_type>()) ) > { default_intersector isect; return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond); } } // visionaray <|endoftext|>
<commit_before>/** * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/bitcoin/utility/path.hpp> #include <boost/thread/once.hpp> #ifdef _WIN32 #include <Shlobj.h> #endif namespace libbitcoin{ const boost::filesystem::path& default_data_path() { static boost::filesystem::path default_path(""); static boost::once_flag once = BOOST_ONCE_INIT; auto path_init = []() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\Metaverse // Windows >= Vista: C:\Users\Username\AppData\Roaming\Metaverse // Mac: ~/Library/Application Support/Metaverse // Unix: ~/.metaverse #ifdef _WIN32 // Windows #ifdef UNICODE wchar_t file_path[MAX_PATH] = { 0 }; #else char file_path[MAX_PATH] = { 0 }; #endif SHGetSpecialFolderPath(NULL, file_path, CSIDL_APPDATA, true); fs::path pathRet = boost::filesystem::path(file_path) / "Metaverse"; fs::create_directories(pathRet); default_path = pathRet; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == nullptr || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; fs::create_directories(pathRet / "Metaverse"); default_path = pathRet / "Metaverse"; #else // Unix fs::create_directories(pathRet / ".metaverse"); default_path = pathRet / ".metaverse"; #endif #endif }; boost::call_once(path_init, once); return default_path; } boost::filesystem::path webpage_path() { return default_data_path() / "mvs-htmls"; } }//namespace libbitcoin <commit_msg>#139 modify windows webpath dir<commit_after>/** * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/bitcoin/utility/path.hpp> #include <boost/thread/once.hpp> #ifdef _WIN32 #include <Shlobj.h> #endif namespace libbitcoin{ const boost::filesystem::path& default_data_path() { static boost::filesystem::path default_path(""); static boost::once_flag once = BOOST_ONCE_INIT; auto path_init = []() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\Metaverse // Windows >= Vista: C:\Users\Username\AppData\Roaming\Metaverse // Mac: ~/Library/Application Support/Metaverse // Unix: ~/.metaverse #ifdef _WIN32 // Windows #ifdef UNICODE wchar_t file_path[MAX_PATH] = { 0 }; #else char file_path[MAX_PATH] = { 0 }; #endif SHGetSpecialFolderPath(NULL, file_path, CSIDL_APPDATA, true); fs::path pathRet = boost::filesystem::path(file_path) / "Metaverse"; fs::create_directories(pathRet); default_path = pathRet; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == nullptr || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; fs::create_directories(pathRet / "Metaverse"); default_path = pathRet / "Metaverse"; #else // Unix fs::create_directories(pathRet / ".metaverse"); default_path = pathRet / ".metaverse"; #endif #endif }; boost::call_once(path_init, once); return default_path; } boost::filesystem::path webpage_path() { #ifdef _MSC_VER return "./mvs-htmls"; #else return default_data_path() / "mvs-htmls"; #endif } }//namespace libbitcoin <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Piotr Korzuszek * 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 <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Properties.h" #include "common.h" std::map<CL_String, CL_String> Properties::m_keyValueMap; const char* FILENAME = "gear.cfg"; Properties::Properties() { } Properties::~Properties() { } void Properties::load() { try { CL_File file(FILENAME, CL_File::open_existing, CL_File::access_read); CL_DataBuffer buffer(file.get_size()); file.read(buffer.get_data(), buffer.get_size()); file.close(); const std::vector<CL_TempString> lines = CL_StringHelp::split_text(buffer.get_data(), END_OF_LINE, true); const int linesCount = static_cast<signed>(lines.size()); std::vector<CL_TempString> parts; for (int i = 0; i < linesCount; ++i) { parts = CL_StringHelp::split_text(lines[i], "=", false); if (parts.size() == 2) { const CL_TempString left = CL_StringHelp::trim(parts[0]); const CL_TempString right = CL_StringHelp::trim(parts[1]); Properties::setProperty(left, right); cl_log_event(LOG_DEBUG, "Option '%1' set to '%2'", left, right); } else { cl_log_event(LOG_DEBUG, "Cannot parse line: %1", lines[i]); } } } catch (CL_Exception &e) { cl_log_event(LOG_DEBUG, "File %1 cannot be read: %2", FILENAME, e.message); } } void Properties::save() { try { CL_File file(FILENAME, CL_File::create_always, CL_File::access_write); std::pair<CL_String, CL_String> pair; CL_String line; foreach(pair, m_keyValueMap) { line = cl_format("%1 = %2%3", pair.first, pair.second, END_OF_LINE); file.write(line.c_str(), line.length()); cl_log_event(LOG_DEBUG, "Option '%1' saved with value '%2'", pair.first, pair.second); } file.close(); } catch (CL_Exception &e) { cl_log_event(LOG_DEBUG, "File %1 cannot be written: %2", FILENAME, e.message); } } void Properties::setProperty(const CL_String &p_key, bool p_value) { setProperty(p_key, CL_StringHelp::bool_to_local8(p_value)); } void Properties::setProperty(const CL_String &p_key, int p_value) { setProperty(p_key, CL_StringHelp::int_to_local8(p_value)); } void Properties::setProperty(const CL_String &p_key, const CL_String &p_value) { m_keyValueMap[p_key] = p_value; } bool Properties::getPropertyAsBool(const CL_String &p_key, bool p_defaultValue) { return CL_StringHelp::local8_to_bool(getPropertyAsString(p_key, CL_StringHelp::bool_to_local8(p_defaultValue))); } int Properties::getPropertyAsInt(const CL_String &p_key, int p_defaultValue) { return CL_StringHelp::local8_to_int(getPropertyAsString(p_key, CL_StringHelp::int_to_local8(p_defaultValue))); } CL_String Properties::getPropertyAsString(const CL_String &p_key, const CL_String &defaultValue) { if (m_keyValueMap.find(p_key) != m_keyValueMap.end()) { return m_keyValueMap[p_key]; } else { return defaultValue; } } <commit_msg>Fix to Win32 empty properties loading bug<commit_after>/* * Copyright (c) 2009-2010, Piotr Korzuszek * 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 <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Properties.h" #include "common.h" std::map<CL_String, CL_String> Properties::m_keyValueMap; const char* FILENAME = "gear.cfg"; Properties::Properties() { } Properties::~Properties() { } void Properties::load() { try { CL_File file(FILENAME, CL_File::open_existing, CL_File::access_read); CL_DataBuffer buffer(file.get_size()); file.read(buffer.get_data(), buffer.get_size()); file.close(); if (buffer.get_size() != 0) { const std::vector<CL_TempString> lines = CL_StringHelp::split_text(buffer.get_data(), END_OF_LINE, true); const int linesCount = static_cast<signed>(lines.size()); std::vector<CL_TempString> parts; for (int i = 0; i < linesCount; ++i) { parts = CL_StringHelp::split_text(lines[i], "=", false); if (parts.size() == 2) { const CL_TempString left = CL_StringHelp::trim(parts[0]); const CL_TempString right = CL_StringHelp::trim(parts[1]); Properties::setProperty(left, right); cl_log_event(LOG_DEBUG, "Option '%1' set to '%2'", left, right); } else { cl_log_event(LOG_DEBUG, "Cannot parse line: %1", lines[i]); } } } } catch (CL_Exception &e) { cl_log_event(LOG_DEBUG, "File %1 cannot be read: %2", FILENAME, e.message); } } void Properties::save() { try { CL_File file(FILENAME, CL_File::create_always, CL_File::access_write); std::pair<CL_String, CL_String> pair; CL_String line; foreach(pair, m_keyValueMap) { line = cl_format("%1 = %2%3", pair.first, pair.second, END_OF_LINE); file.write(line.c_str(), line.length()); cl_log_event(LOG_DEBUG, "Option '%1' saved with value '%2'", pair.first, pair.second); } file.close(); } catch (CL_Exception &e) { cl_log_event(LOG_DEBUG, "File %1 cannot be written: %2", FILENAME, e.message); } } void Properties::setProperty(const CL_String &p_key, bool p_value) { setProperty(p_key, CL_StringHelp::bool_to_local8(p_value)); } void Properties::setProperty(const CL_String &p_key, int p_value) { setProperty(p_key, CL_StringHelp::int_to_local8(p_value)); } void Properties::setProperty(const CL_String &p_key, const CL_String &p_value) { m_keyValueMap[p_key] = p_value; } bool Properties::getPropertyAsBool(const CL_String &p_key, bool p_defaultValue) { return CL_StringHelp::local8_to_bool(getPropertyAsString(p_key, CL_StringHelp::bool_to_local8(p_defaultValue))); } int Properties::getPropertyAsInt(const CL_String &p_key, int p_defaultValue) { return CL_StringHelp::local8_to_int(getPropertyAsString(p_key, CL_StringHelp::int_to_local8(p_defaultValue))); } CL_String Properties::getPropertyAsString(const CL_String &p_key, const CL_String &defaultValue) { if (m_keyValueMap.find(p_key) != m_keyValueMap.end()) { return m_keyValueMap[p_key]; } else { return defaultValue; } } <|endoftext|>
<commit_before>// SafeArryGUID.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <objbase.h> #include <string> #include<atlsafe.h> #include<iostream> using namespace std; string GuidToString(const GUID &guid) { char buf[64] = { 0 }; sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); return string(buf); } void Put1GuidInSafeArry() { GUID guid; CoCreateGuid(&guid); auto guidStri = GuidToString(guid); cout << guidStri << endl; //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; auto guidsize = sizeof(GUID); safe_arry_bound[0].cElements = guidsize; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = guidsize; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound); auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData); memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize); //TODO... //do something.. SafeArrayDestroy(p_safe_arry); } void Put2GuidInSafeArry() { GUID guid, guid2; CoCreateGuid(&guid); CoCreateGuid(&guid2); //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; safe_arry_bound[0].cElements = 2; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = 16; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound); auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData); pnData[0] = guid; pnData[1] = guid2; //TODO... //do something.. //TODO... SafeArrayDestroy(p_safe_arry); } void Put1GuidInSafeArryByStack() { GUID guid; //TODO... put the guid into safearry.. SAFEARRAY* pArray = nullptr; auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray); pArray->cbElements = sizeof(GUID); pArray->rgsabound[0].cElements = 1; pArray->rgsabound[0].lLbound = 16; pArray->pvData = &guid; pArray->fFeatures = FADF_AUTO; //_bstr_t bstr; } void CComSafeArrayGUID() { //CComSafeArray<GUID> comsafeguid(10); } void LearnSafeArray() { SAFEARRAY *pArray = nullptr; HRESULT hr = SafeArrayAllocDescriptor(1, &pArray);//SAFEARRAYṹĶ pArray->cbElements = sizeof(GUID); pArray->rgsabound[0].cElements = 10; pArray->rgsabound[0].lLbound = 0; GUID guid, guid2; CoCreateGuid(&guid); CoCreateGuid(&guid2); GUID _guidarr[] = { guid,guid2 }; pArray->pvData = _guidarr; pArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE; //CComSafeArray<VARIANT> saguid; // saguid.Attach(pArray); //auto count = saguid.GetCount(); //auto t = saguid.GetType(); GUID* p_GUIDArry = nullptr; SafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry); auto retv = p_GUIDArry[0]; auto retv1 = p_GUIDArry[1]; long Low(0), High(0); hr = SafeArrayGetLBound(pArray, 1, &Low);//ά1ʼ hr = SafeArrayGetUBound(pArray, 1, &High);//ά1ʼ cin.get(); } void TestSafeArry() { LearnSafeArray(); //CComSafeArrayBound bound(2); //CComSafeArray<GUID> guid_Array; //GUID guid, guid2; //CoCreateGuid(&guid); //CoCreateGuid(&guid2); //guid_Array.Add(guid); //guid_Array.Add(guid2); //auto count = guid_Array.GetCount(); //auto demention = guid_Array.GetDimensions(); //auto upperbound = guid_Array.GetUpperBound(); //auto p_safeArry = &guid_Array; //GUID guid3; //CoCreateGuid(&guid3); //p_safeArry->SetAt(1, guid3); } int _tmain(int argc, _TCHAR* argv[]) { TestSafeArry(); Put1GuidInSafeArry(); Put2GuidInSafeArry(); Put1GuidInSafeArryByStack(); return 0; }<commit_msg>update using .<commit_after>// SafeArryGUID.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <objbase.h> #include <string> #include<atlsafe.h> #include<iostream> using namespace std; string GuidToString(const GUID &guid) { char buf[64] = { 0 }; sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); return string(buf); } void Put1GuidInSafeArry() { GUID guid; CoCreateGuid(&guid); auto guidStri = GuidToString(guid); cout << guidStri << endl; //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; auto guidsize = sizeof(GUID); safe_arry_bound[0].cElements = guidsize; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = guidsize; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound); auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData); memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize); //TODO... //do something.. SafeArrayDestroy(p_safe_arry); } void Put2GuidInSafeArry() { GUID guid, guid2; CoCreateGuid(&guid); CoCreateGuid(&guid2); //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; safe_arry_bound[0].cElements = 2; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = 16; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound); auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData); pnData[0] = guid; pnData[1] = guid2; //TODO... //do something.. //TODO... SafeArrayDestroy(p_safe_arry); } void Put1GuidInSafeArryByStack() { GUID guid; //TODO... put the guid into safearry.. SAFEARRAY* pArray = nullptr; auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray); pArray->cbElements = sizeof(GUID); pArray->rgsabound[0].cElements = 1; pArray->rgsabound[0].lLbound = 16; pArray->pvData = &guid; pArray->fFeatures = FADF_AUTO; //_bstr_t bstr; } void CComSafeArrayGUID() { //CComSafeArray<GUID> comsafeguid(10); } void LearnSafeArray() { SAFEARRAY *pArray = nullptr; HRESULT hr = SafeArrayAllocDescriptor(1, &pArray);//SAFEARRAYṹĶ pArray->cbElements = sizeof(GUID); pArray->rgsabound[0].cElements = 10; pArray->rgsabound[0].lLbound = 0; GUID guid, guid2; CoCreateGuid(&guid); CoCreateGuid(&guid2); GUID _guidarr[] = { guid,guid2 }; pArray->pvData = _guidarr; pArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE; //CComSafeArray<VARIANT> saguid; // saguid.Attach(pArray); //auto count = saguid.GetCount(); //auto t = saguid.GetType(); GUID* p_GUIDArry = nullptr; SafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry); auto retv = p_GUIDArry[0]; auto retv1 = p_GUIDArry[1]; long Low(0), High(0); hr = SafeArrayGetLBound(pArray, 1, &Low);//ά1ʼ hr = SafeArrayGetUBound(pArray, 1, &High);//ά1ʼ SafeArrayUnaccessData(pArray); SafeArrayDestroy(pArray); cin.get(); } void TestSafeArry() { LearnSafeArray(); //CComSafeArrayBound bound(2); //CComSafeArray<GUID> guid_Array; //GUID guid, guid2; //CoCreateGuid(&guid); //CoCreateGuid(&guid2); //guid_Array.Add(guid); //guid_Array.Add(guid2); //auto count = guid_Array.GetCount(); //auto demention = guid_Array.GetDimensions(); //auto upperbound = guid_Array.GetUpperBound(); //auto p_safeArry = &guid_Array; //GUID guid3; //CoCreateGuid(&guid3); //p_safeArry->SetAt(1, guid3); } int _tmain(int argc, _TCHAR* argv[]) { TestSafeArry(); Put1GuidInSafeArry(); Put2GuidInSafeArry(); Put1GuidInSafeArryByStack(); return 0; }<|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // interface header #include "TimeKeeper.h" // system headers #include <time.h> #include <string> #include <string.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef __BEOS__ # include <OS.h> #endif #if !defined(_WIN32) # include <sys/time.h> # include <sys/types.h> static int64_t lastTime = 0; # ifdef HAVE_SCHED_H # include <sched.h> # endif #else // !defined(_WIN32) # include <mmsystem.h> static unsigned long int lastTime = 0; static LARGE_INTEGER qpcLastTime; static LONGLONG qpcFrequency = 0; static LONGLONG qpcLastCalibration; static DWORD timeLastCalibration; #endif // !defined(_WIN32) // system threading headers #ifndef _WIN32 # include <sys/types.h> # include <dirent.h> #endif #ifdef HAVE_PTHREADS # include <pthread.h> #endif // common headers #include "TextUtils.h" #include "bzfio.h" //============================================================================// #if defined(HAVE_PTHREADS) static pthread_mutex_t timer_mutex; # define LOCK_TIMER_MUTEX pthread_mutex_lock(&timer_mutex); # define UNLOCK_TIMER_MUTEX pthread_mutex_unlock(&timer_mutex); #elif defined(_WIN32) static CRITICAL_SECTION timer_critical; # define LOCK_TIMER_MUTEX EnterCriticalSection(&timer_critical); # define UNLOCK_TIMER_MUTEX LeaveCriticalSection(&timer_critical); #else # define LOCK_TIMER_MUTEX # define UNLOCK_TIMER_MUTEX #endif //============================================================================// static TimeKeeper currentTime; static TimeKeeper tickTime; static TimeKeeper sunExplodeTime; static TimeKeeper sunGenesisTime; static TimeKeeper nullTime; static TimeKeeper startTime = TimeKeeper::getCurrent(); //============================================================================// #if !defined(_WIN32) static inline int64_t getEpochMicroseconds() { struct timeval nowTime; gettimeofday(&nowTime, NULL); return (int64_t(nowTime.tv_sec) * int64_t(1000000)) + int64_t(nowTime.tv_usec); } #endif const TimeKeeper& TimeKeeper::getCurrent(void) { LOCK_TIMER_MUTEX // if not first call then update current time, else use default initial time #if !defined(_WIN32) if (lastTime == 0) { // time starts at 0 seconds from the first call to getCurrent() lastTime = getEpochMicroseconds(); } else { const int64_t nowTime = getEpochMicroseconds(); int64_t diff = (nowTime - lastTime); if (diff < 0) { logDebugMessage(5, "WARNING: went back in time %li microseconds\n", (long int)diff); diff = 0; // eh, how'd we go back in time? } currentTime += double(diff) * 1.0e-6;; lastTime = nowTime; } #else /* !defined(_WIN32) */ if (qpcFrequency != 0) { // main timer is qpc LARGE_INTEGER now; QueryPerformanceCounter(&now); LONGLONG diff = now.QuadPart - qpcLastTime.QuadPart; LONGLONG clkSpent = now.QuadPart - qpcLastCalibration; qpcLastTime = now; if (clkSpent > qpcFrequency) { // Recalibrate Frequency DWORD tgt = timeGetTime(); DWORD deltaTgt = tgt - timeLastCalibration; timeLastCalibration = tgt; qpcLastCalibration = now.QuadPart; if (deltaTgt > 0) { LONGLONG oldqpcfreq = qpcFrequency; qpcFrequency = (clkSpent * 1000) / deltaTgt; if (qpcFrequency != oldqpcfreq) logDebugMessage(4, "Recalibrated QPC frequency. Old: %f ; New: %f\n", (double)oldqpcfreq, (double)qpcFrequency); } } currentTime += (double) diff / (double) qpcFrequency; } else if (lastTime != 0) { unsigned long int now = (unsigned long int)timeGetTime(); unsigned long int diff; if (now < lastTime) { // eh, how'd we go back in time? diff = 0; } else { diff = now - lastTime; } currentTime += 1.0e-3 * (double)diff; lastTime = now; } else { static bool sane = true; // should only get into here once on app start if (!sane) { logDebugMessage(1,"Sanity check failure in TimeKeeper::getCurrent()\n"); } sane = false; // make sure we're at our best timer resolution possible timeBeginPeriod(1); LARGE_INTEGER freq; if (QueryPerformanceFrequency(&freq)) { QueryPerformanceCounter(&qpcLastTime); qpcFrequency = freq.QuadPart; logDebugMessage(4,"Actual reported QPC Frequency: %f\n", (double)qpcFrequency); qpcLastCalibration = qpcLastTime.QuadPart; timeLastCalibration = timeGetTime(); } else { logDebugMessage(1,"QueryPerformanceFrequency failed with error %d\n", GetLastError()); lastTime = (unsigned long int)timeGetTime(); } } #endif /* !defined(_WIN32) */ UNLOCK_TIMER_MUTEX return currentTime; } const TimeKeeper& TimeKeeper::getStartTime(void) // const { return startTime; } const TimeKeeper& TimeKeeper::getTick(void) // const { return tickTime; } void TimeKeeper::setTick(void) { tickTime = getCurrent(); } const TimeKeeper& TimeKeeper::getSunExplodeTime(void) { sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60; return sunExplodeTime; } const TimeKeeper& TimeKeeper::getSunGenesisTime(void) { sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60; return sunGenesisTime; } const TimeKeeper& TimeKeeper::getNullTime(void) { nullTime.seconds = 0; return nullTime; } const char *TimeKeeper::timestamp(void) // const { static char buffer[256]; // static, so that it doesn't vanish time_t tnow = time(0); struct tm *now = localtime(&tnow); now->tm_year += 1900; ++now->tm_mon; strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256); buffer[255] = '\0'; // safety return buffer; } /** returns a short string of the local time */ //static std::string TimeKeeper::shortTimeStamp(void) { time_t tnow = time(0); struct tm *now = localtime(&tnow); std::string result( TextUtils::format("%02d:%02d", now->tm_hour, now->tm_min) ); return result; } void TimeKeeper::localTime(int *year, int *month, int* day, int* hour, int* min, int* sec, bool* dst) // const { time_t tnow = time(0); struct tm *now = localtime(&tnow); now->tm_year += 1900; ++now->tm_mon; if (year) { *year = now->tm_year; } if (month) { *month = now->tm_mon; } if (day) { *day = now->tm_mday; } if (hour) { *hour = now->tm_hour; } if (min) { *min = now->tm_min; } if (sec) { *sec = now->tm_sec; } if (dst) { *dst = (now->tm_isdst != 0); } } void TimeKeeper::localTimeDOW(int *year, int *month, int* day, int* wday, int* hour, int* min, int* sec, bool* dst) // const { time_t tnow = time(0); struct tm *now = localtime(&tnow); now->tm_year += 1900; ++now->tm_mon; if (year) { *year = now->tm_year; } if (month) { *month = now->tm_mon; } if (day) { *day = now->tm_mday; } if (wday) { *wday = now->tm_wday; } if (hour) { *hour = now->tm_hour; } if (min) { *min = now->tm_min; } if (sec) { *sec = now->tm_sec; } if (dst) { *dst = (now->tm_isdst != 0); } } void TimeKeeper::UTCTime(int *year, int *month, int* day, int* wday, int* hour, int* min, int* sec, bool* dst) // const { time_t tnow = time(0); struct tm *now = gmtime(&tnow); now->tm_year += 1900; ++now->tm_mon; if (year) { *year = now->tm_year; } if (month) { *month = now->tm_mon; } if (day) { *day = now->tm_mday; } if (wday) { *wday = now->tm_wday; } if (hour) { *hour = now->tm_hour; } if (min) { *min = now->tm_min; } if (sec) { *sec = now->tm_sec; } if (dst) { *dst = (now->tm_isdst != 0); } } // function for converting a float time (e.g. difference of two TimeKeepers) // into an array of ints void TimeKeeper::convertTime(double raw, long int convertedTimes[]) // const { long int day, hour, min, sec, remainder; static const int secondsInDay = 86400; sec = (long int)raw; day = sec / secondsInDay; remainder = sec - (day * secondsInDay); hour = remainder / 3600; remainder = sec - ((hour * 3600) + (day * secondsInDay)); min = remainder / 60; remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60)); sec = remainder; convertedTimes[0] = day; convertedTimes[1] = hour; convertedTimes[2] = min; convertedTimes[3] = sec; return; } // function for printing an array of ints representing a time // as a human-readable string const std::string TimeKeeper::printTime(long int timeValue[]) { std::string valueNames; char temp[20]; if (timeValue[0] > 0) { snprintf(temp, 20, "%ld day%s", timeValue[0], timeValue[0] == 1 ? "" : "s"); valueNames.append(temp); } if (timeValue[1] > 0) { if (timeValue[0] > 0) { valueNames.append(", "); } snprintf(temp, 20, "%ld hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s"); valueNames.append(temp); } if (timeValue[2] > 0) { if ((timeValue[1] > 0) || (timeValue[0] > 0)) { valueNames.append(", "); } snprintf(temp, 20, "%ld min%s", timeValue[2], timeValue[2] == 1 ? "" : "s"); valueNames.append(temp); } if (timeValue[3] > 0) { if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) { valueNames.append(", "); } snprintf(temp, 20, "%ld sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s"); valueNames.append(temp); } return valueNames; } // function for printing a float time difference as a human-readable string const std::string TimeKeeper::printTime(double diff) { long int temp[4]; convertTime(diff, temp); return printTime(temp); } void TimeKeeper::sleep(double seconds) { if (seconds <= 0.0) { return; } #ifdef HAVE_USLEEP usleep((unsigned int)(1.0e6 * seconds)); return; #endif #if defined(HAVE_SLEEP) && !defined(__APPLE__) // equivalent to _sleep() on win32 (not sleep(3)) Sleep((DWORD)(seconds * 1000.0)); return; #endif #ifdef HAVE_SNOOZE snooze((bigtime_t)(1.0e6 * seconds)); return; #endif #ifdef HAVE_SELECT struct timeval tv; tv.tv_sec = (long)seconds; tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec)); select(0, NULL, NULL, NULL, &tv); return; #endif #ifdef HAVE_WAITFORSINGLEOBJECT HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL); WaitForSingleObject(dummyEvent, (DWORD)(1000.0 * seconds)); CloseHandle(dummyEvent); return; #endif // fall-back case is fugly manual timekeeping TimeKeeper now = TimeKeeper::getCurrent(); while ((TimeKeeper::getCurrent() - now) < seconds) { continue; } return; } void TimeKeeper::setProcessorAffinity(int processor) { #ifdef HAVE_SCHED_SETAFFINITY /* linuxy fix for time travel */ cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(processor, &mask); sched_setaffinity(0, sizeof(mask), &mask); #elif defined(WIN32) /* windowsy fix for time travel */ HANDLE hThread = GetCurrentThread(); DWORD_PTR dwMask = 1 << processor; DWORD_PTR dwProcs = 0; GetProcessAffinityMask(NULL, NULL, &dwProcs); if (dwMask < dwProcs) { logDebugMessage(1, "Unable to set process affinity mask (specified processor does not exist).\n"); return; } SetThreadAffinityMask(hThread, dwMask); #else logDebugMessage(1, "Unable to set processor affinity to %d - function not implemented on this platform.\n", processor); #endif } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>* informative comment<commit_after>/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // interface header #include "TimeKeeper.h" // system headers #include <time.h> #include <string> #include <string.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef __BEOS__ # include <OS.h> #endif #if !defined(_WIN32) # include <sys/time.h> # include <sys/types.h> static int64_t lastTime = 0; # ifdef HAVE_SCHED_H # include <sched.h> # endif #else // !defined(_WIN32) # include <mmsystem.h> static unsigned long int lastTime = 0; static LARGE_INTEGER qpcLastTime; static LONGLONG qpcFrequency = 0; static LONGLONG qpcLastCalibration; static DWORD timeLastCalibration; #endif // !defined(_WIN32) // system threading headers #ifndef _WIN32 # include <sys/types.h> # include <dirent.h> #endif #ifdef HAVE_PTHREADS # include <pthread.h> #endif // common headers #include "TextUtils.h" #include "bzfio.h" //============================================================================// #if defined(HAVE_PTHREADS) static pthread_mutex_t timer_mutex; # define LOCK_TIMER_MUTEX pthread_mutex_lock(&timer_mutex); # define UNLOCK_TIMER_MUTEX pthread_mutex_unlock(&timer_mutex); #elif defined(_WIN32) static CRITICAL_SECTION timer_critical; # define LOCK_TIMER_MUTEX EnterCriticalSection(&timer_critical); # define UNLOCK_TIMER_MUTEX LeaveCriticalSection(&timer_critical); #else # define LOCK_TIMER_MUTEX # define UNLOCK_TIMER_MUTEX #endif //============================================================================// static TimeKeeper currentTime; static TimeKeeper tickTime; static TimeKeeper sunExplodeTime; static TimeKeeper sunGenesisTime; static TimeKeeper nullTime; static TimeKeeper startTime = TimeKeeper::getCurrent(); //============================================================================// #if !defined(_WIN32) static inline int64_t getEpochMicroseconds() { struct timeval nowTime; gettimeofday(&nowTime, NULL); return (int64_t(nowTime.tv_sec) * int64_t(1000000)) + int64_t(nowTime.tv_usec); } #endif const TimeKeeper& TimeKeeper::getCurrent(void) { // a mutex lock is used because this routine // is called from the client's sound thread LOCK_TIMER_MUTEX // if not first call then update current time, else use default initial time #if !defined(_WIN32) if (lastTime == 0) { // time starts at 0 seconds from the first call to getCurrent() lastTime = getEpochMicroseconds(); } else { const int64_t nowTime = getEpochMicroseconds(); int64_t diff = (nowTime - lastTime); if (diff < 0) { logDebugMessage(5, "WARNING: went back in time %li microseconds\n", (long int)diff); diff = 0; // eh, how'd we go back in time? } currentTime += double(diff) * 1.0e-6;; lastTime = nowTime; } #else /* !defined(_WIN32) */ if (qpcFrequency != 0) { // main timer is qpc LARGE_INTEGER now; QueryPerformanceCounter(&now); LONGLONG diff = now.QuadPart - qpcLastTime.QuadPart; LONGLONG clkSpent = now.QuadPart - qpcLastCalibration; qpcLastTime = now; if (clkSpent > qpcFrequency) { // Recalibrate Frequency DWORD tgt = timeGetTime(); DWORD deltaTgt = tgt - timeLastCalibration; timeLastCalibration = tgt; qpcLastCalibration = now.QuadPart; if (deltaTgt > 0) { LONGLONG oldqpcfreq = qpcFrequency; qpcFrequency = (clkSpent * 1000) / deltaTgt; if (qpcFrequency != oldqpcfreq) logDebugMessage(4, "Recalibrated QPC frequency. Old: %f ; New: %f\n", (double)oldqpcfreq, (double)qpcFrequency); } } currentTime += (double) diff / (double) qpcFrequency; } else if (lastTime != 0) { unsigned long int now = (unsigned long int)timeGetTime(); unsigned long int diff; if (now < lastTime) { // eh, how'd we go back in time? diff = 0; } else { diff = now - lastTime; } currentTime += 1.0e-3 * (double)diff; lastTime = now; } else { static bool sane = true; // should only get into here once on app start if (!sane) { logDebugMessage(1,"Sanity check failure in TimeKeeper::getCurrent()\n"); } sane = false; // make sure we're at our best timer resolution possible timeBeginPeriod(1); LARGE_INTEGER freq; if (QueryPerformanceFrequency(&freq)) { QueryPerformanceCounter(&qpcLastTime); qpcFrequency = freq.QuadPart; logDebugMessage(4,"Actual reported QPC Frequency: %f\n", (double)qpcFrequency); qpcLastCalibration = qpcLastTime.QuadPart; timeLastCalibration = timeGetTime(); } else { logDebugMessage(1,"QueryPerformanceFrequency failed with error %d\n", GetLastError()); lastTime = (unsigned long int)timeGetTime(); } } #endif /* !defined(_WIN32) */ UNLOCK_TIMER_MUTEX return currentTime; } const TimeKeeper& TimeKeeper::getStartTime(void) // const { return startTime; } const TimeKeeper& TimeKeeper::getTick(void) // const { return tickTime; } void TimeKeeper::setTick(void) { tickTime = getCurrent(); } const TimeKeeper& TimeKeeper::getSunExplodeTime(void) { sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60; return sunExplodeTime; } const TimeKeeper& TimeKeeper::getSunGenesisTime(void) { sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60; return sunGenesisTime; } const TimeKeeper& TimeKeeper::getNullTime(void) { nullTime.seconds = 0; return nullTime; } const char *TimeKeeper::timestamp(void) // const { static char buffer[256]; // static, so that it doesn't vanish time_t tnow = time(0); struct tm *now = localtime(&tnow); now->tm_year += 1900; ++now->tm_mon; strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d", now->tm_year, now->tm_mon, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256); buffer[255] = '\0'; // safety return buffer; } /** returns a short string of the local time */ //static std::string TimeKeeper::shortTimeStamp(void) { time_t tnow = time(0); struct tm *now = localtime(&tnow); std::string result( TextUtils::format("%02d:%02d", now->tm_hour, now->tm_min) ); return result; } void TimeKeeper::localTime(int *year, int *month, int* day, int* hour, int* min, int* sec, bool* dst) // const { time_t tnow = time(0); struct tm *now = localtime(&tnow); now->tm_year += 1900; ++now->tm_mon; if (year) { *year = now->tm_year; } if (month) { *month = now->tm_mon; } if (day) { *day = now->tm_mday; } if (hour) { *hour = now->tm_hour; } if (min) { *min = now->tm_min; } if (sec) { *sec = now->tm_sec; } if (dst) { *dst = (now->tm_isdst != 0); } } void TimeKeeper::localTimeDOW(int *year, int *month, int* day, int* wday, int* hour, int* min, int* sec, bool* dst) // const { time_t tnow = time(0); struct tm *now = localtime(&tnow); now->tm_year += 1900; ++now->tm_mon; if (year) { *year = now->tm_year; } if (month) { *month = now->tm_mon; } if (day) { *day = now->tm_mday; } if (wday) { *wday = now->tm_wday; } if (hour) { *hour = now->tm_hour; } if (min) { *min = now->tm_min; } if (sec) { *sec = now->tm_sec; } if (dst) { *dst = (now->tm_isdst != 0); } } void TimeKeeper::UTCTime(int *year, int *month, int* day, int* wday, int* hour, int* min, int* sec, bool* dst) // const { time_t tnow = time(0); struct tm *now = gmtime(&tnow); now->tm_year += 1900; ++now->tm_mon; if (year) { *year = now->tm_year; } if (month) { *month = now->tm_mon; } if (day) { *day = now->tm_mday; } if (wday) { *wday = now->tm_wday; } if (hour) { *hour = now->tm_hour; } if (min) { *min = now->tm_min; } if (sec) { *sec = now->tm_sec; } if (dst) { *dst = (now->tm_isdst != 0); } } // function for converting a float time (e.g. difference of two TimeKeepers) // into an array of ints void TimeKeeper::convertTime(double raw, long int convertedTimes[]) // const { long int day, hour, min, sec, remainder; static const int secondsInDay = 86400; sec = (long int)raw; day = sec / secondsInDay; remainder = sec - (day * secondsInDay); hour = remainder / 3600; remainder = sec - ((hour * 3600) + (day * secondsInDay)); min = remainder / 60; remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60)); sec = remainder; convertedTimes[0] = day; convertedTimes[1] = hour; convertedTimes[2] = min; convertedTimes[3] = sec; return; } // function for printing an array of ints representing a time // as a human-readable string const std::string TimeKeeper::printTime(long int timeValue[]) { std::string valueNames; char temp[20]; if (timeValue[0] > 0) { snprintf(temp, 20, "%ld day%s", timeValue[0], timeValue[0] == 1 ? "" : "s"); valueNames.append(temp); } if (timeValue[1] > 0) { if (timeValue[0] > 0) { valueNames.append(", "); } snprintf(temp, 20, "%ld hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s"); valueNames.append(temp); } if (timeValue[2] > 0) { if ((timeValue[1] > 0) || (timeValue[0] > 0)) { valueNames.append(", "); } snprintf(temp, 20, "%ld min%s", timeValue[2], timeValue[2] == 1 ? "" : "s"); valueNames.append(temp); } if (timeValue[3] > 0) { if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) { valueNames.append(", "); } snprintf(temp, 20, "%ld sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s"); valueNames.append(temp); } return valueNames; } // function for printing a float time difference as a human-readable string const std::string TimeKeeper::printTime(double diff) { long int temp[4]; convertTime(diff, temp); return printTime(temp); } void TimeKeeper::sleep(double seconds) { if (seconds <= 0.0) { return; } #ifdef HAVE_USLEEP usleep((unsigned int)(1.0e6 * seconds)); return; #endif #if defined(HAVE_SLEEP) && !defined(__APPLE__) // equivalent to _sleep() on win32 (not sleep(3)) Sleep((DWORD)(seconds * 1000.0)); return; #endif #ifdef HAVE_SNOOZE snooze((bigtime_t)(1.0e6 * seconds)); return; #endif #ifdef HAVE_SELECT struct timeval tv; tv.tv_sec = (long)seconds; tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec)); select(0, NULL, NULL, NULL, &tv); return; #endif #ifdef HAVE_WAITFORSINGLEOBJECT HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL); WaitForSingleObject(dummyEvent, (DWORD)(1000.0 * seconds)); CloseHandle(dummyEvent); return; #endif // fall-back case is fugly manual timekeeping TimeKeeper now = TimeKeeper::getCurrent(); while ((TimeKeeper::getCurrent() - now) < seconds) { continue; } return; } void TimeKeeper::setProcessorAffinity(int processor) { #ifdef HAVE_SCHED_SETAFFINITY /* linuxy fix for time travel */ cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(processor, &mask); sched_setaffinity(0, sizeof(mask), &mask); #elif defined(WIN32) /* windowsy fix for time travel */ HANDLE hThread = GetCurrentThread(); DWORD_PTR dwMask = 1 << processor; DWORD_PTR dwProcs = 0; GetProcessAffinityMask(NULL, NULL, &dwProcs); if (dwMask < dwProcs) { logDebugMessage(1, "Unable to set process affinity mask (specified processor does not exist).\n"); return; } SetThreadAffinityMask(hThread, dwMask); #else logDebugMessage(1, "Unable to set processor affinity to %d - function not implemented on this platform.\n", processor); #endif } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "file_utils.h" #include "log/log.h" #include <wordexp.h> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <pwd.h> LOG_DECLARE_NAMESPACE("client.common.file_utils"); namespace Cthun { namespace Common { namespace FileUtils { // HERE(ale): copied from Pegasus // TODO(ale): look for boost alternatives std::string expandAsDoneByShell(std::string txt) { // This will store the expansion outcome wordexp_t result; // Expand and check the success if (wordexp(txt.c_str(), &result, 0) != 0) { wordfree(&result); return ""; } // Get the expanded text and free the memory std::string expanded_txt { result.we_wordv[0] }; wordfree(&result); return expanded_txt; } bool fileExists(const std::string& file_path) { bool exists { false }; if (file_path.empty()) { LOG_WARNING("file path is an empty string"); } else { std::ifstream file_stream { file_path }; exists = file_stream.good(); file_stream.close(); } return exists; } void removeFile(const std::string& file_path) { if (FileUtils::fileExists(file_path)) { if (std::remove(file_path.c_str()) != 0) { throw file_error { "failed to remove " + file_path }; } } } void streamToFile(const std::string& text, const std::string& file_path, std::ios_base::openmode mode) { std::ofstream ofs; ofs.open(file_path, mode); if (!ofs.is_open()) { throw file_error { "failed to open " + file_path }; } ofs << text; } void writeToFile(const std::string& text, const std::string& file_path) { streamToFile(text, file_path, std::ofstream::out | std::ofstream::trunc); } } // namespace FileUtils } // namespace Common } // namespace Cthun <commit_msg>(maint) - Relative path to log.h in file_utils.cpp<commit_after>#include "file_utils.h" #include "../log/log.h" #include <wordexp.h> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <pwd.h> LOG_DECLARE_NAMESPACE("client.common.file_utils"); namespace Cthun { namespace Common { namespace FileUtils { // HERE(ale): copied from Pegasus // TODO(ale): look for boost alternatives std::string expandAsDoneByShell(std::string txt) { // This will store the expansion outcome wordexp_t result; // Expand and check the success if (wordexp(txt.c_str(), &result, 0) != 0) { wordfree(&result); return ""; } // Get the expanded text and free the memory std::string expanded_txt { result.we_wordv[0] }; wordfree(&result); return expanded_txt; } bool fileExists(const std::string& file_path) { bool exists { false }; if (file_path.empty()) { LOG_WARNING("file path is an empty string"); } else { std::ifstream file_stream { file_path }; exists = file_stream.good(); file_stream.close(); } return exists; } void removeFile(const std::string& file_path) { if (FileUtils::fileExists(file_path)) { if (std::remove(file_path.c_str()) != 0) { throw file_error { "failed to remove " + file_path }; } } } void streamToFile(const std::string& text, const std::string& file_path, std::ios_base::openmode mode) { std::ofstream ofs; ofs.open(file_path, mode); if (!ofs.is_open()) { throw file_error { "failed to open " + file_path }; } ofs << text; } void writeToFile(const std::string& text, const std::string& file_path) { streamToFile(text, file_path, std::ofstream::out | std::ofstream::trunc); } } // namespace FileUtils } // namespace Common } // namespace Cthun <|endoftext|>
<commit_before>#include <QObject> #include <QGraphicsSceneMouseEvent> #include <dcpappletpage.h> #include <dcpappletobject.h> #include "ut_dcpappletpage.h" void Ut_DcpAppletPage::init() { m_subject = new DcpAppletPage(0); } void Ut_DcpAppletPage::cleanup() { delete m_subject; m_subject = 0; } void Ut_DcpAppletPage::initTestCase() { QSKIP("incomplete", SkipSingle); // remove this when you've finished } void Ut_DcpAppletPage::cleanupTestCase() { } QTEST_MAIN(Ut_DcpAppletPage) <commit_msg>ut_dcpappletpage first pass (no cases really)<commit_after>#include <QObject> #include <QGraphicsSceneMouseEvent> #include <dcpappletpage.h> #include <dcpappletobject.h> #include "ut_dcpappletpage.h" void Ut_DcpAppletPage::init() { m_subject = new DcpAppletPage(0); } void Ut_DcpAppletPage::cleanup() { delete m_subject; m_subject = 0; } void Ut_DcpAppletPage::initTestCase() { QSKIP("incomplete", SkipSingle); // remove this when you've finished } void Ut_DcpAppletPage::cleanupTestCase() { } QTEST_APPLESS_MAIN(Ut_DcpAppletPage) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_3D_SceneGeometry.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 17:42:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_TP_3D_SCENE_GEOMETRY_HXX #define _CHART2_TP_3D_SCENE_GEOMETRY_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX #include <basegfx/matrix/b3dhommatrix.hxx> #endif // header for class TabPage #ifndef _SV_TABPAGE_HXX #include <vcl/tabpage.hxx> #endif // header for class FixedLine #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif // header for class MetricField #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif // header for class OKButton #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #include "ControllerLockGuard.hxx" //............................................................................. namespace chart { //............................................................................. class ThreeD_SceneGeometry_TabPage : public TabPage { public: ThreeD_SceneGeometry_TabPage( Window* pWindow, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xSceneProperties, ControllerLockHelper & rControllerLockHelper ); virtual ~ThreeD_SceneGeometry_TabPage(); // has to be called in case the dialog was closed with OK void commitPendingChanges(); // is called by timer to apply changes to model DECL_LINK( AngleChanged, void* ); // is called immediately when a field changes DECL_LINK( AngleEdited, void* ); // is called by timer to apply changes to model DECL_LINK( PerspectiveChanged, void* ); // is called immediately when a field changes DECL_LINK( PerspectiveEdited, void* ); DECL_LINK( PerspectiveToggled, void* ); private: void fillDialogAnglesFromModel() const; void applyAnglesToModel(); void applyPerspectiveToModel(); double CameraDistanceToPerspective( double fCameraDistance ); double PerspectiveToCameraDistance( double fPerspective ); void shiftAngleToValidRange( double& rfAngleDegree ); ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSceneProperties; FixedText m_aFtXRotation; MetricField m_aMFXRotation; FixedText m_aFtYRotation; MetricField m_aMFYRotation; FixedText m_aFtZRotation; MetricField m_aMFZRotation; CheckBox m_aCbxPerspective; MetricField m_aMFPerspective; bool m_bAngleChangePending; bool m_bPerspectiveChangePending; ControllerLockHelper & m_rControllerLockHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS chart06 (1.2.8); FILE MERGED 2007/06/15 12:47:31 iha 1.2.8.2: #i67754# for right-angled-axes restrict angles to meaningful values 2007/06/11 09:10:18 iha 1.2.8.1: #i67754# right-angled-axes option for 3D charts<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_3D_SceneGeometry.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-03 13:39:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_TP_3D_SCENE_GEOMETRY_HXX #define _CHART2_TP_3D_SCENE_GEOMETRY_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX #include <basegfx/matrix/b3dhommatrix.hxx> #endif // header for class TabPage #ifndef _SV_TABPAGE_HXX #include <vcl/tabpage.hxx> #endif // header for class FixedLine #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif // header for class MetricField #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif // header for class OKButton #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #include "ControllerLockGuard.hxx" //............................................................................. namespace chart { //............................................................................. class ThreeD_SceneGeometry_TabPage : public TabPage { public: ThreeD_SceneGeometry_TabPage( Window* pWindow, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xSceneProperties, ControllerLockHelper & rControllerLockHelper ); virtual ~ThreeD_SceneGeometry_TabPage(); // has to be called in case the dialog was closed with OK void commitPendingChanges(); // is called by timer to apply changes to model DECL_LINK( AngleChanged, void* ); // is called immediately when a field changes DECL_LINK( AngleEdited, void* ); // is called by timer to apply changes to model DECL_LINK( PerspectiveChanged, void* ); // is called immediately when a field changes DECL_LINK( PerspectiveEdited, void* ); DECL_LINK( PerspectiveToggled, void* ); DECL_LINK( RightAngledAxesToggled, void* ); private: void fillDialogAnglesFromModel() const; void applyAnglesToModel(); void applyPerspectiveToModel(); ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSceneProperties; CheckBox m_aCbxRightAngledAxes; FixedText m_aFtXRotation; MetricField m_aMFXRotation; FixedText m_aFtYRotation; MetricField m_aMFYRotation; FixedText m_aFtZRotation; MetricField m_aMFZRotation; CheckBox m_aCbxPerspective; MetricField m_aMFPerspective; //to keep old values when switching to right angled axes sal_Int64 m_nXRotation; sal_Int64 m_nYRotation; sal_Int64 m_nZRotation; bool m_bAngleChangePending; bool m_bPerspectiveChangePending; ControllerLockHelper & m_rControllerLockHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_3D_SceneGeometry.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-03 13:39:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_TP_3D_SCENE_GEOMETRY_HXX #define _CHART2_TP_3D_SCENE_GEOMETRY_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX #include <basegfx/matrix/b3dhommatrix.hxx> #endif // header for class TabPage #ifndef _SV_TABPAGE_HXX #include <vcl/tabpage.hxx> #endif // header for class FixedLine #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif // header for class MetricField #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif // header for class OKButton #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #include "ControllerLockGuard.hxx" //............................................................................. namespace chart { //............................................................................. class ThreeD_SceneGeometry_TabPage : public TabPage { public: ThreeD_SceneGeometry_TabPage( Window* pWindow, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xSceneProperties, ControllerLockHelper & rControllerLockHelper ); virtual ~ThreeD_SceneGeometry_TabPage(); // has to be called in case the dialog was closed with OK void commitPendingChanges(); // is called by timer to apply changes to model DECL_LINK( AngleChanged, void* ); // is called immediately when a field changes DECL_LINK( AngleEdited, void* ); // is called by timer to apply changes to model DECL_LINK( PerspectiveChanged, void* ); // is called immediately when a field changes DECL_LINK( PerspectiveEdited, void* ); DECL_LINK( PerspectiveToggled, void* ); DECL_LINK( RightAngledAxesToggled, void* ); private: void fillDialogAnglesFromModel() const; void applyAnglesToModel(); void applyPerspectiveToModel(); ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSceneProperties; CheckBox m_aCbxRightAngledAxes; FixedText m_aFtXRotation; MetricField m_aMFXRotation; FixedText m_aFtYRotation; MetricField m_aMFYRotation; FixedText m_aFtZRotation; MetricField m_aMFZRotation; CheckBox m_aCbxPerspective; MetricField m_aMFPerspective; //to keep old values when switching to right angled axes sal_Int64 m_nXRotation; sal_Int64 m_nYRotation; sal_Int64 m_nZRotation; bool m_bAngleChangePending; bool m_bPerspectiveChangePending; ControllerLockHelper & m_rControllerLockHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.106); FILE MERGED 2008/04/01 15:04:02 thb 1.3.106.3: #i85898# Stripping all external header guards 2008/04/01 10:50:19 thb 1.3.106.2: #i85898# Stripping all external header guards 2008/03/28 16:43:30 rt 1.3.106.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_3D_SceneGeometry.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CHART2_TP_3D_SCENE_GEOMETRY_HXX #define _CHART2_TP_3D_SCENE_GEOMETRY_HXX #include <com/sun/star/beans/XPropertySet.hpp> #include <basegfx/matrix/b3dhommatrix.hxx> // header for class TabPage #include <vcl/tabpage.hxx> // header for class FixedLine #include <vcl/fixed.hxx> // header for class MetricField #include <vcl/field.hxx> // header for class OKButton #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #include "ControllerLockGuard.hxx" //............................................................................. namespace chart { //............................................................................. class ThreeD_SceneGeometry_TabPage : public TabPage { public: ThreeD_SceneGeometry_TabPage( Window* pWindow, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & xSceneProperties, ControllerLockHelper & rControllerLockHelper ); virtual ~ThreeD_SceneGeometry_TabPage(); // has to be called in case the dialog was closed with OK void commitPendingChanges(); // is called by timer to apply changes to model DECL_LINK( AngleChanged, void* ); // is called immediately when a field changes DECL_LINK( AngleEdited, void* ); // is called by timer to apply changes to model DECL_LINK( PerspectiveChanged, void* ); // is called immediately when a field changes DECL_LINK( PerspectiveEdited, void* ); DECL_LINK( PerspectiveToggled, void* ); DECL_LINK( RightAngledAxesToggled, void* ); private: void fillDialogAnglesFromModel() const; void applyAnglesToModel(); void applyPerspectiveToModel(); ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSceneProperties; CheckBox m_aCbxRightAngledAxes; FixedText m_aFtXRotation; MetricField m_aMFXRotation; FixedText m_aFtYRotation; MetricField m_aMFYRotation; FixedText m_aFtZRotation; MetricField m_aMFZRotation; CheckBox m_aCbxPerspective; MetricField m_aMFPerspective; //to keep old values when switching to right angled axes sal_Int64 m_nXRotation; sal_Int64 m_nYRotation; sal_Int64 m_nZRotation; bool m_bAngleChangePending; bool m_bPerspectiveChangePending; ControllerLockHelper & m_rControllerLockHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/shown_sections_handler.h" #include "base/scoped_ptr.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/prefs/pref_value_store.h" #include "chrome/common/json_pref_store.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_pref_service.h" #include "testing/gtest/include/gtest/gtest.h" class ShownSectionsHandlerTest : public testing::Test { }; // http://crbug.com/53405 TEST_F(ShownSectionsHandlerTest, DISABLED_MigrateUserPrefs) { scoped_ptr<PrefService> pref(new TestingPrefService); // Set an *old* value pref->RegisterIntegerPref(prefs::kNTPShownSections, 0); pref->SetInteger(prefs::kNTPShownSections, THUMB); ShownSectionsHandler::MigrateUserPrefs(pref.get(), 0, 1); int shown_sections = pref->GetInteger(prefs::kNTPShownSections); EXPECT_TRUE(shown_sections & THUMB); EXPECT_FALSE(shown_sections & LIST); EXPECT_FALSE(shown_sections & RECENT); EXPECT_TRUE(shown_sections & TIPS); EXPECT_TRUE(shown_sections & SYNC); } // http://crbug.com/53405 TEST_F(ShownSectionsHandlerTest, DISABLED_MigrateUserPrefs1To2) { scoped_ptr<PrefService> pref(new TestingPrefService); // Set an *old* value pref->RegisterIntegerPref(prefs::kNTPShownSections, 0); pref->SetInteger(prefs::kNTPShownSections, LIST); ShownSectionsHandler::MigrateUserPrefs(pref.get(), 1, 2); int shown_sections = pref->GetInteger(prefs::kNTPShownSections); EXPECT_TRUE(shown_sections & THUMB); EXPECT_FALSE(shown_sections & LIST); } <commit_msg>Re-enable 2 uni_tests. They started passing again after a revert.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/shown_sections_handler.h" #include "base/scoped_ptr.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/prefs/pref_value_store.h" #include "chrome/common/json_pref_store.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_pref_service.h" #include "testing/gtest/include/gtest/gtest.h" class ShownSectionsHandlerTest : public testing::Test { }; TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) { scoped_ptr<PrefService> pref(new TestingPrefService); // Set an *old* value pref->RegisterIntegerPref(prefs::kNTPShownSections, 0); pref->SetInteger(prefs::kNTPShownSections, THUMB); ShownSectionsHandler::MigrateUserPrefs(pref.get(), 0, 1); int shown_sections = pref->GetInteger(prefs::kNTPShownSections); EXPECT_TRUE(shown_sections & THUMB); EXPECT_FALSE(shown_sections & LIST); EXPECT_FALSE(shown_sections & RECENT); EXPECT_TRUE(shown_sections & TIPS); EXPECT_TRUE(shown_sections & SYNC); } TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs1To2) { scoped_ptr<PrefService> pref(new TestingPrefService); // Set an *old* value pref->RegisterIntegerPref(prefs::kNTPShownSections, 0); pref->SetInteger(prefs::kNTPShownSections, LIST); ShownSectionsHandler::MigrateUserPrefs(pref.get(), 1, 2); int shown_sections = pref->GetInteger(prefs::kNTPShownSections); EXPECT_TRUE(shown_sections & THUMB); EXPECT_FALSE(shown_sections & LIST); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(rafaelw,erikkay) disabled due to flakiness // BUG=22668 (probably the same bug) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; } <commit_msg>Enable ExtensionApiTest.Toolstrip<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(rafaelw,erikkay) disabled due to flakiness // BUG=22668 (probably the same bug) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; } <|endoftext|>
<commit_before>//============================================================================== /// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file vktTimestampedCmdBuf.cpp /// \brief A wrapper for internal command buffer which holds 1 timestamp. //============================================================================== #include "vktTimestampedCmdBuf.h" //----------------------------------------------------------------------------- /// Static method that instantiates a VktTimestampedCmdBuf. /// \param config A configuration structure. /// \returns A new VktTimestampedCmdBuf instance. //----------------------------------------------------------------------------- VktTimestampedCmdBuf* VktTimestampedCmdBuf::Create(const TimestampedCmdBufConfig& config) { VktTimestampedCmdBuf* pOut = new VktTimestampedCmdBuf(); if (pOut != nullptr) { if (pOut->Init(config) != VK_SUCCESS) { delete pOut; pOut = nullptr; } } return pOut; } //----------------------------------------------------------------------------- /// Constructor. //----------------------------------------------------------------------------- VktTimestampedCmdBuf::VktTimestampedCmdBuf() : m_pInstanceDT(nullptr), m_pDeviceDT(nullptr), m_cmdPool(VK_NULL_HANDLE), m_cmdBuf(VK_NULL_HANDLE) { } //----------------------------------------------------------------------------- /// Destructor. //----------------------------------------------------------------------------- VktTimestampedCmdBuf::~VktTimestampedCmdBuf() { if (m_gpuRes.timestampQueryPool != NULL) { m_pDeviceDT->DestroyQueryPool(m_config.device, m_gpuRes.timestampQueryPool, nullptr); m_gpuRes.timestampQueryPool = NULL; } if (m_gpuRes.timestampBuffer != NULL) { m_pDeviceDT->DestroyBuffer(m_config.device, m_gpuRes.timestampBuffer, nullptr); m_gpuRes.timestampBuffer = NULL; } if (m_gpuRes.timestampMem != NULL) { m_pDeviceDT->FreeMemory(m_config.device, m_gpuRes.timestampMem, nullptr); m_gpuRes.timestampMem = NULL; } if (m_cmdBuf != VK_NULL_HANDLE) { m_pDeviceDT->FreeCommandBuffers(m_config.device, m_cmdPool, 1, &m_cmdBuf); m_cmdBuf = VK_NULL_HANDLE; } } //----------------------------------------------------------------------------- /// Perform all initialization. /// \param config A pointer to a profiler configuration structure. /// \returns The result code for initialization. //----------------------------------------------------------------------------- VkResult VktTimestampedCmdBuf::Init(const TimestampedCmdBufConfig& config) ///< [in] Pointer to profiler configuration { VkResult result = VK_INCOMPLETE; memcpy(&m_config, &config, sizeof(m_config)); if ((m_config.physicalDevice != VK_NULL_HANDLE) && (m_config.device != VK_NULL_HANDLE)) { m_pInstanceDT = instance_dispatch_table(config.physicalDevice); m_pDeviceDT = device_dispatch_table(config.device); m_pInstanceDT->GetPhysicalDeviceMemoryProperties(m_config.physicalDevice, &m_memProps); // Create command pool VkCommandPoolCreateInfo cmdPoolCreateInfo = {}; cmdPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmdPoolCreateInfo.pNext = nullptr; cmdPoolCreateInfo.queueFamilyIndex = m_config.queueFamilyIndex; cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; result = m_pDeviceDT->CreateCommandPool(m_config.device, &cmdPoolCreateInfo, nullptr, &m_cmdPool); // Create command buffer if (result == VK_SUCCESS) { VkCommandBufferAllocateInfo cmdBufAllocInfo = {}; cmdBufAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; cmdBufAllocInfo.pNext = nullptr; cmdBufAllocInfo.commandPool = m_cmdPool; cmdBufAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cmdBufAllocInfo.commandBufferCount = 1; result = m_pDeviceDT->AllocateCommandBuffers(m_config.device, &cmdBufAllocInfo, &m_cmdBuf); } // Create query pool if (result == VK_SUCCESS) { VkQueryPoolCreateInfo queryPoolCreateInfo = {}; queryPoolCreateInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; queryPoolCreateInfo.pNext = nullptr; queryPoolCreateInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; queryPoolCreateInfo.queryCount = 1; result = m_pDeviceDT->CreateQueryPool(m_config.device, &queryPoolCreateInfo, nullptr, &m_gpuRes.timestampQueryPool); } // Create timestamp buffer if (result == VK_SUCCESS) { VkBufferCreateInfo bufferCreateInfo = {}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.pNext = nullptr; bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; bufferCreateInfo.size = sizeof(UINT64); bufferCreateInfo.queueFamilyIndexCount = 0; bufferCreateInfo.pQueueFamilyIndices = nullptr; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; bufferCreateInfo.flags = 0; result = m_pDeviceDT->CreateBuffer(m_config.device, &bufferCreateInfo, nullptr, &m_gpuRes.timestampBuffer); if (result == VK_SUCCESS) { VkMemoryRequirements memReqs = {}; m_pDeviceDT->GetBufferMemoryRequirements(m_config.device, m_gpuRes.timestampBuffer, &memReqs); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.allocationSize = memReqs.size; result = MemTypeFromProps( memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex); if (result == VK_SUCCESS) { result = m_pDeviceDT->AllocateMemory(m_config.device, &allocInfo, nullptr, &m_gpuRes.timestampMem); if (result == VK_SUCCESS) { result = m_pDeviceDT->BindBufferMemory(m_config.device, m_gpuRes.timestampBuffer, m_gpuRes.timestampMem, 0); if (result == VK_SUCCESS) { void* pMappedMem = nullptr; result = m_pDeviceDT->MapMemory( m_config.device, m_gpuRes.timestampMem, 0, VK_WHOLE_SIZE, 0, &pMappedMem); if (result == VK_SUCCESS) { memset(pMappedMem, 0, memReqs.size); m_pDeviceDT->UnmapMemory(m_config.device, m_gpuRes.timestampMem); } } } } } } // Fill in the command buffer if (result == VK_SUCCESS) { VkCommandBufferInheritanceInfo cmdBufInheritInfo = {}; cmdBufInheritInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO; cmdBufInheritInfo.pNext = nullptr; cmdBufInheritInfo.renderPass = VK_NULL_HANDLE; cmdBufInheritInfo.subpass = 0; cmdBufInheritInfo.framebuffer = VK_NULL_HANDLE; cmdBufInheritInfo.occlusionQueryEnable = VK_FALSE; cmdBufInheritInfo.queryFlags = 0; cmdBufInheritInfo.pipelineStatistics = 0; VkCommandBufferBeginInfo cmdBufBeginInfo = {}; cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmdBufBeginInfo.pNext = nullptr; cmdBufBeginInfo.flags = 0; cmdBufBeginInfo.pInheritanceInfo = &cmdBufInheritInfo; result = m_pDeviceDT->BeginCommandBuffer(m_cmdBuf, &cmdBufBeginInfo); m_pDeviceDT->CmdResetQueryPool(m_cmdBuf, m_gpuRes.timestampQueryPool, 0, 1); // Inject timestamp m_pDeviceDT->CmdWriteTimestamp( m_cmdBuf, m_config.pipelineLoc, m_gpuRes.timestampQueryPool, 0); if (m_config.mapTimestampMem == true) { m_pDeviceDT->CmdCopyQueryPoolResults( m_cmdBuf, m_gpuRes.timestampQueryPool, 0, 1, m_gpuRes.timestampBuffer, 0, sizeof(UINT64), VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT); } result = m_pDeviceDT->EndCommandBuffer(m_cmdBuf); } } return result; } //----------------------------------------------------------------------------- /// Find a memory type from available heaps. /// \param typeBits The requested mem type. /// \param reqsMask Mem requirements. /// \param pTypeIdx The output heap index. /// \returns A Vulkan result code. //----------------------------------------------------------------------------- VkResult VktTimestampedCmdBuf::MemTypeFromProps( UINT typeBits, VkFlags reqsMask, UINT* pTypeIdx) { // Search memory types to find first index with those properties for (UINT i = 0; i < 32; i++) { if ((typeBits & 1) == 1) { // Type is available, does it match user properties? if ((m_memProps.memoryTypes[i].propertyFlags & reqsMask) == reqsMask) { *pTypeIdx = i; return VK_SUCCESS; } } typeBits >>= 1; } // No memory types matched, return failure return VK_INCOMPLETE; } //----------------------------------------------------------------------------- /// GetTimestampResult /// \param pOutClock A pointer to a UINT64 which will hold our clock value. /// \returns The result code for initialization. //----------------------------------------------------------------------------- VkResult VktTimestampedCmdBuf::GetTimestampResult(UINT64* pOutClock) { VkResult result = VK_INCOMPLETE; if (pOutClock != nullptr) { UINT64* pTimestampData = nullptr; // We use vkCmdCopyQueryPoolResults if (m_config.mapTimestampMem == true) { result = m_pDeviceDT->MapMemory( m_config.device, m_gpuRes.timestampMem, 0, VK_WHOLE_SIZE, 0, (void**)&pTimestampData); *pOutClock = *pTimestampData; } // We use vkGetQueryPoolResults else { result = m_pDeviceDT->GetQueryPoolResults( m_config.device, m_gpuRes.timestampQueryPool, 0, 1, sizeof(UINT64), pOutClock, sizeof(UINT64), VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT); } } return result; } <commit_msg>Implement Vulkan timestamp calibration for GPU/CPU sync.<commit_after>//============================================================================== /// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file vktTimestampedCmdBuf.cpp /// \brief A wrapper for internal command buffer which holds 1 timestamp. //============================================================================== #include "vktTimestampedCmdBuf.h" //----------------------------------------------------------------------------- /// Static method that instantiates a VktTimestampedCmdBuf. /// \param config A configuration structure. /// \returns A new VktTimestampedCmdBuf instance. //----------------------------------------------------------------------------- VktTimestampedCmdBuf* VktTimestampedCmdBuf::Create(const TimestampedCmdBufConfig& config) { VktTimestampedCmdBuf* pOut = new VktTimestampedCmdBuf(); if (pOut != nullptr) { if (pOut->Init(config) != VK_SUCCESS) { delete pOut; pOut = nullptr; } } return pOut; } //----------------------------------------------------------------------------- /// Constructor. //----------------------------------------------------------------------------- VktTimestampedCmdBuf::VktTimestampedCmdBuf() : m_pInstanceDT(nullptr), m_pDeviceDT(nullptr), m_cmdPool(VK_NULL_HANDLE), m_cmdBuf(VK_NULL_HANDLE) { } //----------------------------------------------------------------------------- /// Destructor. //----------------------------------------------------------------------------- VktTimestampedCmdBuf::~VktTimestampedCmdBuf() { if (m_gpuRes.timestampQueryPool != NULL) { m_pDeviceDT->DestroyQueryPool(m_config.device, m_gpuRes.timestampQueryPool, nullptr); m_gpuRes.timestampQueryPool = NULL; } if (m_gpuRes.timestampBuffer != NULL) { m_pDeviceDT->DestroyBuffer(m_config.device, m_gpuRes.timestampBuffer, nullptr); m_gpuRes.timestampBuffer = NULL; } if (m_gpuRes.timestampMem != NULL) { m_pDeviceDT->FreeMemory(m_config.device, m_gpuRes.timestampMem, nullptr); m_gpuRes.timestampMem = NULL; } if (m_cmdBuf != VK_NULL_HANDLE) { m_pDeviceDT->FreeCommandBuffers(m_config.device, m_cmdPool, 1, &m_cmdBuf); m_cmdBuf = VK_NULL_HANDLE; } } //----------------------------------------------------------------------------- /// Perform all initialization. /// \param config A pointer to a profiler configuration structure. /// \returns The result code for initialization. //----------------------------------------------------------------------------- VkResult VktTimestampedCmdBuf::Init(const TimestampedCmdBufConfig& config) ///< [in] Pointer to profiler configuration { VkResult result = VK_INCOMPLETE; memcpy(&m_config, &config, sizeof(m_config)); if ((m_config.physicalDevice != VK_NULL_HANDLE) && (m_config.device != VK_NULL_HANDLE)) { m_pInstanceDT = instance_dispatch_table(config.physicalDevice); m_pDeviceDT = device_dispatch_table(config.device); m_pInstanceDT->GetPhysicalDeviceMemoryProperties(m_config.physicalDevice, &m_memProps); // Create command pool VkCommandPoolCreateInfo cmdPoolCreateInfo = {}; cmdPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmdPoolCreateInfo.pNext = nullptr; cmdPoolCreateInfo.queueFamilyIndex = m_config.queueFamilyIndex; cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; result = m_pDeviceDT->CreateCommandPool(m_config.device, &cmdPoolCreateInfo, nullptr, &m_cmdPool); // Create command buffer if (result == VK_SUCCESS) { VkCommandBufferAllocateInfo cmdBufAllocInfo = {}; cmdBufAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; cmdBufAllocInfo.pNext = nullptr; cmdBufAllocInfo.commandPool = m_cmdPool; cmdBufAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cmdBufAllocInfo.commandBufferCount = 1; result = m_pDeviceDT->AllocateCommandBuffers(m_config.device, &cmdBufAllocInfo, &m_cmdBuf); } // Create query pool if (result == VK_SUCCESS) { VkQueryPoolCreateInfo queryPoolCreateInfo = {}; queryPoolCreateInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; queryPoolCreateInfo.pNext = nullptr; queryPoolCreateInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; queryPoolCreateInfo.queryCount = 1; result = m_pDeviceDT->CreateQueryPool(m_config.device, &queryPoolCreateInfo, nullptr, &m_gpuRes.timestampQueryPool); } // Create timestamp buffer if (result == VK_SUCCESS) { VkBufferCreateInfo bufferCreateInfo = {}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.pNext = nullptr; bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; bufferCreateInfo.size = sizeof(UINT64); bufferCreateInfo.queueFamilyIndexCount = 0; bufferCreateInfo.pQueueFamilyIndices = nullptr; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; bufferCreateInfo.flags = 0; result = m_pDeviceDT->CreateBuffer(m_config.device, &bufferCreateInfo, nullptr, &m_gpuRes.timestampBuffer); if (result == VK_SUCCESS) { VkMemoryRequirements memReqs = {}; m_pDeviceDT->GetBufferMemoryRequirements(m_config.device, m_gpuRes.timestampBuffer, &memReqs); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.allocationSize = memReqs.size; result = MemTypeFromProps( memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex); if (result == VK_SUCCESS) { result = m_pDeviceDT->AllocateMemory(m_config.device, &allocInfo, nullptr, &m_gpuRes.timestampMem); if (result == VK_SUCCESS) { result = m_pDeviceDT->BindBufferMemory(m_config.device, m_gpuRes.timestampBuffer, m_gpuRes.timestampMem, 0); if (result == VK_SUCCESS) { void* pMappedMem = nullptr; result = m_pDeviceDT->MapMemory( m_config.device, m_gpuRes.timestampMem, 0, VK_WHOLE_SIZE, 0, &pMappedMem); if (result == VK_SUCCESS) { memset(pMappedMem, 0, (size_t)memReqs.size); m_pDeviceDT->UnmapMemory(m_config.device, m_gpuRes.timestampMem); } } } } } } // Fill in the command buffer if (result == VK_SUCCESS) { VkCommandBufferInheritanceInfo cmdBufInheritInfo = {}; cmdBufInheritInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO; cmdBufInheritInfo.pNext = nullptr; cmdBufInheritInfo.renderPass = VK_NULL_HANDLE; cmdBufInheritInfo.subpass = 0; cmdBufInheritInfo.framebuffer = VK_NULL_HANDLE; cmdBufInheritInfo.occlusionQueryEnable = VK_FALSE; cmdBufInheritInfo.queryFlags = 0; cmdBufInheritInfo.pipelineStatistics = 0; VkCommandBufferBeginInfo cmdBufBeginInfo = {}; cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmdBufBeginInfo.pNext = nullptr; cmdBufBeginInfo.flags = 0; cmdBufBeginInfo.pInheritanceInfo = &cmdBufInheritInfo; result = m_pDeviceDT->BeginCommandBuffer(m_cmdBuf, &cmdBufBeginInfo); m_pDeviceDT->CmdResetQueryPool(m_cmdBuf, m_gpuRes.timestampQueryPool, 0, 1); // Inject timestamp m_pDeviceDT->CmdWriteTimestamp( m_cmdBuf, m_config.pipelineLoc, m_gpuRes.timestampQueryPool, 0); if (m_config.mapTimestampMem == true) { m_pDeviceDT->CmdCopyQueryPoolResults( m_cmdBuf, m_gpuRes.timestampQueryPool, 0, 1, m_gpuRes.timestampBuffer, 0, sizeof(UINT64), VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT); } result = m_pDeviceDT->EndCommandBuffer(m_cmdBuf); } } return result; } //----------------------------------------------------------------------------- /// Find a memory type from available heaps. /// \param typeBits The requested mem type. /// \param reqsMask Mem requirements. /// \param pTypeIdx The output heap index. /// \returns A Vulkan result code. //----------------------------------------------------------------------------- VkResult VktTimestampedCmdBuf::MemTypeFromProps( UINT typeBits, VkFlags reqsMask, UINT* pTypeIdx) { // Search memory types to find first index with those properties for (UINT i = 0; i < 32; i++) { if ((typeBits & 1) == 1) { // Type is available, does it match user properties? if ((m_memProps.memoryTypes[i].propertyFlags & reqsMask) == reqsMask) { *pTypeIdx = i; return VK_SUCCESS; } } typeBits >>= 1; } // No memory types matched, return failure return VK_INCOMPLETE; } //----------------------------------------------------------------------------- /// GetTimestampResult /// \param pOutClock A pointer to a UINT64 which will hold our clock value. /// \returns The result code for initialization. //----------------------------------------------------------------------------- VkResult VktTimestampedCmdBuf::GetTimestampResult(UINT64* pOutClock) { VkResult result = VK_INCOMPLETE; if (pOutClock != nullptr) { UINT64* pTimestampData = nullptr; // We use vkCmdCopyQueryPoolResults if (m_config.mapTimestampMem == true) { result = m_pDeviceDT->MapMemory( m_config.device, m_gpuRes.timestampMem, 0, VK_WHOLE_SIZE, 0, (void**)&pTimestampData); *pOutClock = *pTimestampData; } // We use vkGetQueryPoolResults else { result = m_pDeviceDT->GetQueryPoolResults( m_config.device, m_gpuRes.timestampQueryPool, 0, 1, sizeof(UINT64), pOutClock, sizeof(UINT64), VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT); } } return result; } <|endoftext|>
<commit_before>// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fpdfapi/font/cpdf_type3font.h" #include <utility> #include "core/fpdfapi/font/cpdf_type3char.h" #include "core/fpdfapi/page/cpdf_form.h" #include "core/fpdfapi/page/pageint.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fxcrt/fx_system.h" #include "third_party/base/stl_util.h" #define FPDF_MAX_TYPE3_FORM_LEVEL 4 CPDF_Type3Font::CPDF_Type3Font() : m_pCharProcs(nullptr), m_pPageResources(nullptr), m_pFontResources(nullptr), m_CharLoadingDepth(0) { FXSYS_memset(m_CharWidthL, 0, sizeof(m_CharWidthL)); } CPDF_Type3Font::~CPDF_Type3Font() {} bool CPDF_Type3Font::IsType3Font() const { return true; } const CPDF_Type3Font* CPDF_Type3Font::AsType3Font() const { return this; } CPDF_Type3Font* CPDF_Type3Font::AsType3Font() { return this; } bool CPDF_Type3Font::Load() { m_pFontResources = m_pFontDict->GetDictFor("Resources"); CPDF_Array* pMatrix = m_pFontDict->GetArrayFor("FontMatrix"); FX_FLOAT xscale = 1.0f, yscale = 1.0f; if (pMatrix) { m_FontMatrix = pMatrix->GetMatrix(); xscale = m_FontMatrix.a; yscale = m_FontMatrix.d; } CPDF_Array* pBBox = m_pFontDict->GetArrayFor("FontBBox"); if (pBBox) { m_FontBBox.left = (int32_t)(pBBox->GetNumberAt(0) * xscale * 1000); m_FontBBox.bottom = (int32_t)(pBBox->GetNumberAt(1) * yscale * 1000); m_FontBBox.right = (int32_t)(pBBox->GetNumberAt(2) * xscale * 1000); m_FontBBox.top = (int32_t)(pBBox->GetNumberAt(3) * yscale * 1000); } int StartChar = m_pFontDict->GetIntegerFor("FirstChar"); CPDF_Array* pWidthArray = m_pFontDict->GetArrayFor("Widths"); if (pWidthArray && (StartChar >= 0 && StartChar < 256)) { size_t count = pWidthArray->GetCount(); if (count > 256) count = 256; if (StartChar + count > 256) count = 256 - StartChar; for (size_t i = 0; i < count; i++) { m_CharWidthL[StartChar + i] = FXSYS_round(pWidthArray->GetNumberAt(i) * xscale * 1000); } } m_pCharProcs = m_pFontDict->GetDictFor("CharProcs"); CPDF_Object* pEncoding = m_pFontDict->GetDirectObjectFor("Encoding"); if (pEncoding) { LoadPDFEncoding(pEncoding, m_BaseEncoding, &m_CharNames, false, false); if (!m_CharNames.empty()) { for (int i = 0; i < 256; i++) { m_Encoding.m_Unicodes[i] = PDF_UnicodeFromAdobeName(m_CharNames[i].c_str()); if (m_Encoding.m_Unicodes[i] == 0) { m_Encoding.m_Unicodes[i] = i; } } } } return true; } void CPDF_Type3Font::CheckType3FontMetrics() { CheckFontMetrics(); } CPDF_Type3Char* CPDF_Type3Font::LoadChar(uint32_t charcode) { if (m_CharLoadingDepth >= FPDF_MAX_TYPE3_FORM_LEVEL) return nullptr; auto it = m_CacheMap.find(charcode); if (it != m_CacheMap.end()) return it->second.get(); const FX_CHAR* name = GetAdobeCharName(m_BaseEncoding, m_CharNames, charcode); if (!name) return nullptr; CPDF_Stream* pStream = ToStream(m_pCharProcs ? m_pCharProcs->GetDirectObjectFor(name) : nullptr); if (!pStream) return nullptr; std::unique_ptr<CPDF_Type3Char> pNewChar(new CPDF_Type3Char(new CPDF_Form( m_pDocument, m_pFontResources ? m_pFontResources : m_pPageResources, pStream, nullptr))); // This can trigger recursion into this method. The content of |m_CacheMap| // can change as a result. Thus after it returns, check the cache again for // a cache hit. m_CharLoadingDepth++; pNewChar->m_pForm->ParseContent(nullptr, nullptr, pNewChar.get()); m_CharLoadingDepth--; it = m_CacheMap.find(charcode); if (it != m_CacheMap.end()) return it->second.get(); FX_FLOAT scale = m_FontMatrix.GetXUnit(); pNewChar->m_Width = (int32_t)(pNewChar->m_Width * scale + 0.5f); FX_RECT& rcBBox = pNewChar->m_BBox; CFX_FloatRect char_rect( (FX_FLOAT)rcBBox.left / 1000.0f, (FX_FLOAT)rcBBox.bottom / 1000.0f, (FX_FLOAT)rcBBox.right / 1000.0f, (FX_FLOAT)rcBBox.top / 1000.0f); if (rcBBox.right <= rcBBox.left || rcBBox.bottom >= rcBBox.top) char_rect = pNewChar->m_pForm->CalcBoundingBox(); char_rect.Transform(&m_FontMatrix); rcBBox.left = FXSYS_round(char_rect.left * 1000); rcBBox.right = FXSYS_round(char_rect.right * 1000); rcBBox.top = FXSYS_round(char_rect.top * 1000); rcBBox.bottom = FXSYS_round(char_rect.bottom * 1000); ASSERT(!pdfium::ContainsKey(m_CacheMap, charcode)); m_CacheMap[charcode] = std::move(pNewChar); CPDF_Type3Char* pCachedChar = m_CacheMap[charcode].get(); if (pCachedChar->m_pForm->GetPageObjectList()->empty()) pCachedChar->m_pForm.reset(); return pCachedChar; } int CPDF_Type3Font::GetCharWidthF(uint32_t charcode) { if (charcode >= FX_ArraySize(m_CharWidthL)) charcode = 0; if (m_CharWidthL[charcode]) return m_CharWidthL[charcode]; const CPDF_Type3Char* pChar = LoadChar(charcode); return pChar ? pChar->m_Width : 0; } FX_RECT CPDF_Type3Font::GetCharBBox(uint32_t charcode) { const CPDF_Type3Char* pChar = LoadChar(charcode); return pChar ? pChar->m_BBox : FX_RECT(); } <commit_msg>Stop using Encoding array to get unicode from charcode in Type 3 fonts<commit_after>// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fpdfapi/font/cpdf_type3font.h" #include <utility> #include "core/fpdfapi/font/cpdf_type3char.h" #include "core/fpdfapi/page/cpdf_form.h" #include "core/fpdfapi/page/pageint.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fxcrt/fx_system.h" #include "third_party/base/stl_util.h" #define FPDF_MAX_TYPE3_FORM_LEVEL 4 CPDF_Type3Font::CPDF_Type3Font() : m_pCharProcs(nullptr), m_pPageResources(nullptr), m_pFontResources(nullptr), m_CharLoadingDepth(0) { FXSYS_memset(m_CharWidthL, 0, sizeof(m_CharWidthL)); } CPDF_Type3Font::~CPDF_Type3Font() {} bool CPDF_Type3Font::IsType3Font() const { return true; } const CPDF_Type3Font* CPDF_Type3Font::AsType3Font() const { return this; } CPDF_Type3Font* CPDF_Type3Font::AsType3Font() { return this; } bool CPDF_Type3Font::Load() { m_pFontResources = m_pFontDict->GetDictFor("Resources"); CPDF_Array* pMatrix = m_pFontDict->GetArrayFor("FontMatrix"); FX_FLOAT xscale = 1.0f, yscale = 1.0f; if (pMatrix) { m_FontMatrix = pMatrix->GetMatrix(); xscale = m_FontMatrix.a; yscale = m_FontMatrix.d; } CPDF_Array* pBBox = m_pFontDict->GetArrayFor("FontBBox"); if (pBBox) { m_FontBBox.left = (int32_t)(pBBox->GetNumberAt(0) * xscale * 1000); m_FontBBox.bottom = (int32_t)(pBBox->GetNumberAt(1) * yscale * 1000); m_FontBBox.right = (int32_t)(pBBox->GetNumberAt(2) * xscale * 1000); m_FontBBox.top = (int32_t)(pBBox->GetNumberAt(3) * yscale * 1000); } int StartChar = m_pFontDict->GetIntegerFor("FirstChar"); CPDF_Array* pWidthArray = m_pFontDict->GetArrayFor("Widths"); if (pWidthArray && (StartChar >= 0 && StartChar < 256)) { size_t count = pWidthArray->GetCount(); if (count > 256) count = 256; if (StartChar + count > 256) count = 256 - StartChar; for (size_t i = 0; i < count; i++) { m_CharWidthL[StartChar + i] = FXSYS_round(pWidthArray->GetNumberAt(i) * xscale * 1000); } } m_pCharProcs = m_pFontDict->GetDictFor("CharProcs"); CPDF_Object* pEncoding = m_pFontDict->GetDirectObjectFor("Encoding"); if (pEncoding) LoadPDFEncoding(pEncoding, m_BaseEncoding, &m_CharNames, false, false); return true; } void CPDF_Type3Font::CheckType3FontMetrics() { CheckFontMetrics(); } CPDF_Type3Char* CPDF_Type3Font::LoadChar(uint32_t charcode) { if (m_CharLoadingDepth >= FPDF_MAX_TYPE3_FORM_LEVEL) return nullptr; auto it = m_CacheMap.find(charcode); if (it != m_CacheMap.end()) return it->second.get(); const FX_CHAR* name = GetAdobeCharName(m_BaseEncoding, m_CharNames, charcode); if (!name) return nullptr; CPDF_Stream* pStream = ToStream(m_pCharProcs ? m_pCharProcs->GetDirectObjectFor(name) : nullptr); if (!pStream) return nullptr; std::unique_ptr<CPDF_Type3Char> pNewChar(new CPDF_Type3Char(new CPDF_Form( m_pDocument, m_pFontResources ? m_pFontResources : m_pPageResources, pStream, nullptr))); // This can trigger recursion into this method. The content of |m_CacheMap| // can change as a result. Thus after it returns, check the cache again for // a cache hit. m_CharLoadingDepth++; pNewChar->m_pForm->ParseContent(nullptr, nullptr, pNewChar.get()); m_CharLoadingDepth--; it = m_CacheMap.find(charcode); if (it != m_CacheMap.end()) return it->second.get(); FX_FLOAT scale = m_FontMatrix.GetXUnit(); pNewChar->m_Width = (int32_t)(pNewChar->m_Width * scale + 0.5f); FX_RECT& rcBBox = pNewChar->m_BBox; CFX_FloatRect char_rect( (FX_FLOAT)rcBBox.left / 1000.0f, (FX_FLOAT)rcBBox.bottom / 1000.0f, (FX_FLOAT)rcBBox.right / 1000.0f, (FX_FLOAT)rcBBox.top / 1000.0f); if (rcBBox.right <= rcBBox.left || rcBBox.bottom >= rcBBox.top) char_rect = pNewChar->m_pForm->CalcBoundingBox(); char_rect.Transform(&m_FontMatrix); rcBBox.left = FXSYS_round(char_rect.left * 1000); rcBBox.right = FXSYS_round(char_rect.right * 1000); rcBBox.top = FXSYS_round(char_rect.top * 1000); rcBBox.bottom = FXSYS_round(char_rect.bottom * 1000); ASSERT(!pdfium::ContainsKey(m_CacheMap, charcode)); m_CacheMap[charcode] = std::move(pNewChar); CPDF_Type3Char* pCachedChar = m_CacheMap[charcode].get(); if (pCachedChar->m_pForm->GetPageObjectList()->empty()) pCachedChar->m_pForm.reset(); return pCachedChar; } int CPDF_Type3Font::GetCharWidthF(uint32_t charcode) { if (charcode >= FX_ArraySize(m_CharWidthL)) charcode = 0; if (m_CharWidthL[charcode]) return m_CharWidthL[charcode]; const CPDF_Type3Char* pChar = LoadChar(charcode); return pChar ? pChar->m_Width : 0; } FX_RECT CPDF_Type3Font::GetCharBBox(uint32_t charcode) { const CPDF_Type3Char* pChar = LoadChar(charcode); return pChar ? pChar->m_BBox : FX_RECT(); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; TEST_F(GtkKeyBindingsHandlerTest, MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <commit_msg>Mark the GtkKeyBindingsHandlerTest tests as flaky since they don't work in a chroot.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <|endoftext|>
<commit_before>#include <iostream> #include "../include/PreAllocString.h" int main() { CREATE(str25, 25); printf("Size: %u\n", static_cast<unsigned int>(str25.SizeOf())); const char *cstr = "fester string"; printf("String: %s\n", str25); str25 += 'c'; str25.AddWhiteSpace(); printf("String: %s\n", str25); str25 += "Blabla"; printf("String: %s\n", str25); printf("Length: %u\n", static_cast<unsigned int>(str25.GetLength())); str25 += cstr; printf("String: %s\n", str25); printf("Length: %u\n", static_cast<unsigned int>(str25.GetLength())); CREATE(str0, 0); printf("Size: %u\n", static_cast<unsigned int>(str0.SizeOf())); printf("String: %s\n", str0); str0 += 'c'; str0.AddWhiteSpace(); printf("String: %s\n", str0); str0 += "Blabla"; printf("String: %s\n", str0); printf("Length: %u\n", static_cast<unsigned int>(str0.GetLength())); str0 += cstr; printf("String: %s\n", str0); printf("Length: %u\n", static_cast<unsigned int>(str0.GetLength())); CREATE(str1, 1); printf("Size: %u\n", static_cast<unsigned int>(str1.SizeOf())); printf("String: %s\n", str1); str1 += 'c'; str1.AddWhiteSpace(); printf("String: %s\n", str1); str1 += "Blabla"; printf("String: %s\n", str1); printf("Length: %u\n", static_cast<unsigned int>(str1.GetLength())); str1 += cstr; printf("String: %s\n", str1); printf("Length: %u\n", static_cast<unsigned int>(str1.GetLength())); return 0; /* CREATE(test_string_5,5); CREATE(test_string_20,20); CREATE(test_string_100,100); int counter=1; printf("-->Test %d. Overflow:\n",counter++); */ /* Test overflow *//* test_string_5 = "abcdefghijk"; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n",\ (const char*)test_string_5,\ test_string_5.GetLength(),\ test_string_5.SizeOf()); printf("-->Test %d. char operators:\n",counter++); */ /* Test operator = for char *//* test_string_20 = 'a'; test_string_20.AddWhiteSpace(); */ /* Test operator += for char *//* test_string_20 += 'b'; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n", (const char*)test_string_20, test_string_20.GetLength(), test_string_20.SizeOf()); printf("-->Test %d. String operators:\n",counter++); */ /* Test operator = for char array*//* test_string_100 = "abcdef"; test_string_100.AddWhiteSpace(); */ /* Test operator += for char array*//* test_string_100 += "ghijklo"; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n", (const char*)test_string_100, test_string_100.GetLength(), test_string_100.SizeOf()); printf("-->Test %d. Array operator\n\t\tarray[%d]\t=\tValue: %c\n\t\tarray[%d]\t=\tValue: %c\n", counter++, 1, test_string_100[1], 101, test_string_100[101]); test_string_100[1]; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n",\ (const char*)test_string_100,\ test_string_100.GetLength(),\ test_string_100.SizeOf()); printf("-->Test %d. indirekt test of AddFormat and Empty:\n",counter++); test_string_100="abcdefghijklmnopqrstuvwxyz"; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n",\ (const char*)test_string_100,\ test_string_100.GetLength(),\ test_string_100.SizeOf()); //CREATE(test_string20_2,20); */ /*printf("-->Test %d. Copy Class:\n",counter++); *test_string20_2="zyxw"; * fails-->> test_string_20=test_string20_2; *//* printf("--> Test ENDE \n"); }<commit_msg>fix comment problems in main<commit_after>#include <iostream> #include "../include/PreAllocString.h" int main() { CREATE(str25, 25); printf("Size: %u\n", static_cast<unsigned int>(str25.SizeOf())); const char *cstr = "fester string"; printf("String: %s\n", str25); str25 += 'c'; str25.AddWhiteSpace(); printf("String: %s\n", str25); str25 += "Blabla"; printf("String: %s\n", str25); printf("Length: %u\n", static_cast<unsigned int>(str25.GetLength())); str25 += cstr; printf("String: %s\n", str25); printf("Length: %u\n", static_cast<unsigned int>(str25.GetLength())); CREATE(str0, 0); printf("Size: %u\n", static_cast<unsigned int>(str0.SizeOf())); printf("String: %s\n", str0); str0 += 'c'; str0.AddWhiteSpace(); printf("String: %s\n", str0); str0 += "Blabla"; printf("String: %s\n", str0); printf("Length: %u\n", static_cast<unsigned int>(str0.GetLength())); str0 += cstr; printf("String: %s\n", str0); printf("Length: %u\n", static_cast<unsigned int>(str0.GetLength())); CREATE(str1, 1); printf("Size: %u\n", static_cast<unsigned int>(str1.SizeOf())); printf("String: %s\n", str1); str1 += 'c'; str1.AddWhiteSpace(); printf("String: %s\n", str1); str1 += "Blabla"; printf("String: %s\n", str1); printf("Length: %u\n", static_cast<unsigned int>(str1.GetLength())); str1 += cstr; printf("String: %s\n", str1); printf("Length: %u\n", static_cast<unsigned int>(str1.GetLength())); return 0; /* CREATE(test_string_5,5); CREATE(test_string_20,20); CREATE(test_string_100,100); int counter=1; printf("-->Test %d. Overflow:\n",counter++); */ /* Test overflow *//* test_string_5 = "abcdefghijk"; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n",\ (const char*)test_string_5,\ test_string_5.GetLength(),\ test_string_5.SizeOf()); printf("-->Test %d. char operators:\n",counter++); */ /* Test operator = for char *//* test_string_20 = 'a'; test_string_20.AddWhiteSpace(); */ /* Test operator += for char *//* test_string_20 += 'b'; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n", (const char*)test_string_20, test_string_20.GetLength(), test_string_20.SizeOf()); printf("-->Test %d. String operators:\n",counter++); */ /* Test operator = for char array*//* test_string_100 = "abcdef"; test_string_100.AddWhiteSpace(); */ /* Test operator += for char array*//* test_string_100 += "ghijklo"; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n", (const char*)test_string_100, test_string_100.GetLength(), test_string_100.SizeOf()); printf("-->Test %d. Array operator\n\t\tarray[%d]\t=\tValue: %c\n\t\tarray[%d]\t=\tValue: %c\n", counter++, 1, test_string_100[1], 101, test_string_100[101]); test_string_100[1]; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n",\ (const char*)test_string_100,\ test_string_100.GetLength(),\ test_string_100.SizeOf()); printf("-->Test %d. indirekt test of AddFormat and Empty:\n",counter++); test_string_100="abcdefghijklmnopqrstuvwxyz"; printf("\t\tInhalt: %s\t Länge: %d\t Maximum: %d\n",\ (const char*)test_string_100,\ test_string_100.GetLength(),\ test_string_100.SizeOf()); //CREATE(test_string20_2,20); */ /*printf("-->Test %d. Copy Class:\n",counter++); *test_string20_2="zyxw"; * fails-->> test_string_20=test_string20_2; */ printf("--> Test ENDE \n"); } <|endoftext|>
<commit_before>int source(); void sink(...) {}; void arithAssignments(int source1, int clean1) { sink(clean1); // clean clean1 += source1; clean1 += 1; sink(clean1); // tainted clean1 = source1 = 1; sink(clean1); // clean source1 = clean1 = source(); source1++; ++source1; source1 += 1; sink(source1); // tainted sink(++source1); // tainted } // --- globals --- int increment(int x) {return x + 1;} int zero(int x) {return 0;} int global1 = 0; int global2 = source(); int global3 = global2 + 1; int global4 = increment(source()); int global5 = zero(source()); int global6, global7, global8, global9, global10; void do_source() { global6 = 0; global7 = source(); global8 = global7 + 1; global9 = increment(source()); global10 = zero(source()); sink(global6); sink(global7); // tainted sink(global8); // tainted sink(global9); // tainted sink(global10); } void do_sink() { sink(global1); sink(global2); // tainted [NOT DETECTED] sink(global3); // tainted [NOT DETECTED] sink(global4); // tainted [NOT DETECTED] sink(global5); sink(global6); sink(global7); // tainted [NOT DETECTED] sink(global8); // tainted [NOT DETECTED] sink(global9); // tainted [NOT DETECTED] sink(global10); } void global_test() { do_source(); do_sink(); } // --- class fields --- class MyClass { public: MyClass() : a(0), b(source()) { c = source(); d = 0; } void myMethod() { d = source(); } int a, b, c, d; }; void class_field_test() { MyClass mc1, mc2; mc1.myMethod(); sink(mc1.a); sink(mc1.b); // tainted [NOT DETECTED with IR] sink(mc1.c); // tainted [NOT DETECTED with IR] sink(mc1.d); // tainted [NOT DETECTED with IR] sink(mc2.a); sink(mc2.b); // tainted [NOT DETECTED with IR] sink(mc2.c); // tainted [NOT DETECTED with IR] sink(mc2.d); } // --- arrays --- void array_test(int i) { int arr1[10] = {0}; int arr2[10] = {0}; int arr3[10] = {0}; arr1[5] = source(); arr2[i] = source(); arr3[5] = 0; sink(arr1[5]); // tainted sink(arr1[i]); // tainted [NOT DETECTED] sink(arr2[5]); // tainted [NOT DETECTED] sink(arr2[i]); // tainted [NOT DETECTED] sink(arr3[5]); sink(arr3[i]); } // --- pointers --- void pointer_test() { int t1 = source(); int t2 = 1; int t3 = 1; int *p1 = &t1; int *p2 = &t2; int *p3 = &t3; *p2 = source(); sink(*p1); // tainted sink(*p2); // tainted [NOT DETECTED] sink(*p3); p3 = &t1; sink(*p3); // tainted *p3 = 0; sink(*p3); // [FALSE POSITIVE] } // --- return values --- int select(int i, int a, int b) { if (i == 1) { return a; } else { return b; } } void fn_test(int i) { sink(select(i, 1, source())); // tainted } // --- strings --- char *strcpy(char *destination, const char *source); char *strcat(char *destination, const char *source); namespace strings { char *source(); // char* source void strings_test1() { char *tainted = source(); char buffer[1024] = {0}; sink(source()); // tainted sink(tainted); // tainted strcpy(buffer, "Hello, "); sink(buffer); strcat(buffer, tainted); sink(buffer); // tainted } } // --- pass by reference --- namespace refs { void callee(int *p) { sink(*p); // tainted } void caller() { int x = source(); callee(&x); } } void *memcpy(void *dest, void *src, int len); void test_memcpy(int *source) { int x; memcpy(&x, source, sizeof(int)); sink(x); } // --- std::swap --- namespace std { template<class T> constexpr void swap(T& a, T& b); } void test_swap() { int x, y; x = source(); y = 0; sink(x); // tainted sink(y); // clean std::swap(x, y); sink(x); // clean [FALSE POSITIVE] sink(y); // tainted } // --- lambdas --- void test_lambdas() { int t = source(); int u = 0; int v = 0; int w = 0; auto a = [t, u]() -> int { sink(t); // tainted sink(u); // clean return t; }; sink(a()); // tainted auto b = [&] { sink(t); // tainted sink(u); // clean v = source(); // (v is reference captured) }; b(); sink(v); // tainted [NOT DETECTED] auto c = [=] { sink(t); // tainted sink(u); // clean }; c(); auto d = [](int a, int b) { sink(a); // tainted sink(b); // clean }; d(t, u); auto e = [](int &a, int &b, int &c) { sink(a); // tainted sink(b); // clean c = source(); }; e(t, u, w); sink(w); // tainted } // --- taint through return value --- int id(int x) { return x; } void test_return() { int x, y, z, t; t = source(); x = 0; y = 0; z = 0; sink(t); // tainted sink(x); sink(y); sink(z); x = id(t); y = id(id(t)); z = id(z); sink(t); // tainted sink(x); // tainted sink(y); // tainted sink(z); } // --- taint through parameters --- void myAssign1(int &a, int &b) { a = b; } void myAssign2(int &a, int b) { a = b; } void myAssign3(int *a, int b) { *a = b; } void myAssign4(int *a, int b) { int c; c = b + 1; *a = c; } void myNotAssign(int &a, int &b) { a = a + 1; b = b + 1; } void test_outparams() { int t, a, b, c, d, e; t = source(); a = 0; b = 0; c = 0; d = 0; e = 0; sink(t); // tainted sink(a); sink(b); sink(c); sink(d); sink(e); myAssign1(a, t); myAssign2(b, t); myAssign3(&c, t); myAssign4(&d, t); myNotAssign(e, t); sink(t); // tainted sink(a); // tainted sink(b); // tainted sink(c); // tainted [NOT DETECTED] sink(d); // tainted [NOT DETECTED] sink(e); } // --- strdup --- typedef unsigned long size_t; char *strdup(const char *s1); char *strndup(const char *s1, size_t n); wchar_t* wcsdup(const wchar_t* s1); void test_strdup(char *source) { char *a, *b, *c; a = strdup(source); b = strdup("hello, world"); c = strndup(source, 100); sink(a); // tainted sink(b); sink(c); // tainted } void test_strndup(int source) { char *a; a = strndup("hello, world", source); sink(a); // tainted } void test_wcsdup(wchar_t *source) { wchar_t *a, *b; a = wcsdup(source); b = wcsdup(L"hello, world"); sink(a); // tainted sink(b); } // --- qualifiers --- class MyClass2 { public: MyClass2(int value); void setMember(int value); int getMember(); int member; }; class MyClass3 { public: MyClass3(const char *string); void setString(const char *string); const char *getString(); const char *buffer; }; void test_qualifiers() { MyClass2 a(0), b(0), *c; MyClass3 d(""); sink(a); sink(a.getMember()); a.setMember(source()); sink(a); // tainted sink(a.getMember()); // tainted sink(b); sink(b.getMember()); b.member = source(); sink(b); // tainted sink(b.member); // tainted sink(b.getMember()); c = new MyClass2(0); sink(c); sink(c->getMember()); c->setMember(source()); sink(c); // tainted (deref) sink(c->getMember()); // tainted delete c; sink(d); sink(d.getString()); d.setString(strings::source()); sink(d); // tainted sink(d.getString()); // tainted } // --- non-standard swap --- void swop(int &a, int &b) { int c = a; a = b; b = c; } void test_swop() { int x, y; x = source(); y = 0; sink(x); // tainted sink(y); // clean swop(x, y); sink(x); // clean [FALSE POSITIVE] sink(y); // tainted } // --- getdelim --- struct FILE; int getdelim(char ** lineptr, size_t * n, int delimiter, FILE *stream); void test_getdelim(FILE* source1) { char* line = nullptr; size_t n; getdelim(&line, &n, '\n', source1); sink(line); } namespace std { template <class T> T &&move(T &t) noexcept; // simplified signature } namespace IntWrapper { struct Class { int data; Class() = default; Class(const Class &that) : data(that.data) {} Class &operator=(const Class &that) { auto tmp = that; swap(tmp); return *this; } Class& operator=(Class&& that) { swap(that); return *this; } void swap(Class &that) noexcept { using std::swap; swap(data, that.data); } }; // For ADL void swap(Class &x, Class &y) { x.swap(y); } } // namespace ImplementationDetails // using std::swap; void test_copy_assignment_operator() { IntWrapper::Class x; IntWrapper::Class y; x.data = source(); sink(x.data); // tainted sink(y.data); // clean y = x; sink(y.data); // tainted [FALSE NEGATIVE in IR] sink(x.data); // tainted IntWrapper::Class z1, z2; z1.data = source(); sink(z1.data); // tainted swap(z1, z2); sink(z2.data); // tainted sink(z1.data); // clean [FALSE POSITIVE] } void test_move_assignment_operator() { IntWrapper::Class x; IntWrapper::Class y; x.data = source(); sink(x.data); // tainted sink(y.data); // clean y = std::move(x); sink(y.data); // tainted [FALSE NEGATIVE in IR] sink(x.data); // tainted }<commit_msg>Update cpp/ql/test/library-tests/dataflow/taint-tests/taint.cpp<commit_after>int source(); void sink(...) {}; void arithAssignments(int source1, int clean1) { sink(clean1); // clean clean1 += source1; clean1 += 1; sink(clean1); // tainted clean1 = source1 = 1; sink(clean1); // clean source1 = clean1 = source(); source1++; ++source1; source1 += 1; sink(source1); // tainted sink(++source1); // tainted } // --- globals --- int increment(int x) {return x + 1;} int zero(int x) {return 0;} int global1 = 0; int global2 = source(); int global3 = global2 + 1; int global4 = increment(source()); int global5 = zero(source()); int global6, global7, global8, global9, global10; void do_source() { global6 = 0; global7 = source(); global8 = global7 + 1; global9 = increment(source()); global10 = zero(source()); sink(global6); sink(global7); // tainted sink(global8); // tainted sink(global9); // tainted sink(global10); } void do_sink() { sink(global1); sink(global2); // tainted [NOT DETECTED] sink(global3); // tainted [NOT DETECTED] sink(global4); // tainted [NOT DETECTED] sink(global5); sink(global6); sink(global7); // tainted [NOT DETECTED] sink(global8); // tainted [NOT DETECTED] sink(global9); // tainted [NOT DETECTED] sink(global10); } void global_test() { do_source(); do_sink(); } // --- class fields --- class MyClass { public: MyClass() : a(0), b(source()) { c = source(); d = 0; } void myMethod() { d = source(); } int a, b, c, d; }; void class_field_test() { MyClass mc1, mc2; mc1.myMethod(); sink(mc1.a); sink(mc1.b); // tainted [NOT DETECTED with IR] sink(mc1.c); // tainted [NOT DETECTED with IR] sink(mc1.d); // tainted [NOT DETECTED with IR] sink(mc2.a); sink(mc2.b); // tainted [NOT DETECTED with IR] sink(mc2.c); // tainted [NOT DETECTED with IR] sink(mc2.d); } // --- arrays --- void array_test(int i) { int arr1[10] = {0}; int arr2[10] = {0}; int arr3[10] = {0}; arr1[5] = source(); arr2[i] = source(); arr3[5] = 0; sink(arr1[5]); // tainted sink(arr1[i]); // tainted [NOT DETECTED] sink(arr2[5]); // tainted [NOT DETECTED] sink(arr2[i]); // tainted [NOT DETECTED] sink(arr3[5]); sink(arr3[i]); } // --- pointers --- void pointer_test() { int t1 = source(); int t2 = 1; int t3 = 1; int *p1 = &t1; int *p2 = &t2; int *p3 = &t3; *p2 = source(); sink(*p1); // tainted sink(*p2); // tainted [NOT DETECTED] sink(*p3); p3 = &t1; sink(*p3); // tainted *p3 = 0; sink(*p3); // [FALSE POSITIVE] } // --- return values --- int select(int i, int a, int b) { if (i == 1) { return a; } else { return b; } } void fn_test(int i) { sink(select(i, 1, source())); // tainted } // --- strings --- char *strcpy(char *destination, const char *source); char *strcat(char *destination, const char *source); namespace strings { char *source(); // char* source void strings_test1() { char *tainted = source(); char buffer[1024] = {0}; sink(source()); // tainted sink(tainted); // tainted strcpy(buffer, "Hello, "); sink(buffer); strcat(buffer, tainted); sink(buffer); // tainted } } // --- pass by reference --- namespace refs { void callee(int *p) { sink(*p); // tainted } void caller() { int x = source(); callee(&x); } } void *memcpy(void *dest, void *src, int len); void test_memcpy(int *source) { int x; memcpy(&x, source, sizeof(int)); sink(x); } // --- std::swap --- namespace std { template<class T> constexpr void swap(T& a, T& b); } void test_swap() { int x, y; x = source(); y = 0; sink(x); // tainted sink(y); // clean std::swap(x, y); sink(x); // clean [FALSE POSITIVE] sink(y); // tainted } // --- lambdas --- void test_lambdas() { int t = source(); int u = 0; int v = 0; int w = 0; auto a = [t, u]() -> int { sink(t); // tainted sink(u); // clean return t; }; sink(a()); // tainted auto b = [&] { sink(t); // tainted sink(u); // clean v = source(); // (v is reference captured) }; b(); sink(v); // tainted [NOT DETECTED] auto c = [=] { sink(t); // tainted sink(u); // clean }; c(); auto d = [](int a, int b) { sink(a); // tainted sink(b); // clean }; d(t, u); auto e = [](int &a, int &b, int &c) { sink(a); // tainted sink(b); // clean c = source(); }; e(t, u, w); sink(w); // tainted } // --- taint through return value --- int id(int x) { return x; } void test_return() { int x, y, z, t; t = source(); x = 0; y = 0; z = 0; sink(t); // tainted sink(x); sink(y); sink(z); x = id(t); y = id(id(t)); z = id(z); sink(t); // tainted sink(x); // tainted sink(y); // tainted sink(z); } // --- taint through parameters --- void myAssign1(int &a, int &b) { a = b; } void myAssign2(int &a, int b) { a = b; } void myAssign3(int *a, int b) { *a = b; } void myAssign4(int *a, int b) { int c; c = b + 1; *a = c; } void myNotAssign(int &a, int &b) { a = a + 1; b = b + 1; } void test_outparams() { int t, a, b, c, d, e; t = source(); a = 0; b = 0; c = 0; d = 0; e = 0; sink(t); // tainted sink(a); sink(b); sink(c); sink(d); sink(e); myAssign1(a, t); myAssign2(b, t); myAssign3(&c, t); myAssign4(&d, t); myNotAssign(e, t); sink(t); // tainted sink(a); // tainted sink(b); // tainted sink(c); // tainted [NOT DETECTED] sink(d); // tainted [NOT DETECTED] sink(e); } // --- strdup --- typedef unsigned long size_t; char *strdup(const char *s1); char *strndup(const char *s1, size_t n); wchar_t* wcsdup(const wchar_t* s1); void test_strdup(char *source) { char *a, *b, *c; a = strdup(source); b = strdup("hello, world"); c = strndup(source, 100); sink(a); // tainted sink(b); sink(c); // tainted } void test_strndup(int source) { char *a; a = strndup("hello, world", source); sink(a); // tainted } void test_wcsdup(wchar_t *source) { wchar_t *a, *b; a = wcsdup(source); b = wcsdup(L"hello, world"); sink(a); // tainted sink(b); } // --- qualifiers --- class MyClass2 { public: MyClass2(int value); void setMember(int value); int getMember(); int member; }; class MyClass3 { public: MyClass3(const char *string); void setString(const char *string); const char *getString(); const char *buffer; }; void test_qualifiers() { MyClass2 a(0), b(0), *c; MyClass3 d(""); sink(a); sink(a.getMember()); a.setMember(source()); sink(a); // tainted sink(a.getMember()); // tainted sink(b); sink(b.getMember()); b.member = source(); sink(b); // tainted sink(b.member); // tainted sink(b.getMember()); c = new MyClass2(0); sink(c); sink(c->getMember()); c->setMember(source()); sink(c); // tainted (deref) sink(c->getMember()); // tainted delete c; sink(d); sink(d.getString()); d.setString(strings::source()); sink(d); // tainted sink(d.getString()); // tainted } // --- non-standard swap --- void swop(int &a, int &b) { int c = a; a = b; b = c; } void test_swop() { int x, y; x = source(); y = 0; sink(x); // tainted sink(y); // clean swop(x, y); sink(x); // clean [FALSE POSITIVE] sink(y); // tainted } // --- getdelim --- struct FILE; int getdelim(char ** lineptr, size_t * n, int delimiter, FILE *stream); void test_getdelim(FILE* source1) { char* line = nullptr; size_t n; getdelim(&line, &n, '\n', source1); sink(line); } namespace std { template <class T> T &&move(T &t) noexcept; // simplified signature } namespace IntWrapper { struct Class { int data; Class() = default; Class(const Class &that) : data(that.data) {} Class &operator=(const Class &that) { auto tmp = that; swap(tmp); return *this; } Class& operator=(Class&& that) { swap(that); return *this; } void swap(Class &that) noexcept { using std::swap; swap(data, that.data); } }; // For ADL void swap(Class &x, Class &y) { x.swap(y); } } // namespace IntWrapper // using std::swap; void test_copy_assignment_operator() { IntWrapper::Class x; IntWrapper::Class y; x.data = source(); sink(x.data); // tainted sink(y.data); // clean y = x; sink(y.data); // tainted [FALSE NEGATIVE in IR] sink(x.data); // tainted IntWrapper::Class z1, z2; z1.data = source(); sink(z1.data); // tainted swap(z1, z2); sink(z2.data); // tainted sink(z1.data); // clean [FALSE POSITIVE] } void test_move_assignment_operator() { IntWrapper::Class x; IntWrapper::Class y; x.data = source(); sink(x.data); // tainted sink(y.data); // clean y = std::move(x); sink(y.data); // tainted [FALSE NEGATIVE in IR] sink(x.data); // tainted } <|endoftext|>
<commit_before>#ifndef EXPORTELEMENTVISITOR_HPP_DEFINED #define EXPORTELEMENTVISITOR_HPP_DEFINED #include "Callbacks.hpp" #include "GeoCoordinate.hpp" #include "entities/Element.hpp" #include "entities/Node.hpp" #include "entities/Area.hpp" #include "entities/Way.hpp" #include "entities/Relation.hpp" #include "heightmap/ElevationProvider.hpp" #include "mapcss/StyleProvider.hpp" #include <string> #include <vector> /// Exports elements to external code using element callback. struct ExportElementVisitor : public utymap::entities::ElementVisitor { using Tags = std::vector<utymap::formats::Tag>; using Coordinates = std::vector<utymap::GeoCoordinate>; ExportElementVisitor(const utymap::QuadKey& quadKey, utymap::index::StringTable& stringTable, const utymap::mapcss::StyleProvider& styleProvider, const utymap::heightmap::ElevationProvider& eleProvider, OnElementLoaded* elementCallback) : quadKey_(quadKey), stringTable_(stringTable), styleProvider_(styleProvider), eleProvider_(eleProvider), elementCallback_(elementCallback) { } void visitNode(const utymap::entities::Node& node) override { visitElement(node, Coordinates{ node.coordinate }); } void visitWay(const utymap::entities::Way& way) override { visitElement(way, way.coordinates); } void visitArea(const utymap::entities::Area& area) override { visitElement(area, area.coordinates); } void visitRelation(const utymap::entities::Relation& relation) override { // TODO not supported yet. } private: void visitElement(const utymap::entities::Element& element, const Coordinates& coordinates) { // convert tags std::vector<const char*> ctags; tagStrings_.reserve(element.tags.size() * 2); ctags.reserve(element.tags.size() * 2); for (std::size_t i = 0; i < element.tags.size(); ++i) { const utymap::entities::Tag& tag = element.tags[i]; tagStrings_.push_back(stringTable_.getString(tag.key)); tagStrings_.push_back(stringTable_.getString(tag.value)); ctags.push_back(tagStrings_[tagStrings_.size() - 2].c_str()); ctags.push_back(tagStrings_[tagStrings_.size() - 1].c_str()); } // convert geometry std::vector<double> vertices; vertices.reserve(coordinates.size() * 3); for (std::size_t i = 0; i < coordinates.size(); ++i) { const utymap::GeoCoordinate coordinate = coordinates[i]; vertices.push_back(coordinate.longitude); vertices.push_back(coordinate.latitude); vertices.push_back(eleProvider_.getElevation(quadKey_, coordinate)); } // convert style utymap::mapcss::Style style = styleProvider_.forElement(element, levelOfDetail_); std::vector<const char*> cstyles; auto declarations = style.declarations(); styleStrings_.reserve(declarations.size() * 2); cstyles.reserve(declarations.size()); for (const auto& declaration : declarations) { styleStrings_.push_back(stringTable_.getString(declaration->key())); styleStrings_.push_back(declaration->value()); cstyles.push_back(styleStrings_[styleStrings_.size() - 2].c_str()); cstyles.push_back(styleStrings_[styleStrings_.size() - 1].c_str()); } elementCallback_(element.id, ctags.data(), static_cast<int>(ctags.size()), vertices.data(), static_cast<int>(vertices.size()), cstyles.data(), static_cast<int>(cstyles.size())); // NOTE clear vectors after raw array data is consumed by external code tagStrings_.clear(); styleStrings_.clear(); } const utymap::QuadKey& quadKey_; utymap::index::StringTable& stringTable_; const utymap::mapcss::StyleProvider& styleProvider_; const utymap::heightmap::ElevationProvider& eleProvider_; int levelOfDetail_; OnElementLoaded* elementCallback_; std::vector<std::string> tagStrings_; // holds temporary tag strings std::vector<std::string> styleStrings_; // holds temporary style strings }; #endif // EXPORTELEMENTVISITOR_HPP_DEFINED <commit_msg>core: fix issue in element exporting<commit_after>#ifndef EXPORTELEMENTVISITOR_HPP_DEFINED #define EXPORTELEMENTVISITOR_HPP_DEFINED #include "Callbacks.hpp" #include "GeoCoordinate.hpp" #include "entities/Element.hpp" #include "entities/Node.hpp" #include "entities/Area.hpp" #include "entities/Way.hpp" #include "entities/Relation.hpp" #include "heightmap/ElevationProvider.hpp" #include "mapcss/StyleProvider.hpp" #include <string> #include <vector> /// Exports elements to external code using element callback. struct ExportElementVisitor : public utymap::entities::ElementVisitor { using Tags = std::vector<utymap::formats::Tag>; using Coordinates = std::vector<utymap::GeoCoordinate>; ExportElementVisitor(const utymap::QuadKey& quadKey, utymap::index::StringTable& stringTable, const utymap::mapcss::StyleProvider& styleProvider, const utymap::heightmap::ElevationProvider& eleProvider, OnElementLoaded* elementCallback) : quadKey_(quadKey), stringTable_(stringTable), styleProvider_(styleProvider), eleProvider_(eleProvider), elementCallback_(elementCallback) { } void visitNode(const utymap::entities::Node& node) override { visitElement(node, Coordinates{ node.coordinate }); } void visitWay(const utymap::entities::Way& way) override { visitElement(way, way.coordinates); } void visitArea(const utymap::entities::Area& area) override { visitElement(area, area.coordinates); } void visitRelation(const utymap::entities::Relation& relation) override { // TODO not supported yet. } private: void visitElement(const utymap::entities::Element& element, const Coordinates& coordinates) { // convert tags std::vector<const char*> ctags; tagStrings_.reserve(element.tags.size() * 2); ctags.reserve(element.tags.size() * 2); for (std::size_t i = 0; i < element.tags.size(); ++i) { const utymap::entities::Tag& tag = element.tags[i]; tagStrings_.push_back(stringTable_.getString(tag.key)); tagStrings_.push_back(stringTable_.getString(tag.value)); ctags.push_back(tagStrings_[tagStrings_.size() - 2].c_str()); ctags.push_back(tagStrings_[tagStrings_.size() - 1].c_str()); } // convert geometry std::vector<double> vertices; vertices.reserve(coordinates.size() * 3); for (std::size_t i = 0; i < coordinates.size(); ++i) { const utymap::GeoCoordinate coordinate = coordinates[i]; vertices.push_back(coordinate.longitude); vertices.push_back(coordinate.latitude); vertices.push_back(eleProvider_.getElevation(quadKey_, coordinate)); } // convert style utymap::mapcss::Style style = styleProvider_.forElement(element, quadKey_.levelOfDetail); std::vector<const char*> cstyles; auto declarations = style.declarations(); styleStrings_.reserve(declarations.size() * 2); cstyles.reserve(declarations.size()); for (const auto& declaration : declarations) { styleStrings_.push_back(stringTable_.getString(declaration->key())); styleStrings_.push_back(declaration->value()); cstyles.push_back(styleStrings_[styleStrings_.size() - 2].c_str()); cstyles.push_back(styleStrings_[styleStrings_.size() - 1].c_str()); } elementCallback_(element.id, ctags.data(), static_cast<int>(ctags.size()), vertices.data(), static_cast<int>(vertices.size()), cstyles.data(), static_cast<int>(cstyles.size())); // NOTE clear vectors after raw array data is consumed by external code tagStrings_.clear(); styleStrings_.clear(); } const utymap::QuadKey& quadKey_; utymap::index::StringTable& stringTable_; const utymap::mapcss::StyleProvider& styleProvider_; const utymap::heightmap::ElevationProvider& eleProvider_; OnElementLoaded* elementCallback_; std::vector<std::string> tagStrings_; // holds temporary tag strings std::vector<std::string> styleStrings_; // holds temporary style strings }; #endif // EXPORTELEMENTVISITOR_HPP_DEFINED <|endoftext|>
<commit_before>#include "lsys/LSystemParser.hpp" #include "lsys/StringTurtle.hpp" #include <boost/test/unit_test.hpp> using namespace utymap::lsys; using namespace utymap::tests; namespace { const double ProbabilityPrecision = 0.01; const std::string SimpleGrammar = "generations: 3\n" "angle: 45\n" "scale: 0.1\n" "axiom: D F ab G G F K\n" "F(1) -> F G\n" "G(0.8) -> F\n" "G(0.2) -> G G G G ab\n" "ab -> G G F ab"; std::shared_ptr<MoveForwardRule> move() { return std::make_shared<MoveForwardRule>(); } std::shared_ptr<JumpForwardRule> jump() { return std::make_shared<JumpForwardRule>(); } std::shared_ptr<WordRule> A() { return std::make_shared<WordRule>("ab"); } } BOOST_AUTO_TEST_SUITE(Lsys_LSystemParser) BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasGenerations) { BOOST_CHECK_EQUAL(LSystemParser().parse(SimpleGrammar).generations, 3); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasAngle) { BOOST_CHECK_CLOSE(LSystemParser().parse(SimpleGrammar).angle, 45, ProbabilityPrecision); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasScale) { BOOST_CHECK_CLOSE(LSystemParser().parse(SimpleGrammar).scale, 0.1, ProbabilityPrecision); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasExpectedAmountOfAxiomRules) { BOOST_CHECK_EQUAL(LSystemParser().parse(SimpleGrammar).axiom.size(), 7); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasExpectedAmountOfProductions) { auto lsystem = LSystemParser().parse(SimpleGrammar); BOOST_CHECK_EQUAL(lsystem.productions.size(), 3); BOOST_CHECK_EQUAL(lsystem.productions[move()].size(), 1); BOOST_CHECK_CLOSE(lsystem.productions[move()].at(0).first, 1, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[move()].at(0).second.size(), 2); BOOST_CHECK_EQUAL(lsystem.productions[jump()].size(), 2); BOOST_CHECK_CLOSE(lsystem.productions[jump()].at(0).first, 0.8, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[jump()].at(0).second.size(), 1); BOOST_CHECK_CLOSE(lsystem.productions[jump()].at(1).first, 0.2, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[jump()].at(1).second.size(), 5); BOOST_CHECK_EQUAL(lsystem.productions[A()].size(), 1); BOOST_CHECK_CLOSE(lsystem.productions[A()].at(0).first, 1, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[A()].at(0).second.size(), 4); } BOOST_AUTO_TEST_CASE(GivenGrammarWithComment_WhenParse_ThenSkipsCommentLine) { const std::string grammar = "generations: 3\n" "#angle:35\n" "angle: 45\n" "#angle:55\n" "scale: 1.2\n" "axiom: A\n" "A -> G G"; BOOST_CHECK_EQUAL(LSystemParser().parse(grammar).angle, 45); } BOOST_AUTO_TEST_CASE(GivenGrammarWithProbabilities_WhenParse_ThenStringTurtleBuildsProperPath) { StringTurtle turtle; const std::string grammar = "generations: 2\n" "angle: 45\n" "scale: 1.2\n" "axiom: A G\n" "G(0) -> G\n" "G(1) -> F F\n" "F -> G\n" "A -> G G"; turtle.run(LSystemParser().parse(grammar)); BOOST_CHECK_EQUAL(turtle.path, "FFFFGG"); } BOOST_AUTO_TEST_CASE(GivenGrammarWithWords_WhenParse_ThenStringTurtleBuildsProperPath) { StringTurtle turtle; const std::string grammar = "generations: 1\n" "angle: 45\n" "scale: 1.2\n" "axiom: root F G leaf\n" "root(0) -> G\n" "root(1) -> F trunk\n" "G -> F\n" "leaf -> trunk G leaf"; turtle.run(LSystemParser().parse(grammar)); BOOST_CHECK_EQUAL(turtle.path, "FtrunkFFtrunkGleaf"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>core: add unit test for lsystem parser<commit_after>#include "lsys/LSystemParser.hpp" #include "lsys/StringTurtle.hpp" #include <boost/test/unit_test.hpp> #include "config.hpp" #include <fstream> using namespace utymap::lsys; using namespace utymap::tests; namespace { const double ProbabilityPrecision = 0.01; const std::string SimpleGrammar = "generations: 3\n" "angle: 45\n" "scale: 0.1\n" "axiom: D F ab G G F K\n" "F(1) -> F G\n" "G(0.8) -> F\n" "G(0.2) -> G G G G ab\n" "ab -> G G F ab"; std::shared_ptr<MoveForwardRule> move() { return std::make_shared<MoveForwardRule>(); } std::shared_ptr<JumpForwardRule> jump() { return std::make_shared<JumpForwardRule>(); } std::shared_ptr<WordRule> A() { return std::make_shared<WordRule>("ab"); } } BOOST_AUTO_TEST_SUITE(Lsys_LSystemParser) BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasGenerations) { BOOST_CHECK_EQUAL(LSystemParser().parse(SimpleGrammar).generations, 3); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasAngle) { BOOST_CHECK_CLOSE(LSystemParser().parse(SimpleGrammar).angle, 45, ProbabilityPrecision); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasScale) { BOOST_CHECK_CLOSE(LSystemParser().parse(SimpleGrammar).scale, 0.1, ProbabilityPrecision); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasExpectedAmountOfAxiomRules) { BOOST_CHECK_EQUAL(LSystemParser().parse(SimpleGrammar).axiom.size(), 7); } BOOST_AUTO_TEST_CASE(GivenSimpleGrammar_WhenParse_ThenHasExpectedAmountOfProductions) { auto lsystem = LSystemParser().parse(SimpleGrammar); BOOST_CHECK_EQUAL(lsystem.productions.size(), 3); BOOST_CHECK_EQUAL(lsystem.productions[move()].size(), 1); BOOST_CHECK_CLOSE(lsystem.productions[move()].at(0).first, 1, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[move()].at(0).second.size(), 2); BOOST_CHECK_EQUAL(lsystem.productions[jump()].size(), 2); BOOST_CHECK_CLOSE(lsystem.productions[jump()].at(0).first, 0.8, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[jump()].at(0).second.size(), 1); BOOST_CHECK_CLOSE(lsystem.productions[jump()].at(1).first, 0.2, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[jump()].at(1).second.size(), 5); BOOST_CHECK_EQUAL(lsystem.productions[A()].size(), 1); BOOST_CHECK_CLOSE(lsystem.productions[A()].at(0).first, 1, ProbabilityPrecision); BOOST_CHECK_EQUAL(lsystem.productions[A()].at(0).second.size(), 4); } BOOST_AUTO_TEST_CASE(GivenGrammarWithComment_WhenParse_ThenSkipsCommentLine) { const std::string grammar = "generations: 3\n" "#angle:35\n" "angle: 45\n" "#angle:55\n" "scale: 1.2\n" "axiom: A\n" "A -> G G"; BOOST_CHECK_EQUAL(LSystemParser().parse(grammar).angle, 45); } BOOST_AUTO_TEST_CASE(GivenGrammarWithProbabilities_WhenParse_ThenStringTurtleBuildsProperPath) { StringTurtle turtle; const std::string grammar = "generations: 2\n" "angle: 45\n" "scale: 1.2\n" "axiom: A G\n" "G(0) -> G\n" "G(1) -> F F\n" "F -> G\n" "A -> G G"; turtle.run(LSystemParser().parse(grammar)); BOOST_CHECK_EQUAL(turtle.path, "FFFFGG"); } BOOST_AUTO_TEST_CASE(GivenGrammarWithWords_WhenParse_ThenStringTurtleBuildsProperPath) { StringTurtle turtle; const std::string grammar = "generations: 1\n" "angle: 45\n" "scale: 1.2\n" "axiom: root F G leaf\n" "root(0) -> G\n" "root(1) -> F trunk\n" "G -> F\n" "leaf -> trunk G leaf"; turtle.run(LSystemParser().parse(grammar)); BOOST_CHECK_EQUAL(turtle.path, "FtrunkFFtrunkGleaf"); } BOOST_AUTO_TEST_CASE(GivenGrammarInFile_WhenParse_ThenGrammarIsParsed) { StringTurtle turtle; std::ifstream file(TEST_MAPCSS_PATH "tree.lsys"); turtle.run(LSystemParser().parse(file)); BOOST_CHECK_EQUAL(turtle.path, "cylindersphere"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before><commit_msg>removed variable re-declaration.<commit_after><|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/CurvesPrimitive.h" #include "IECore/Exception.h" #include "IECore/SimpleTypedData.h" #include "IECoreArnold/ToArnoldCurvesConverter.h" using namespace IECoreArnold; using namespace IECore; using namespace std; IE_CORE_DEFINERUNTIMETYPED( ToArnoldCurvesConverter ); ToArnoldCurvesConverter::ConverterDescription<ToArnoldCurvesConverter> ToArnoldCurvesConverter::g_description; ToArnoldCurvesConverter::ToArnoldCurvesConverter( IECore::CurvesPrimitivePtr toConvert ) : ToArnoldShapeConverter( "Converts IECore::CurvesPrimitives to arnold curves nodes", IECore::CurvesPrimitive::staticTypeId() ) { srcParameter()->setValue( toConvert ); } ToArnoldCurvesConverter::~ToArnoldCurvesConverter() { } AtNode *ToArnoldCurvesConverter::doConversion( IECore::ConstObjectPtr from, IECore::ConstCompoundObjectPtr operands ) const { const CurvesPrimitive *curves = static_cast<const CurvesPrimitive *>( from.get() ); const V3fVectorData *p = curves->variableData<V3fVectorData>( "P", PrimitiveVariable::Vertex ); if( !p ) { throw Exception( "CurvesPrimitive does not have \"P\" primitive variable of interpolation type Vertex." ); } // make the result curves and add points AtNode *result = AiNode( "curves" ); const std::vector<int> verticesPerCurve = curves->verticesPerCurve()->readable(); AiNodeSetArray( result, "num_points", AiArrayConvert( verticesPerCurve.size(), 1, AI_TYPE_INT, (void *)&( verticesPerCurve[0] ) ) ); convertP( p, result, "points" ); // set basis if( curves->basis() == CubicBasisf::bezier() ) { AiNodeSetStr( result, "basis", "bezier" ); } else if( curves->basis() == CubicBasisf::bSpline() ) { AiNodeSetStr( result, "basis", "b-spline" ); } else if( curves->basis() == CubicBasisf::catmullRom() ) { AiNodeSetStr( result, "basis", "catmull-rom" ); } else { // just accept the default } // add radius convertRadius( curves, result ); // add arbitrary user parameters const char *ignore[] = { "P", "width", "radius", 0 }; convertPrimitiveVariables( curves, result, ignore ); return result; } <commit_msg>IECoreArnold now supports linear curves<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/CurvesPrimitive.h" #include "IECore/Exception.h" #include "IECore/SimpleTypedData.h" #include "IECoreArnold/ToArnoldCurvesConverter.h" using namespace IECoreArnold; using namespace IECore; using namespace std; IE_CORE_DEFINERUNTIMETYPED( ToArnoldCurvesConverter ); ToArnoldCurvesConverter::ConverterDescription<ToArnoldCurvesConverter> ToArnoldCurvesConverter::g_description; ToArnoldCurvesConverter::ToArnoldCurvesConverter( IECore::CurvesPrimitivePtr toConvert ) : ToArnoldShapeConverter( "Converts IECore::CurvesPrimitives to arnold curves nodes", IECore::CurvesPrimitive::staticTypeId() ) { srcParameter()->setValue( toConvert ); } ToArnoldCurvesConverter::~ToArnoldCurvesConverter() { } AtNode *ToArnoldCurvesConverter::doConversion( IECore::ConstObjectPtr from, IECore::ConstCompoundObjectPtr operands ) const { const CurvesPrimitive *curves = static_cast<const CurvesPrimitive *>( from.get() ); const V3fVectorData *p = curves->variableData<V3fVectorData>( "P", PrimitiveVariable::Vertex ); if( !p ) { throw Exception( "CurvesPrimitive does not have \"P\" primitive variable of interpolation type Vertex." ); } // make the result curves and add points AtNode *result = AiNode( "curves" ); const std::vector<int> verticesPerCurve = curves->verticesPerCurve()->readable(); AiNodeSetArray( result, "num_points", AiArrayConvert( verticesPerCurve.size(), 1, AI_TYPE_INT, (void *)&( verticesPerCurve[0] ) ) ); convertP( p, result, "points" ); // set basis if( curves->basis() == CubicBasisf::bezier() ) { AiNodeSetStr( result, "basis", "bezier" ); } else if( curves->basis() == CubicBasisf::bSpline() ) { AiNodeSetStr( result, "basis", "b-spline" ); } else if( curves->basis() == CubicBasisf::catmullRom() ) { AiNodeSetStr( result, "basis", "catmull-rom" ); } else if( curves->basis() == CubicBasisf::linear() ) { AiNodeSetStr( result, "basis", "linear" ); } else { // just accept the default } // add radius convertRadius( curves, result ); // add arbitrary user parameters const char *ignore[] = { "P", "width", "radius", 0 }; convertPrimitiveVariables( curves, result, ignore ); return result; } <|endoftext|>
<commit_before>// Please read Bounce2.h for information about the liscence and authors #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "Bounce2.h" #define DEBOUNCED_STATE 0 #define UNSTABLE_STATE 1 #define STATE_CHANGED 3 Bounce::Bounce() : previous_millis(0) , interval_millis(10) , state(0) , pin(0) {} void Bounce::attach(int pin) { this->pin = pin; state = 0; if (digitalRead(pin)) { state = _BV(DEBOUNCED_STATE) | _BV(UNSTABLE_STATE); } #ifdef BOUNCE_LOCK_OUT previous_millis = 0; #else previous_millis = millis(); #endif } void Bounce::attach(int pin, int mode){ pinMode(pin, mode); this->attach(pin); } void Bounce::interval(uint16_t interval_millis) { this->interval_millis = interval_millis; } bool Bounce::update() { #ifdef BOUNCE_LOCK_OUT state &= ~_BV(STATE_CHANGED); // Ignore everything if we are locked out if (millis() - previous_millis >= interval_millis) { bool currentState = digitalRead(pin); if ((bool)(state & _BV(DEBOUNCED_STATE)) != currentState) { previous_millis = millis(); state ^= _BV(DEBOUNCED_STATE); state |= _BV(STATE_CHANGED); } } return state & _BV(STATE_CHANGED); #elif defined BOUNCE_WITH_PROMPT_DETECTION // Read the state of the switch port into a temporary variable. bool readState = digitalRead(pin); // Clear Changed State Flag - will be reset if we confirm a button state change. state &= ~_BV(STATE_CHANGED); if ( readState != (bool)(state & _BV(DEBOUNCED_STATE))) { // We have seen a change from the current button state. if ( millis() - previous_millis >= interval_millis ) { // We have passed the time threshold, so a new change of state is allowed. // set the STATE_CHANGED flag and the new DEBOUNCED_STATE. // This will be prompt as long as there has been greater than interval_misllis ms since last change of input. // Otherwise debounced state will not change again until bouncing is stable for the timeout period. state ^= _BV(DEBOUNCED_STATE); state |= _BV(STATE_CHANGED); } } // If the readState is different from previous readState, reset the debounce timer - as input is still unstable // and we want to prevent new button state changes until the previous one has remained stable for the timeout. if ( readState != (bool)(state & _BV(UNSTABLE_STATE)) ) { // Update Unstable Bit to macth readState state ^= _BV(UNSTABLE_STATE); previous_millis = millis(); } // return just the sate changed bit return state & _BV(STATE_CHANGED); #else // Read the state of the switch in a temporary variable. bool currentState = digitalRead(pin); state &= ~_BV(STATE_CHANGED); // If the reading is different from last reading, reset the debounce counter if ( currentState != (bool)(state & _BV(UNSTABLE_STATE)) ) { previous_millis = millis(); state ^= _BV(UNSTABLE_STATE); } else if ( millis() - previous_millis >= interval_millis ) { // We have passed the threshold time, so the input is now stable // If it is different from last state, set the STATE_CHANGED flag if ((bool)(state & _BV(DEBOUNCED_STATE)) != currentState) { previous_millis = millis(); state ^= _BV(DEBOUNCED_STATE); state |= _BV(STATE_CHANGED); } } return state & _BV(STATE_CHANGED); #endif } bool Bounce::read() { return state & _BV(DEBOUNCED_STATE); } bool Bounce::rose() { return ( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED)); } bool Bounce::fell() { return !( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED)); } <commit_msg>Blue Pill port<commit_after>// Please read Bounce2.h for information about the liscence and authors #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "Bounce2.h" #define DEBOUNCED_STATE 0 #define UNSTABLE_STATE 1 #define STATE_CHANGED 3 Bounce::Bounce() : previous_millis(0) , interval_millis(10) , state(0) , pin(0) {} void Bounce::attach(int pin) { this->pin = pin; state = 0; if (digitalRead(pin)) { state = _BV(DEBOUNCED_STATE) | _BV(UNSTABLE_STATE); } #ifdef BOUNCE_LOCK_OUT previous_millis = 0; #else previous_millis = millis(); #endif } void Bounce::attach(int pin, int mode){ #if defined(ARDUINO_STM_NUCLEO_F103RB) || defined(ARDUINO_GENERIC_STM32F103C) pinMode(pin, (WiringPinMode)mode); #else pinMode(pin, mode); #endif this->attach(pin); } void Bounce::interval(uint16_t interval_millis) { this->interval_millis = interval_millis; } bool Bounce::update() { #ifdef BOUNCE_LOCK_OUT state &= ~_BV(STATE_CHANGED); // Ignore everything if we are locked out if (millis() - previous_millis >= interval_millis) { bool currentState = digitalRead(pin); if ((bool)(state & _BV(DEBOUNCED_STATE)) != currentState) { previous_millis = millis(); state ^= _BV(DEBOUNCED_STATE); state |= _BV(STATE_CHANGED); } } return state & _BV(STATE_CHANGED); #elif defined BOUNCE_WITH_PROMPT_DETECTION // Read the state of the switch port into a temporary variable. bool readState = digitalRead(pin); // Clear Changed State Flag - will be reset if we confirm a button state change. state &= ~_BV(STATE_CHANGED); if ( readState != (bool)(state & _BV(DEBOUNCED_STATE))) { // We have seen a change from the current button state. if ( millis() - previous_millis >= interval_millis ) { // We have passed the time threshold, so a new change of state is allowed. // set the STATE_CHANGED flag and the new DEBOUNCED_STATE. // This will be prompt as long as there has been greater than interval_misllis ms since last change of input. // Otherwise debounced state will not change again until bouncing is stable for the timeout period. state ^= _BV(DEBOUNCED_STATE); state |= _BV(STATE_CHANGED); } } // If the readState is different from previous readState, reset the debounce timer - as input is still unstable // and we want to prevent new button state changes until the previous one has remained stable for the timeout. if ( readState != (bool)(state & _BV(UNSTABLE_STATE)) ) { // Update Unstable Bit to macth readState state ^= _BV(UNSTABLE_STATE); previous_millis = millis(); } // return just the sate changed bit return state & _BV(STATE_CHANGED); #else // Read the state of the switch in a temporary variable. bool currentState = digitalRead(pin); state &= ~_BV(STATE_CHANGED); // If the reading is different from last reading, reset the debounce counter if ( currentState != (bool)(state & _BV(UNSTABLE_STATE)) ) { previous_millis = millis(); state ^= _BV(UNSTABLE_STATE); } else if ( millis() - previous_millis >= interval_millis ) { // We have passed the threshold time, so the input is now stable // If it is different from last state, set the STATE_CHANGED flag if ((bool)(state & _BV(DEBOUNCED_STATE)) != currentState) { previous_millis = millis(); state ^= _BV(DEBOUNCED_STATE); state |= _BV(STATE_CHANGED); } } return state & _BV(STATE_CHANGED); #endif } bool Bounce::read() { return state & _BV(DEBOUNCED_STATE); } bool Bounce::rose() { return ( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED)); } bool Bounce::fell() { return !( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED)); } <|endoftext|>
<commit_before>/* * D3D11VertexBufferArray.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "D3D11VertexBufferArray.h" #include "D3D11VertexBuffer.h" #include "../../CheckedCast.h" namespace LLGL { D3D11VertexBufferArray::D3D11VertexBufferArray(unsigned int numBuffers, Buffer* const * bufferArray) : D3D11BufferArray( BufferType::Vertex, numBuffers, bufferArray ) { /* Store the pointer of each ID3D11Buffer inside the array */ for (strides_.reserve(numBuffers), offsets_.reserve(numBuffers); numBuffers > 0; --numBuffers) { auto vertexBufferD3D = LLGL_CAST(D3D11VertexBuffer*, (*bufferArray)); strides_.push_back(vertexBufferD3D->GetStride()); offsets_.push_back(0);//vertexBufferD3D->GetOffset()); ++bufferArray; } } } // /namespace LLGL // ================================================================================ <commit_msg>Simplified D3D11VertexBufferArray constructor.<commit_after>/* * D3D11VertexBufferArray.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "D3D11VertexBufferArray.h" #include "D3D11VertexBuffer.h" #include "../../CheckedCast.h" #include "../../../Core/Helper.h" namespace LLGL { D3D11VertexBufferArray::D3D11VertexBufferArray(unsigned int numBuffers, Buffer* const * bufferArray) : D3D11BufferArray( BufferType::Vertex, numBuffers, bufferArray ) { /* Store the pointer of each ID3D11Buffer inside the array */ strides_.reserve(numBuffers); offsets_.reserve(numBuffers); while (auto next = NextArrayResource<D3D11VertexBuffer>(numBuffers, bufferArray)) { strides_.push_back(next->GetStride()); offsets_.push_back(0);//next->GetOffset()); } } } // /namespace LLGL // ================================================================================ <|endoftext|>
<commit_before>#include "ExampleGame/Components/GameScripts/Units/Assassin.h" #include "ExampleGame/Components/Grid/GameGrid.h" #include "ExampleGame/Components/Grid/GridCell.h" #include "ExampleGame/Components/Grid/GridManager.h" #include "ExampleGame/Components/Grid/GridNavigator.h" #include "ExampleGame/GameConstants/GameConstants.h" #include "ExampleGame/GameSingletons/GameSingletons.h" #include "ExampleGame/Messages/Declarations.h" #include "Vajra/Common/Messages/CustomMessageDatas/MessageData1S1I1F.h" #include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Input/Input.h" #include "Vajra/Engine/MessageHub/MessageHub.h" #include "Vajra/Engine/SceneGraph/SceneGraph3D.h" #include "Vajra/Engine/Tween/Tween.h" #include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h" // Tween callbacks void assassinTweenCallback(ObjectIdType gameObjectId , std::string /* tweenClipName */) { GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId); ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid"); if(go != nullptr) { Assassin* pUnit = go->GetComponent<Assassin>(); ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit"); if(pUnit != nullptr) { pUnit->specialUpdate(); // make sure we hit everything we got in the last frame pUnit->onSpecialEnd(); } } } void assassinNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float /*currentNumber*/, std::string /*tweenClipName*/, MessageData1S1I1F* userParams) { GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i); ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid"); if(go != nullptr) { Assassin* pUnit = go->GetComponent<Assassin>(); ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit"); if(pUnit != nullptr) { pUnit->specialUpdate(); } } } Assassin::Assassin() : PlayerUnit() { this->init(); } Assassin::Assassin(Object* object_) : PlayerUnit(object_) { this->init(); } Assassin::~Assassin() { this->destroy(); } void Assassin::init() { this->unitType = UnitType::UNIT_TYPE_ASSASSIN; { // create the arrow tail this->arrowTail = new GameObject(ENGINE->GetSceneGraph3D()); SpriteRenderer* spriteRenderer = this->arrowTail->AddComponent<SpriteRenderer>(); std::vector<std::string> pathsToTextures; pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Assassin_ArrowStem_magenta_02.png"); spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center); this->arrowTail->GetTransform()->Rotate(90.0f inRadians, XAXIS); this->arrowTail->SetVisible(false); } { // create the arrow head this->arrowHead = new GameObject(ENGINE->GetSceneGraph3D()); SpriteRenderer* spriteRenderer = this->arrowHead->AddComponent<SpriteRenderer>(); std::vector<std::string> pathsToTextures; pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Assassin_Arrow_magenta_03.png"); spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center); this->arrowHead->GetTransform()->Rotate(90.0f inRadians, XAXIS); this->arrowHead->SetVisible(false); } this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_CELL_CHANGED, this->GetTypeId(), false); } void Assassin::destroy() { } void Assassin::HandleMessage(MessageChunk messageChunk) { PlayerUnit::HandleMessage(messageChunk); switch (messageChunk->GetMessageType()) { case MESSAGE_TYPE_GRID_CELL_CHANGED: this->onGridCellChanged(messageChunk->GetSenderId(), messageChunk->messageData.iv1.x, messageChunk->messageData.iv1.z); break; default: break; } } bool Assassin::isSpecialTouch(int touchId) { if(this->getTouchNearUnit()) { Touch touch = ENGINE->GetInput()->GetTouch(touchId); if(touch.timeDown <= GetFloatGameConstant(GAME_CONSTANT_swipe_duration_in_seconds) && glm::distance(touch.pos, this->touchStartPos) > GetFloatGameConstant(GAME_CONSTANT_assassin_swipe_dist_in_pixels)) { this->swipeDirectionScreen = this->touchStartPos - touch.pos; this->targetedCell = nullptr; this->gridNavRef->HaltMovement(); this->aimSpecial(touchId); return true; } } return false; } void Assassin::onSpecialTouch(int touchId) { Touch touch = ENGINE->GetInput()->GetTouch(touchId); if(touch.phase == TouchPhase::Ended) { this->trySpecial(touchId); } else if(touch.phase == TouchPhase::Cancelled) { this->cancelSpecial(); } else if(touch.phase == TouchPhase::Moved) { this->aimSpecial(touchId); } } void Assassin::trySpecial(int /*touchId*/) { if(this->targetedCell != nullptr && this->targetedCell != this->gridNavRef->GetCurrentCell()) { this->startSpecial(); } else { this->cancelSpecial(); } } void Assassin::startSpecial() { PlayerUnit::startSpecial(); //this->gridNavRef->SetMovementSpeed(GetFloatGameConstant(GAME_CONSTANT_assassin_attack_speed)); //this->gridNavRef->SetDestination(this->targetedCell, true); float tweenTime = glm::distance(this->gameObjectRef->GetTransform()->GetPositionWorld(), this->targetLoc) / GetFloatGameConstant(GAME_CONSTANT_assassin_attack_speed); ASSERT(tweenTime > 0, "tweenTime is greater than zero"); this->lastHitCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld()); this->specialStartPos = this->gameObjectRef->GetTransform()->GetPositionWorld(); ENGINE->GetTween()->TweenPosition(this->gameObjectRef->GetId(), this->gameObjectRef->GetTransform()->GetPositionWorld(), this->targetLoc, tweenTime, false, TWEEN_TRANSLATION_CURVE_TYPE_LINEAR, false, assassinTweenCallback); MessageData1S1I1F* userParams = new MessageData1S1I1F(); userParams->i = this->GetObject()->GetId(); ENGINE->GetTween()->TweenToNumber(0.0f, 1.0f, tweenTime, true, false, true, "dash", NUMBER_TWEEN_AFFILIATION_SCENEGRAPH_3D, userParams, assassinNumberTweenCallback); this->startTouchIndicatorPulse(); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); } void Assassin::onSpecialEnd() { PlayerUnit::onSpecialEnd(); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); this->gridNavRef->SetCurrentCell(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); //this->gridNavRef->SetMovementSpeed(MOVE_SPEED); //this->gridNavRef->SetGridPosition(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); //(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); //this->gameObjectRef->GetTransform()->SetPosition(this->targetLoc); } void Assassin::cancelSpecial() { PlayerUnit::cancelSpecial(); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); ENGINE->GetTween()->CancelNumberTween("dash"); ENGINE->GetTween()->CancelPostitionTween(this->gameObjectRef->GetId()); this->specialUpdate(); this->gridNavRef->SetCurrentCell(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); } void Assassin::onGridCellChanged(ObjectIdType id, int gridX, int gridZ) { // If this object is the one that sent the message, broadcast an attack message as well if (id == this->GetObject()->GetId()) { GridCell* cell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(gridX, gridZ); if (cell != nullptr) { if (this->GetUnitActionState() == UnitActionState::UNIT_ACTION_STATE_DOING_SPECIAL) { // Send an attack message MessageChunk attackMessage = ENGINE->GetMessageHub()->GetOneFreeMessage(); attackMessage->SetMessageType(MESSAGE_TYPE_UNIT_SPECIAL_HIT); attackMessage->messageData.iv1.x = cell->x; attackMessage->messageData.iv1.y = cell->y; attackMessage->messageData.iv1.z = cell->z; attackMessage->messageData.fv1 = this->specialStartPos; ENGINE->GetMessageHub()->SendMulticastMessage(attackMessage, this->GetObject()->GetId()); } } } } void Assassin::aimSpecial(int touchId){ this->targetLoc = SINGLETONS->GetGridManager()->TouchPositionToGridPositionAtElevation(ENGINE->GetInput()->GetTouch(touchId).pos, this->gridNavRef->GetCurrentCell()->y); glm::vec3 sinPos = this->gameObjectRef->GetTransform()->GetPositionWorld(); std::list<GridCell*> touchedCells; GridCell* touchedCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->targetLoc); ASSERT(touchedCell != nullptr, "the target cell is not null"); SINGLETONS->GetGridManager()->GetGrid()->TouchedCells(sinPos, this->targetLoc, touchedCells); int elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(this->gridNavRef->GetCurrentCell()->center.y); int cellIndex = 0; for( GridCell* c : touchedCells) { if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, elevation)) { this->targetedCell = c; } else { break; } cellIndex++; } // if there is a legal target if(this->targetedCell != nullptr && touchedCell != nullptr && this->targetedCell != this->gridNavRef->GetCurrentCell()) { glm::vec3 attackDir = glm::normalize(this->targetLoc - sinPos); if(touchedCell != this->targetedCell) { // if the touched cell is obstructed move back along the path until the target is reachable float dis = glm::distance(sinPos, this->targetedCell->center); while(touchedCell != this->targetedCell && glm::distance(sinPos, this->targetLoc) > dis) { this->targetLoc -= attackDir * .1f; touchedCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->targetLoc); } } float dist = glm::distance(sinPos, this->targetLoc); if(dist > GetFloatGameConstant(GAME_CONSTANT_dash_distance_in_units)) { dist = GetFloatGameConstant(GAME_CONSTANT_dash_distance_in_units); this->targetLoc = sinPos + (attackDir * dist); touchedCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->targetLoc); } dist -= 1.5f; // shorten dist so arrow heads are in the right spot if(dist < 0.5f) { this->arrowTail->SetVisible(false); } // make the sin look at the target this->gridNavRef->SetLookTarget(this->targetLoc); // the yOffset the indicators should have float yOffset = touchedCell->y * 0.05 + .01f; // touch indicator this->SetTouchIndicatorVisible(true); this->SetTouchIndicatorLocation(this->targetLoc + yOffset); // Arrow Tail this->arrowTail->SetVisible(true); this->GridPlaneLookAt(this->arrowTail, this->targetLoc); this->arrowTail->GetTransform()->SetScale(1.0f, dist, 1.0f); this->arrowTail->GetComponent<Transform>()->SetPosition(sinPos + glm::vec3(0.0f, yOffset, 0.0f)); this->arrowTail->GetComponent<Transform>()->Translate(dist * .5f, this->arrowTail->GetComponent<Transform>()->GetUp()); // Arrow Head this->arrowHead->SetVisible(true); this->GridPlaneLookAt(this->arrowHead, this->targetLoc); this->arrowHead->GetTransform()->SetPosition(sinPos + glm::vec3(0.0f, yOffset, 0.0f)); this->arrowHead->GetTransform()->Translate(dist + .5f, this->arrowHead->GetComponent<Transform>()->GetUp()); } else { this->SetTouchIndicatorVisible(false); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); } } void Assassin::specialUpdate() { GridCell* currentCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld()); if(currentCell != this->lastHitCell) { std::list<GridCell*> touchedCells; SINGLETONS->GetGridManager()->CheckZoneCollisions(this->GetObject()->GetId(), this->lastHitCell, currentCell); for( GridCell* c : touchedCells) { if(this->lastHitCell != c) { // Attack the cell MessageChunk attackMessage = ENGINE->GetMessageHub()->GetOneFreeMessage(); attackMessage->SetMessageType(MESSAGE_TYPE_UNIT_SPECIAL_HIT); attackMessage->messageData.iv1.x = c->x; attackMessage->messageData.iv1.y = c->y; attackMessage->messageData.iv1.z = c->z; attackMessage->messageData.fv1 = this->specialStartPos; ENGINE->GetMessageHub()->SendMulticastMessage(attackMessage, this->GetObject()->GetId()); } } this->lastHitCell = currentCell; } } <commit_msg>Fixed sin bug<commit_after>#include "ExampleGame/Components/GameScripts/Units/Assassin.h" #include "ExampleGame/Components/Grid/GameGrid.h" #include "ExampleGame/Components/Grid/GridCell.h" #include "ExampleGame/Components/Grid/GridManager.h" #include "ExampleGame/Components/Grid/GridNavigator.h" #include "ExampleGame/GameConstants/GameConstants.h" #include "ExampleGame/GameSingletons/GameSingletons.h" #include "ExampleGame/Messages/Declarations.h" #include "Vajra/Common/Messages/CustomMessageDatas/MessageData1S1I1F.h" #include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Input/Input.h" #include "Vajra/Engine/MessageHub/MessageHub.h" #include "Vajra/Engine/SceneGraph/SceneGraph3D.h" #include "Vajra/Engine/Tween/Tween.h" #include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h" // Tween callbacks void assassinTweenCallback(ObjectIdType gameObjectId , std::string /* tweenClipName */) { GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId); ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid"); if(go != nullptr) { Assassin* pUnit = go->GetComponent<Assassin>(); ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit"); if(pUnit != nullptr) { pUnit->specialUpdate(); // make sure we hit everything we got in the last frame pUnit->onSpecialEnd(); } } } void assassinNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float /*currentNumber*/, std::string /*tweenClipName*/, MessageData1S1I1F* userParams) { GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i); ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid"); if(go != nullptr) { Assassin* pUnit = go->GetComponent<Assassin>(); ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit"); if(pUnit != nullptr) { pUnit->specialUpdate(); } } } Assassin::Assassin() : PlayerUnit() { this->init(); } Assassin::Assassin(Object* object_) : PlayerUnit(object_) { this->init(); } Assassin::~Assassin() { this->destroy(); } void Assassin::init() { this->unitType = UnitType::UNIT_TYPE_ASSASSIN; { // create the arrow tail this->arrowTail = new GameObject(ENGINE->GetSceneGraph3D()); SpriteRenderer* spriteRenderer = this->arrowTail->AddComponent<SpriteRenderer>(); std::vector<std::string> pathsToTextures; pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Assassin_ArrowStem_magenta_02.png"); spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center); this->arrowTail->GetTransform()->Rotate(90.0f inRadians, XAXIS); this->arrowTail->SetVisible(false); } { // create the arrow head this->arrowHead = new GameObject(ENGINE->GetSceneGraph3D()); SpriteRenderer* spriteRenderer = this->arrowHead->AddComponent<SpriteRenderer>(); std::vector<std::string> pathsToTextures; pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Assassin_Arrow_magenta_03.png"); spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center); this->arrowHead->GetTransform()->Rotate(90.0f inRadians, XAXIS); this->arrowHead->SetVisible(false); } this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_CELL_CHANGED, this->GetTypeId(), false); } void Assassin::destroy() { } void Assassin::HandleMessage(MessageChunk messageChunk) { PlayerUnit::HandleMessage(messageChunk); switch (messageChunk->GetMessageType()) { case MESSAGE_TYPE_GRID_CELL_CHANGED: this->onGridCellChanged(messageChunk->GetSenderId(), messageChunk->messageData.iv1.x, messageChunk->messageData.iv1.z); break; default: break; } } bool Assassin::isSpecialTouch(int touchId) { if(this->getTouchNearUnit()) { Touch touch = ENGINE->GetInput()->GetTouch(touchId); if(touch.timeDown <= GetFloatGameConstant(GAME_CONSTANT_swipe_duration_in_seconds) && glm::distance(touch.pos, this->touchStartPos) > GetFloatGameConstant(GAME_CONSTANT_assassin_swipe_dist_in_pixels)) { this->swipeDirectionScreen = this->touchStartPos - touch.pos; this->targetedCell = nullptr; this->gridNavRef->HaltMovement(); this->aimSpecial(touchId); return true; } } return false; } void Assassin::onSpecialTouch(int touchId) { Touch touch = ENGINE->GetInput()->GetTouch(touchId); if(touch.phase == TouchPhase::Ended) { this->trySpecial(touchId); } else if(touch.phase == TouchPhase::Cancelled) { this->cancelSpecial(); } else if(touch.phase == TouchPhase::Moved) { this->aimSpecial(touchId); } } void Assassin::trySpecial(int /*touchId*/) { if(this->targetedCell != nullptr && this->targetedCell != this->gridNavRef->GetCurrentCell()) { this->startSpecial(); } else { this->cancelSpecial(); } } void Assassin::startSpecial() { PlayerUnit::startSpecial(); //this->gridNavRef->SetMovementSpeed(GetFloatGameConstant(GAME_CONSTANT_assassin_attack_speed)); //this->gridNavRef->SetDestination(this->targetedCell, true); float tweenTime = glm::distance(this->gameObjectRef->GetTransform()->GetPositionWorld(), this->targetLoc) / GetFloatGameConstant(GAME_CONSTANT_assassin_attack_speed); ASSERT(tweenTime > 0, "tweenTime is greater than zero"); this->lastHitCell = this->gridNavRef->GetCurrentCell(); this->specialStartPos = this->gameObjectRef->GetTransform()->GetPositionWorld(); ENGINE->GetTween()->TweenPosition(this->gameObjectRef->GetId(), this->gameObjectRef->GetTransform()->GetPositionWorld(), this->targetLoc, tweenTime, false, TWEEN_TRANSLATION_CURVE_TYPE_LINEAR, false, assassinTweenCallback); MessageData1S1I1F* userParams = new MessageData1S1I1F(); userParams->i = this->GetObject()->GetId(); ENGINE->GetTween()->TweenToNumber(0.0f, 1.0f, tweenTime, true, false, true, "dash", NUMBER_TWEEN_AFFILIATION_SCENEGRAPH_3D, userParams, assassinNumberTweenCallback); this->startTouchIndicatorPulse(); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); } void Assassin::onSpecialEnd() { PlayerUnit::onSpecialEnd(); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); this->gridNavRef->SetCurrentCell(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); //this->gridNavRef->SetMovementSpeed(MOVE_SPEED); //this->gridNavRef->SetGridPosition(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); //(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); //this->gameObjectRef->GetTransform()->SetPosition(this->targetLoc); } void Assassin::cancelSpecial() { PlayerUnit::cancelSpecial(); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); ENGINE->GetTween()->CancelNumberTween("dash"); ENGINE->GetTween()->CancelPostitionTween(this->gameObjectRef->GetId()); this->specialUpdate(); this->gridNavRef->SetCurrentCell(SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld())); } void Assassin::onGridCellChanged(ObjectIdType id, int gridX, int gridZ) { // If this object is the one that sent the message, broadcast an attack message as well if (id == this->GetObject()->GetId()) { GridCell* cell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(gridX, gridZ); if (cell != nullptr) { if (this->GetUnitActionState() == UnitActionState::UNIT_ACTION_STATE_DOING_SPECIAL) { // Send an attack message MessageChunk attackMessage = ENGINE->GetMessageHub()->GetOneFreeMessage(); attackMessage->SetMessageType(MESSAGE_TYPE_UNIT_SPECIAL_HIT); attackMessage->messageData.iv1.x = cell->x; attackMessage->messageData.iv1.y = cell->y; attackMessage->messageData.iv1.z = cell->z; attackMessage->messageData.fv1 = this->specialStartPos; ENGINE->GetMessageHub()->SendMulticastMessage(attackMessage, this->GetObject()->GetId()); } } } } void Assassin::aimSpecial(int touchId){ this->targetLoc = SINGLETONS->GetGridManager()->TouchPositionToGridPositionAtElevation(ENGINE->GetInput()->GetTouch(touchId).pos, this->gridNavRef->GetCurrentCell()->y); glm::vec3 sinPos = this->gameObjectRef->GetTransform()->GetPositionWorld(); std::list<GridCell*> touchedCells; GridCell* touchedCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->targetLoc); ASSERT(touchedCell != nullptr, "the target cell is not null"); SINGLETONS->GetGridManager()->GetGrid()->TouchedCells(sinPos, this->targetLoc, touchedCells); int elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(this->gridNavRef->GetCurrentCell()->center.y); int cellIndex = 0; for( GridCell* c : touchedCells) { if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, elevation)) { this->targetedCell = c; } else { break; } cellIndex++; } // if there is a legal target if(this->targetedCell != nullptr && touchedCell != nullptr && this->targetedCell != this->gridNavRef->GetCurrentCell()) { glm::vec3 attackDir = glm::normalize(this->targetLoc - sinPos); if(touchedCell != this->targetedCell) { // if the touched cell is obstructed move back along the path until the target is reachable float dis = glm::distance(sinPos, this->targetedCell->center); while(touchedCell != this->targetedCell && glm::distance(sinPos, this->targetLoc) > dis) { this->targetLoc -= attackDir * .1f; touchedCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->targetLoc); } } float dist = glm::distance(sinPos, this->targetLoc); if(dist > GetFloatGameConstant(GAME_CONSTANT_dash_distance_in_units)) { dist = GetFloatGameConstant(GAME_CONSTANT_dash_distance_in_units); this->targetLoc = sinPos + (attackDir * dist); touchedCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->targetLoc); } dist -= 1.5f; // shorten dist so arrow heads are in the right spot if(dist < 0.5f) { this->arrowTail->SetVisible(false); } // make the sin look at the target this->gridNavRef->SetLookTarget(this->targetLoc); // the yOffset the indicators should have float yOffset = touchedCell->y * 0.05 + .01f; // touch indicator this->SetTouchIndicatorVisible(true); this->SetTouchIndicatorLocation(this->targetLoc + yOffset); // Arrow Tail this->arrowTail->SetVisible(true); this->GridPlaneLookAt(this->arrowTail, this->targetLoc); this->arrowTail->GetTransform()->SetScale(1.0f, dist, 1.0f); this->arrowTail->GetComponent<Transform>()->SetPosition(sinPos + glm::vec3(0.0f, yOffset, 0.0f)); this->arrowTail->GetComponent<Transform>()->Translate(dist * .5f, this->arrowTail->GetComponent<Transform>()->GetUp()); // Arrow Head this->arrowHead->SetVisible(true); this->GridPlaneLookAt(this->arrowHead, this->targetLoc); this->arrowHead->GetTransform()->SetPosition(sinPos + glm::vec3(0.0f, yOffset, 0.0f)); this->arrowHead->GetTransform()->Translate(dist + .5f, this->arrowHead->GetComponent<Transform>()->GetUp()); } else { this->SetTouchIndicatorVisible(false); this->arrowHead->SetVisible(false); this->arrowTail->SetVisible(false); } } void Assassin::specialUpdate() { GridCell* currentCell = SINGLETONS->GetGridManager()->GetGrid()->GetCell(this->gameObjectRef->GetTransform()->GetPositionWorld()); if(currentCell != this->lastHitCell) { std::list<GridCell*> touchedCells; SINGLETONS->GetGridManager()->GetGrid()->TouchedCells(this->lastHitCell, currentCell, touchedCells); SINGLETONS->GetGridManager()->CheckZoneCollisions(this->GetObject()->GetId(), this->lastHitCell, currentCell); for( GridCell* c : touchedCells) { if(this->lastHitCell != c) { // Attack the cell MessageChunk attackMessage = ENGINE->GetMessageHub()->GetOneFreeMessage(); attackMessage->SetMessageType(MESSAGE_TYPE_UNIT_SPECIAL_HIT); attackMessage->messageData.iv1.x = c->x; attackMessage->messageData.iv1.y = c->y; attackMessage->messageData.iv1.z = c->z; attackMessage->messageData.fv1 = this->specialStartPos; ENGINE->GetMessageHub()->SendMulticastMessage(attackMessage, this->GetObject()->GetId()); } } this->lastHitCell = currentCell; } } <|endoftext|>
<commit_before>/** * Copyright 2016, Quickstep Research Group, Computer Sciences Department, * University of Wisconsin—Madison. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_ #define QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_ #include <algorithm> #include <memory> #include <stack> #include <unordered_set> #include <vector> #include "transaction/Transaction.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" namespace quickstep { namespace transaction { /** \addtogroup Transaction * @{ */ /** * @brief Class for representing a directed graph. Vertices are transaction * ids, edges are wait-for relations. **/ class DirectedGraph { public: typedef std::uint64_t node_id; /** * @brief Default constructor **/ DirectedGraph() {} /** * @brief Adds a new node to the graph with the given transaction id. * It does not check whether the transaction id is valid or not. * @warning Pointer ownership will pass to the graph, therefore it * should not be deleted. * * @param data Pointer to the transaction id that will be contained * in the node. * @return Id of the newly created node. **/ inline node_id addNodeUnchecked(transaction_id *data) { nodes_.emplace_back(data); return nodes_.size() - 1; } /** * @brief Adds a new node to the graph with the given transaction id. * It checks whether the transaction id is valid or not. * @warning Pointer ownership will pass to the graph, therefore it * should not be deleted. * * @param data Pointer to the transaction id that will be contained * in the node. * @return Id of the newly created node. **/ inline node_id addNodeCheckExists(transaction_id *data) { for (std::vector<DirectedGraphNode>::const_iterator it = nodes_.cbegin(); it != nodes_.cend(); ++it) { CHECK(*data != it->getData()); } nodes_.emplace_back(data); return nodes_.size() - 1; } /** * @brief Adds an edge between nodes. It does not check whether the * parameters are valid node ids. * @warning Does not check arguments are legit. It may cause * out of range errors. * * @param fromNode The node that edge is orginated. * @param toNode The node that edge is ended. **/ inline void addEdgeUnchecked(node_id from_node, node_id to_node) { nodes_[from_node].addOutgoingEdge(to_node); } /** * @brief Adds an edge between nodes. It checks whether the * parameters are valid node ids. * * @param fromNode The node that edge is orginated. * @param toNode The node that edge is ended. **/ inline void addEdgeCheckExists(node_id from_node, node_id to_node) { CHECK(from_node < getNumNodes() && to_node < getNumNodes()); nodes_[from_node].addOutgoingEdge(to_node); } /** * @brief Check whether there is a directed edge. * @warning When parameters are not valid ids, it may cause * out of range errors. * * @param fromNode Id of the node that edge is originated from. * @param toNode Id of the node that edge is ended. * @return True if there is an edge, false otherwise. **/ inline bool hasEdge(node_id from_node, node_id to_node) const { DCHECK(from_node < getNumNodes() && to_node < getNumNodes()); return nodes_[from_node].hasOutgoingEdge(to_node); } /** * @brief Get data (transaction id) contained in the node. * @warning Does not check index validity. * * @param node Id of the node that the data is got from. * @return Id of the transaction that this node contains. **/ inline transaction_id getDataFromNode(node_id node) const { return nodes_[node].getData(); } /** * @brief Calculate how many nodes the graph has. * * @return The number of nodes the graph has. **/ inline std::size_t getNumNodes() const { return nodes_.size(); } /** * @brief Gives the node ids that this node has edges to. * * @param id Id of the corresponding node. * @return Vector of node ids that id has edges to. **/ inline std::vector<node_id> getAdjacentNodes(node_id id) const { return nodes_[id].getOutgoingEdges(); } private: // Class for representing a graph node. class DirectedGraphNode { public: explicit DirectedGraphNode(transaction_id *data) : data_(data) {} inline void addOutgoingEdge(node_id to_node) { outgoing_edges_.insert(to_node); } inline bool hasOutgoingEdge(node_id to_node) const { return outgoing_edges_.count(to_node) == 1; } inline std::vector<node_id> getOutgoingEdges() const { std::vector<node_id> result; std::copy(outgoing_edges_.begin(), outgoing_edges_.end(), std::back_inserter(result)); return result; } inline transaction_id getData() const { return *(data_.get()); } private: // Owner pointer to transaction id. std::unique_ptr<transaction_id> data_; // Endpoint nodes of outgoing edges originated from this node. std::unordered_set<node_id> outgoing_edges_; }; // The list of nodes that are created. NodeId is the index of that // node in this buffer. std::vector<DirectedGraphNode> nodes_; DISALLOW_COPY_AND_ASSIGN(DirectedGraph); }; /** @} */ } // namespace transaction } // namespace quickstep #endif // QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_ <commit_msg>Added a todo for considering alternatives.<commit_after>/** * Copyright 2016, Quickstep Research Group, Computer Sciences Department, * University of Wisconsin—Madison. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_ #define QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_ #include <algorithm> #include <memory> #include <stack> #include <unordered_set> #include <vector> #include "transaction/Transaction.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" namespace quickstep { namespace transaction { /** \addtogroup Transaction * @{ */ /** * @brief Class for representing a directed graph. Vertices are transaction * ids, edges are wait-for relations. **/ class DirectedGraph { public: typedef std::uint64_t node_id; /** * @brief Default constructor **/ DirectedGraph() {} /** * @brief Adds a new node to the graph with the given transaction id. * It does not check whether the transaction id is valid or not. * @warning Pointer ownership will pass to the graph, therefore it * should not be deleted. * * @param data Pointer to the transaction id that will be contained * in the node. * @return Id of the newly created node. **/ inline node_id addNodeUnchecked(transaction_id *data) { nodes_.emplace_back(data); return nodes_.size() - 1; } /** * @brief Adds a new node to the graph with the given transaction id. * It checks whether the transaction id is valid or not. * @warning Pointer ownership will pass to the graph, therefore it * should not be deleted. * * @param data Pointer to the transaction id that will be contained * in the node. * @return Id of the newly created node. **/ inline node_id addNodeCheckExists(transaction_id *data) { for (std::vector<DirectedGraphNode>::const_iterator it = nodes_.cbegin(); it != nodes_.cend(); ++it) { CHECK(*data != it->getData()); } nodes_.emplace_back(data); return nodes_.size() - 1; } /** * @brief Adds an edge between nodes. It does not check whether the * parameters are valid node ids. * @warning Does not check arguments are legit. It may cause * out of range errors. * * @param fromNode The node that edge is orginated. * @param toNode The node that edge is ended. **/ inline void addEdgeUnchecked(node_id from_node, node_id to_node) { nodes_[from_node].addOutgoingEdge(to_node); } /** * @brief Adds an edge between nodes. It checks whether the * parameters are valid node ids. * * @param fromNode The node that edge is orginated. * @param toNode The node that edge is ended. **/ inline void addEdgeCheckExists(node_id from_node, node_id to_node) { CHECK(from_node < getNumNodes() && to_node < getNumNodes()); nodes_[from_node].addOutgoingEdge(to_node); } /** * @brief Check whether there is a directed edge. * @warning When parameters are not valid ids, it may cause * out of range errors. * * @param fromNode Id of the node that edge is originated from. * @param toNode Id of the node that edge is ended. * @return True if there is an edge, false otherwise. **/ inline bool hasEdge(node_id from_node, node_id to_node) const { DCHECK(from_node < getNumNodes() && to_node < getNumNodes()); return nodes_[from_node].hasOutgoingEdge(to_node); } /** * @brief Get data (transaction id) contained in the node. * @warning Does not check index validity. * * @param node Id of the node that the data is got from. * @return Id of the transaction that this node contains. **/ inline transaction_id getDataFromNode(node_id node) const { return nodes_[node].getData(); } /** * @brief Calculate how many nodes the graph has. * * @return The number of nodes the graph has. **/ inline std::size_t getNumNodes() const { return nodes_.size(); } /** * @brief Gives the node ids that this node has edges to. * * @param id Id of the corresponding node. * @return Vector of node ids that id has edges to. **/ inline std::vector<node_id> getAdjacentNodes(node_id id) const { return nodes_[id].getOutgoingEdges(); } private: // Class for representing a graph node. class DirectedGraphNode { public: explicit DirectedGraphNode(transaction_id *data) : data_(data) {} inline void addOutgoingEdge(node_id to_node) { outgoing_edges_.insert(to_node); } inline bool hasOutgoingEdge(node_id to_node) const { return outgoing_edges_.count(to_node) == 1; } inline std::vector<node_id> getOutgoingEdges() const { // TODO(hakan): Benchmark this version and the alternative which the // function returns const reference and the uniqueness // is imposed in the outgoing_edges_ as a vector. std::vector<node_id> result; std::copy(outgoing_edges_.begin(), outgoing_edges_.end(), std::back_inserter(result)); return result; } inline transaction_id getData() const { return *(data_.get()); } private: // Owner pointer to transaction id. std::unique_ptr<transaction_id> data_; // Endpoint nodes of outgoing edges originated from this node. std::unordered_set<node_id> outgoing_edges_; }; // The list of nodes that are created. NodeId is the index of that // node in this buffer. std::vector<DirectedGraphNode> nodes_; DISALLOW_COPY_AND_ASSIGN(DirectedGraph); }; /** @} */ } // namespace transaction } // namespace quickstep #endif // QUICKSTEP_TRANSACTION_DIRECTED_GRAPH_HPP_ <|endoftext|>
<commit_before>/// @file /// @author uentity /// @date 22.06.2018 /// @brief Implementation of BS tree-related serialization /// @copyright /// 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 https://mozilla.org/MPL/2.0/ #include <bs/actor_common.h> #include <bs/atoms.h> #include <bs/kernel/radio.h> #include <bs/log.h> #include <bs/tree/tree.h> #include <bs/serialize/serialize.h> #include <bs/serialize/tree.h> #include <bs/serialize/cafbind.h> CAF_ALLOW_UNSAFE_MESSAGE_TYPE(blue_sky::tree::on_serialized_f) NAMESPACE_BEGIN(blue_sky::tree) using namespace kernel::radio; /*----------------------------------------------------------------------------- * tree serialization actor impl *-----------------------------------------------------------------------------*/ NAMESPACE_BEGIN() /////////////////////////////////////////////////////////////////////////////// // Tree FS archive // auto unite_errors(const std::vector<error>& errs) -> error { std::string reduced_er; for(const auto& er : errs) { if(er) { if(!reduced_er.empty()) reduced_er += '\n'; reduced_er += er.what(); } } return reduced_er.empty() ? success() : error::quiet(reduced_er); } auto save_fs(const link& root, const std::string& filename) -> error { // collect all errors happened auto errs = std::vector<error>{}; if(auto er = error::eval_safe([&] { auto ar = tree_fs_output(filename); ar(root); //ar.serializeDeferments(); errs = ar.wait_objects_saved(infinite); })) errs.push_back(er); return unite_errors(errs); } auto load_fs(link& root, const std::string& filename) -> error { // collect all errors happened auto errs = std::vector<error>{}; if(auto er = error::eval_safe([&] { auto ar = tree_fs_input(filename, tree_fs_input::NodeLoad::Normal); ar(root); //ar.serializeDeferments(); errs = ar.wait_objects_loaded(infinite); })) errs.push_back(er); return unite_errors(errs); } /////////////////////////////////////////////////////////////////////////////// // generic archives // auto save_generic(const link& root, const std::string& filename, TreeArchive ar) -> error { return error::eval_safe([&]() -> error { // open file for writing std::ofstream fs( filename, std::ios::out | std::ios::trunc | (ar == TreeArchive::Binary ? std::ios::binary : std::ios::openmode()) ); fs.exceptions(fs.failbit | fs.badbit); // dump link to JSON archive if(ar == TreeArchive::Binary) { cereal::PortableBinaryOutputArchive ja(fs); ja(root); } else { cereal::JSONOutputArchive ja(fs); ja(root); } return perfect; }); } auto load_generic(link& root, const std::string& filename, TreeArchive ar) -> error { return error::eval_safe([&]() -> error { // open file for reading std::ifstream fs( filename, std::ios::in | (ar == TreeArchive::Binary ? std::ios::binary : std::ios::openmode()) ); fs.exceptions(fs.failbit | fs.badbit); // load link from JSON archive if(ar == TreeArchive::Binary) { cereal::PortableBinaryInputArchive ja(fs); ja(root); } else { cereal::JSONInputArchive ja(fs); ja(root); } return perfect; }); } /////////////////////////////////////////////////////////////////////////////// // serial ator impl // auto save_actor( caf::event_based_actor* self, link root, std::string filename, TreeArchive ar, on_serialized_f cb ) -> caf::behavior { return { [ar, r = std::move(root), filename = std::move(filename), cb = std::move(cb)](a_apply) mutable -> error::box { // launch work auto er = ar == TreeArchive::FS ? save_fs(r, filename) : save_generic(r, filename, ar); // invoke callback if(cb) error::eval_safe([&]{ cb(std::move(r), er); }); return er; } }; } auto load_actor( caf::event_based_actor* self, std::string filename, TreeArchive ar, on_serialized_f cb ) -> caf::behavior { return { [ar, filename = std::move(filename), cb = std::move(cb)](a_apply) mutable -> link_or_errbox { // launch work link r; auto er = ar == TreeArchive::FS ? load_fs(r, filename) : load_generic(r, filename, ar); // invoke callback if(cb) error::eval_safe([&]{ cb(r, er); }); if(er.ok()) return r; else return tl::make_unexpected(std::move(er)); } }; } NAMESPACE_END() /*----------------------------------------------------------------------------- * tree save impl *-----------------------------------------------------------------------------*/ auto save_tree(link root, std::string filename, TreeArchive ar, timespan wait_for) -> error { bsout() << "*** save_tree with {} timeout" << (wait_for == infinite ? "infinite" : to_string(wait_for)) << bs_end; // launch worker in detached actor auto Af = caf::make_function_view( system().spawn<caf::spawn_options::detach_flag>( save_actor, std::move(root), std::move(filename), ar, on_serialized_f{} ), wait_for == infinite ? caf::infinite : caf::duration{wait_for} ); // wait for result return actorf<error>(Af, a_apply()); } BS_API auto save_tree( on_serialized_f cb, link root, std::string filename, TreeArchive ar ) -> void { // [NOTE] spawn save in detached actor to prevent starvation auto A = system().spawn<caf::spawn_options::detach_flag>( save_actor, std::move(root), std::move(filename), ar, std::move(cb) ); caf::anon_send(A, a_apply()); } /*----------------------------------------------------------------------------- * tree load impl *-----------------------------------------------------------------------------*/ auto load_tree(std::string filename, TreeArchive ar) -> link_or_err { link r; auto er = ar == TreeArchive::FS ? load_fs(r, filename) : load_generic(r, filename, ar); if(er.ok()) return r; else return tl::make_unexpected(std::move(er)); //// launch worker in detached actor //auto Af = caf::make_function_view( // system().spawn<caf::spawn_options::detach_flag>( // load_actor, std::move(filename), ar, on_serialized_f{} // ), // caf::infinite //); //// wait for result //return actorf<link_or_errbox>(Af, a_apply()); } auto load_tree( on_serialized_f cb, std::string filename, TreeArchive ar ) -> void { // [NOTE] spawn save in detached actor to prevent starvation auto A = system().spawn<caf::spawn_options::detach_flag>( load_actor, std::move(filename), ar, std::move(cb) ); caf::anon_send(A, a_apply()); } NAMESPACE_END(blue_sky::tree) <commit_msg>serial/tree: fix load from monofile (non tree-fs) archives<commit_after>/// @file /// @author uentity /// @date 22.06.2018 /// @brief Implementation of BS tree-related serialization /// @copyright /// 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 https://mozilla.org/MPL/2.0/ #include <bs/actor_common.h> #include <bs/atoms.h> #include <bs/kernel/radio.h> #include <bs/log.h> #include <bs/tree/tree.h> #include <bs/serialize/serialize.h> #include <bs/serialize/tree.h> #include <bs/serialize/cafbind.h> #include <fstream> CAF_ALLOW_UNSAFE_MESSAGE_TYPE(blue_sky::tree::on_serialized_f) NAMESPACE_BEGIN(blue_sky::tree) using namespace kernel::radio; /*----------------------------------------------------------------------------- * tree serialization actor impl *-----------------------------------------------------------------------------*/ NAMESPACE_BEGIN() /////////////////////////////////////////////////////////////////////////////// // Tree FS archive // auto unite_errors(const std::vector<error>& errs) -> error { std::string reduced_er; for(const auto& er : errs) { if(er) { if(!reduced_er.empty()) reduced_er += '\n'; reduced_er += er.what(); } } return reduced_er.empty() ? success() : error::quiet(reduced_er); } auto save_fs(const link& root, const std::string& filename) -> error { // collect all errors happened auto errs = std::vector<error>{}; if(auto er = error::eval_safe([&] { auto ar = tree_fs_output(filename); ar(root); //ar.serializeDeferments(); errs = ar.wait_objects_saved(infinite); })) errs.push_back(er); return unite_errors(errs); } auto load_fs(link& root, const std::string& filename) -> error { // collect all errors happened auto errs = std::vector<error>{}; if(auto er = error::eval_safe([&] { auto ar = tree_fs_input(filename, tree_fs_input::NodeLoad::Normal); ar(root); //ar.serializeDeferments(); errs = ar.wait_objects_loaded(infinite); })) errs.push_back(er); return unite_errors(errs); } /////////////////////////////////////////////////////////////////////////////// // generic archives // auto save_generic(const link& root, const std::string& filename, TreeArchive ar) -> error { return error::eval_safe([&]() -> error { // open file for writing std::ofstream fs( filename, std::ios::out | std::ios::trunc | (ar == TreeArchive::Binary ? std::ios::binary : std::ios::openmode(0)) ); // dump link to JSON archive if(ar == TreeArchive::Binary) { cereal::PortableBinaryOutputArchive ja(fs); ja(root); } else { cereal::JSONOutputArchive ja(fs); ja(root); } return perfect; }); } auto load_generic(link& root, const std::string& filename, TreeArchive ar) -> error { return error::eval_safe([&]() -> error { // open file for reading auto mode = std::ios::in; if(ar == TreeArchive::Binary) mode |= std::ios::binary; std::ifstream fs( filename, std::ios::in | (ar == TreeArchive::Binary ? std::ios::binary : std::ios::openmode(0)) ); // load link from JSON archive if(ar == TreeArchive::Binary) { cereal::PortableBinaryInputArchive ja(fs); ja(root); } else { cereal::JSONInputArchive ja(fs); ja(root); } return perfect; }); } /////////////////////////////////////////////////////////////////////////////// // serial ator impl // auto save_actor( caf::event_based_actor* self, link root, std::string filename, TreeArchive ar, on_serialized_f cb ) -> caf::behavior { return { [ar, r = std::move(root), filename = std::move(filename), cb = std::move(cb)](a_apply) mutable -> error::box { // launch work auto er = ar == TreeArchive::FS ? save_fs(r, filename) : save_generic(r, filename, ar); // invoke callback if(cb) error::eval_safe([&]{ cb(std::move(r), er); }); return er; } }; } auto load_actor( caf::event_based_actor* self, std::string filename, TreeArchive ar, on_serialized_f cb ) -> caf::behavior { return { [ar, filename = std::move(filename), cb = std::move(cb)](a_apply) mutable -> link_or_errbox { // launch work link r; auto er = ar == TreeArchive::FS ? load_fs(r, filename) : load_generic(r, filename, ar); // invoke callback if(cb) error::eval_safe([&]{ cb(r, er); }); if(er.ok()) return r; else return tl::make_unexpected(std::move(er)); } }; } NAMESPACE_END() /*----------------------------------------------------------------------------- * tree save impl *-----------------------------------------------------------------------------*/ auto save_tree(link root, std::string filename, TreeArchive ar, timespan wait_for) -> error { //bsout() << "*** save_tree with {} timeout" << // (wait_for == infinite ? "infinite" : to_string(wait_for)) << bs_end; // launch worker in detached actor auto Af = caf::make_function_view( system().spawn<caf::spawn_options::detach_flag>( save_actor, std::move(root), std::move(filename), ar, on_serialized_f{} ), wait_for == infinite ? caf::infinite : caf::duration{wait_for} ); // wait for result return actorf<error>(Af, a_apply()); } BS_API auto save_tree( on_serialized_f cb, link root, std::string filename, TreeArchive ar ) -> void { // [NOTE] spawn save in detached actor to prevent starvation auto A = system().spawn<caf::spawn_options::detach_flag>( save_actor, std::move(root), std::move(filename), ar, std::move(cb) ); caf::anon_send(A, a_apply()); } /*----------------------------------------------------------------------------- * tree load impl *-----------------------------------------------------------------------------*/ auto load_tree(std::string filename, TreeArchive ar) -> link_or_err { //link r; //auto er = ar == TreeArchive::FS ? load_fs(r, filename) : load_generic(r, filename, ar); //if(er.ok()) // return r; //else // return tl::make_unexpected(std::move(er)); // launch worker in detached actor auto Af = caf::make_function_view( system().spawn<caf::spawn_options::detach_flag>( load_actor, std::move(filename), ar, on_serialized_f{} ), caf::infinite ); // wait for result return actorf<link_or_errbox>(Af, a_apply()); } auto load_tree( on_serialized_f cb, std::string filename, TreeArchive ar ) -> void { // [NOTE] spawn save in detached actor to prevent starvation auto A = system().spawn<caf::spawn_options::detach_flag>( load_actor, std::move(filename), ar, std::move(cb) ); caf::anon_send(A, a_apply()); } NAMESPACE_END(blue_sky::tree) <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qstring.h> #include <qkeycode.h> #include <qlayout.h> #include <qtimer.h> #include <qframe.h> #include <qlabel.h> #include <kdebug.h> #include <klocale.h> #include <kglobal.h> #include <kglobalsettings.h> #include "koglobals.h" #include "koprefs.h" #ifndef KORG_NOPLUGINS #include "kocore.h" #endif #include "kodaymatrix.h" #include <kcalendarsystem.h> #include "navigatorbar.h" #include "kdatenavigator.h" KDateNavigator::KDateNavigator( QWidget *parent, const char *name ) : QFrame( parent, name ) { setFrameStyle( QFrame::NoFrame ); QGridLayout *topLayout = new QGridLayout( this, 8, 8 ); mNavigatorBar = new NavigatorBar( this ); topLayout->addMultiCellWidget( mNavigatorBar, 0, 0, 0, 7 ); connect( mNavigatorBar, SIGNAL( goPrevYear() ), SIGNAL( goPrevYear() ) ); connect( mNavigatorBar, SIGNAL( goPrevMonth() ), SIGNAL( goPrevMonth() ) ); connect( mNavigatorBar, SIGNAL( goNextMonth() ), SIGNAL( goNextMonth() ) ); connect( mNavigatorBar, SIGNAL( goNextYear() ), SIGNAL( goNextYear() ) ); connect( mNavigatorBar, SIGNAL( goMonth( int ) ), SIGNAL( goMonth( int ) ) ); int i; QString generalFont = KGlobalSettings::generalFont().family(); // Set up the heading fields. for( i = 0; i < 7; i++ ) { headings[i] = new QLabel( this ); headings[i]->setFont( QFont( generalFont, 10, QFont::Bold ) ); headings[i]->setAlignment( AlignCenter ); topLayout->addWidget( headings[i], 1, i + 1 ); } // Create the weeknumber labels for( i = 0; i < 6; i++ ) { weeknos[i] = new QLabel( this ); weeknos[i]->setAlignment( AlignCenter ); weeknos[i]->setFont( QFont( generalFont, 10 ) ); weeknos[i]->installEventFilter( this ); topLayout->addWidget( weeknos[i], i + 2, 0 ); } mDayMatrix = new KODayMatrix( this, "KDateNavigator::dayMatrix" ); mDayMatrix->setFrameStyle( QFrame::Panel | QFrame::Sunken ); mDayMatrix->setLineWidth( 1 ); connect( mDayMatrix, SIGNAL( selected( const KCal::DateList & ) ), SIGNAL( datesSelected( const KCal::DateList & ) ) ); connect( mDayMatrix, SIGNAL( incidenceDropped( Incidence * ) ), SIGNAL( incidenceDropped( Incidence * ) ) ); connect( mDayMatrix, SIGNAL( incidenceDroppedMove( Incidence * , Incidence * ) ), SIGNAL( incidenceDroppedMove( Incidence *, Incidence * ) ) ); topLayout->addMultiCellWidget( mDayMatrix, 2, 7, 1, 7 ); // read settings from configuration file. updateConfig(); } KDateNavigator::~KDateNavigator() { } void KDateNavigator::setCalendar( Calendar *cal ) { mDayMatrix->setCalendar( cal ); } void KDateNavigator::setBaseDate( const QDate &date ) { mBaseDate = date; updateDates(); updateView(); KCal::DateList dates; dates.append( date ); mNavigatorBar->selectDates( dates ); mDayMatrix->clearSelection(); mDayMatrix->repaint(); } QSizePolicy KDateNavigator::sizePolicy () const { return QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ); } void KDateNavigator::updateToday() { if ( mDayMatrix->isEndOfMonth() ) { goNextMonth(); } mDayMatrix->recalculateToday(); mDayMatrix->repaint(); } void KDateNavigator::updateDates() { // Find the first day of the week of the current month. //int d1 = KOGlobals::self()->calendarSystem()->day( mBaseDate ); QDate dayone( mBaseDate.year(), mBaseDate.month(), mBaseDate.day() ); int d2 = KOGlobals::self()->calendarSystem()->day( dayone ); //int di = d1 - d2 + 1; dayone = dayone.addDays( -d2 + 1 ); int m_fstDayOfWkCalsys = KOGlobals::self()->calendarSystem()->dayOfWeek( dayone ); // If month begins on Monday and Monday is first day of week, // month should begin on second line. Sunday doesn't have this problem. int nextLine = ( ( m_fstDayOfWkCalsys == 1) && ( KGlobal::locale()->weekStartDay() == 1 ) ) ? 7 : 0; // update the matrix dates int index = ( KGlobal::locale()->weekStartDay() == 1 ? 1 : 0 ) - m_fstDayOfWkCalsys - nextLine; mDayMatrix->updateView( dayone.addDays( index ) ); // each updateDates is followed by an updateView -> repaint is issued there ! // mDayMatrix->repaint(); } void KDateNavigator::updateDayMatrix() { mDayMatrix->updateView(); mDayMatrix->repaint(); } void KDateNavigator::updateView() { // kdDebug() << "KDateNavigator::updateView()" << endl; setUpdatesEnabled( false ); int i; // kdDebug(5850) << "updateView() -> mDayMatrix->updateView()" << endl; mDayMatrix->updateView(); // set the week numbers. for( i = 0; i < 6; i++ ) { QString weeknum; // remember, according to ISO 8601, the first week of the year is the // first week that contains a thursday. Thus we must subtract off 4, // not just 1. //ET int dayOfYear = buttons[(i + 1) * 7 - 4]->date().dayOfYear(); int dayOfYear = KOGlobals::self()->calendarSystem()->dayOfYear( ( mDayMatrix->getDate( ( i + 1 ) * 7 - 4 ) ) ); if ( dayOfYear % 7 != 0 ) weeknum.setNum( dayOfYear / 7 + 1 ); else weeknum.setNum( dayOfYear / 7 ); weeknos[i]->setText( weeknum ); } setUpdatesEnabled( true ); // kdDebug(5850) << "updateView() -> repaint()" << endl; repaint(); mDayMatrix->repaint(); } void KDateNavigator::updateConfig() { int day; for( int i = 0; i < 7; i++ ) { // take the first letter of the day name to be the abbreviation if ( KGlobal::locale()->weekStartDay() == 1 ) { day = i + 1; } else { if ( i == 0 ) day = 7; else day = i; } QString dayName = KOGlobals::self()->calendarSystem()->weekDayName( day, true ); if ( KOPrefs::instance()->mCompactDialogs ) dayName = dayName.left( 1 ); headings[i]->setText( dayName ); } // FIXME: Use actual config setting here // setShowWeekNums( true ); } void KDateNavigator::setShowWeekNums( bool enabled ) { for( int i = 0; i < 6; i++ ) { if( enabled ) weeknos[i]->show(); else weeknos[i]->hide(); } } void KDateNavigator::selectDates( const DateList &dateList ) { if ( dateList.count() > 0 ) { mNavigatorBar->selectDates( dateList ); mSelectedDates = dateList; // set our record of the month and year that this datetbl is // displaying. mBaseDate = mSelectedDates.first(); updateDates(); mDayMatrix->setSelectedDaysFrom( *( dateList.begin() ), *( --dateList.end() ) ); updateView(); } } void KDateNavigator::wheelEvent ( QWheelEvent *e ) { if( e->delta() > 0 ) emit goPrevious(); else emit goNext(); e->accept(); } bool KDateNavigator::eventFilter ( QObject *o, QEvent *e ) { if ( e->type() == QEvent::MouseButtonPress ) { int i; for( i = 0; i < 6; ++i ) { if ( o == weeknos[ i ] ) { QDate weekstart = mDayMatrix->getDate( i * 7 ); emit weekClicked( weekstart ); break; } } return true; } else { return false; } } #include "kdatenavigator.moc" <commit_msg>Now that cvs head is open for commits again, apply the patch. If week start day is not monday, both week numbers are now shown like (for July 2004): Sun Mon Tue Wed Thu Fri Sat 26/27 27 28 29 30 1 2 3 27/28 4 5 6 7 8 9 10 28/29 11 12 13 14 15 16 17 29/30 18 19 20 21 22 23 24 30/31 25 26 27 28 29 30 31<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qstring.h> #include <qkeycode.h> #include <qlayout.h> #include <qtimer.h> #include <qframe.h> #include <qlabel.h> #include <kdebug.h> #include <klocale.h> #include <kglobal.h> #include <kglobalsettings.h> #include "koglobals.h" #include "koprefs.h" #ifndef KORG_NOPLUGINS #include "kocore.h" #endif #include "kodaymatrix.h" #include <kcalendarsystem.h> #include "navigatorbar.h" #include "kdatenavigator.h" KDateNavigator::KDateNavigator( QWidget *parent, const char *name ) : QFrame( parent, name ) { setFrameStyle( QFrame::NoFrame ); QGridLayout *topLayout = new QGridLayout( this, 8, 8 ); mNavigatorBar = new NavigatorBar( this ); topLayout->addMultiCellWidget( mNavigatorBar, 0, 0, 0, 7 ); connect( mNavigatorBar, SIGNAL( goPrevYear() ), SIGNAL( goPrevYear() ) ); connect( mNavigatorBar, SIGNAL( goPrevMonth() ), SIGNAL( goPrevMonth() ) ); connect( mNavigatorBar, SIGNAL( goNextMonth() ), SIGNAL( goNextMonth() ) ); connect( mNavigatorBar, SIGNAL( goNextYear() ), SIGNAL( goNextYear() ) ); connect( mNavigatorBar, SIGNAL( goMonth( int ) ), SIGNAL( goMonth( int ) ) ); int i; QString generalFont = KGlobalSettings::generalFont().family(); // Set up the heading fields. for( i = 0; i < 7; i++ ) { headings[i] = new QLabel( this ); headings[i]->setFont( QFont( generalFont, 10, QFont::Bold ) ); headings[i]->setAlignment( AlignCenter ); topLayout->addWidget( headings[i], 1, i + 1 ); } // Create the weeknumber labels for( i = 0; i < 6; i++ ) { weeknos[i] = new QLabel( this ); weeknos[i]->setAlignment( AlignCenter ); weeknos[i]->setFont( QFont( generalFont, 10 ) ); weeknos[i]->installEventFilter( this ); topLayout->addWidget( weeknos[i], i + 2, 0 ); } mDayMatrix = new KODayMatrix( this, "KDateNavigator::dayMatrix" ); mDayMatrix->setFrameStyle( QFrame::Panel | QFrame::Sunken ); mDayMatrix->setLineWidth( 1 ); connect( mDayMatrix, SIGNAL( selected( const KCal::DateList & ) ), SIGNAL( datesSelected( const KCal::DateList & ) ) ); connect( mDayMatrix, SIGNAL( incidenceDropped( Incidence * ) ), SIGNAL( incidenceDropped( Incidence * ) ) ); connect( mDayMatrix, SIGNAL( incidenceDroppedMove( Incidence * , Incidence * ) ), SIGNAL( incidenceDroppedMove( Incidence *, Incidence * ) ) ); topLayout->addMultiCellWidget( mDayMatrix, 2, 7, 1, 7 ); // read settings from configuration file. updateConfig(); } KDateNavigator::~KDateNavigator() { } void KDateNavigator::setCalendar( Calendar *cal ) { mDayMatrix->setCalendar( cal ); } void KDateNavigator::setBaseDate( const QDate &date ) { mBaseDate = date; updateDates(); updateView(); KCal::DateList dates; dates.append( date ); mNavigatorBar->selectDates( dates ); mDayMatrix->clearSelection(); mDayMatrix->repaint(); } QSizePolicy KDateNavigator::sizePolicy () const { return QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ); } void KDateNavigator::updateToday() { if ( mDayMatrix->isEndOfMonth() ) { goNextMonth(); } mDayMatrix->recalculateToday(); mDayMatrix->repaint(); } void KDateNavigator::updateDates() { // Find the first day of the week of the current month. //int d1 = KOGlobals::self()->calendarSystem()->day( mBaseDate ); QDate dayone( mBaseDate.year(), mBaseDate.month(), mBaseDate.day() ); int d2 = KOGlobals::self()->calendarSystem()->day( dayone ); //int di = d1 - d2 + 1; dayone = dayone.addDays( -d2 + 1 ); int m_fstDayOfWkCalsys = KOGlobals::self()->calendarSystem()->dayOfWeek( dayone ); // If month begins on Monday and Monday is first day of week, // month should begin on second line. Sunday doesn't have this problem. int nextLine = ( ( m_fstDayOfWkCalsys == 1) && ( KGlobal::locale()->weekStartDay() == 1 ) ) ? 7 : 0; // update the matrix dates int index = ( KGlobal::locale()->weekStartDay() == 1 ? 1 : 0 ) - m_fstDayOfWkCalsys - nextLine; mDayMatrix->updateView( dayone.addDays( index ) ); // each updateDates is followed by an updateView -> repaint is issued there ! // mDayMatrix->repaint(); } void KDateNavigator::updateDayMatrix() { mDayMatrix->updateView(); mDayMatrix->repaint(); } void KDateNavigator::updateView() { // kdDebug() << "KDateNavigator::updateView()" << endl; setUpdatesEnabled( false ); int i; // kdDebug(5850) << "updateView() -> mDayMatrix->updateView()" << endl; mDayMatrix->updateView(); // set the week numbers. const KCalendarSystem *calsys = KOGlobals::self()->calendarSystem(); for( i = 0; i < 6; i++ ) { // Use QDate's weekNumber method to determine the week number! QDate dtStart = mDayMatrix->getDate( i * 7 ); QDate dtEnd = mDayMatrix->getDate( ( i + 1 ) * 7 - 1 ); int weeknumstart = calsys->weekNumber( dtStart ); int weeknumend = calsys->weekNumber( dtEnd ); QString weeknum; if ( weeknumstart != weeknumend ) { weeknum = i18n("start/end week number of line in date picker", "%1/%2") .arg( weeknumstart ).arg( weeknumend ); } else { weeknum.setNum( weeknumstart ); } weeknos[i]->setText( weeknum ); } setUpdatesEnabled( true ); // kdDebug(5850) << "updateView() -> repaint()" << endl; repaint(); mDayMatrix->repaint(); } void KDateNavigator::updateConfig() { int day; for( int i = 0; i < 7; i++ ) { // take the first letter of the day name to be the abbreviation if ( KGlobal::locale()->weekStartDay() == 1 ) { day = i + 1; } else { if ( i == 0 ) day = 7; else day = i; } QString dayName = KOGlobals::self()->calendarSystem()->weekDayName( day, true ); if ( KOPrefs::instance()->mCompactDialogs ) dayName = dayName.left( 1 ); headings[i]->setText( dayName ); } // FIXME: Use actual config setting here // setShowWeekNums( true ); } void KDateNavigator::setShowWeekNums( bool enabled ) { for( int i = 0; i < 6; i++ ) { if( enabled ) weeknos[i]->show(); else weeknos[i]->hide(); } } void KDateNavigator::selectDates( const DateList &dateList ) { if ( dateList.count() > 0 ) { mNavigatorBar->selectDates( dateList ); mSelectedDates = dateList; // set our record of the month and year that this datetbl is // displaying. mBaseDate = mSelectedDates.first(); updateDates(); mDayMatrix->setSelectedDaysFrom( *( dateList.begin() ), *( --dateList.end() ) ); updateView(); } } void KDateNavigator::wheelEvent ( QWheelEvent *e ) { if( e->delta() > 0 ) emit goPrevious(); else emit goNext(); e->accept(); } bool KDateNavigator::eventFilter ( QObject *o, QEvent *e ) { if ( e->type() == QEvent::MouseButtonPress ) { int i; for( i = 0; i < 6; ++i ) { if ( o == weeknos[ i ] ) { QDate weekstart = mDayMatrix->getDate( i * 7 ); emit weekClicked( weekstart ); break; } } return true; } else { return false; } } #include "kdatenavigator.moc" <|endoftext|>
<commit_before>/* This file is part of the KDE libraries * Copyright (C) 2005 Joseph Wenninger <jowenn@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <editorchooser.h> #include <editorchooser.moc> #include <QtGui/QComboBox> #include <QtCore/QStringList> #include <QtGui/QLabel> #include <QtGui/QLayout> #include <kmimetypetrader.h> #include <kconfig.h> #include <klocale.h> #include <kglobal.h> #include "ui_editorchooser_ui.h" #include <kconfiggroup.h> using namespace KTextEditor; namespace KTextEditor { class PrivateEditorChooser { public: PrivateEditorChooser() { } ~PrivateEditorChooser(){} // Data Members Ui::EditorChooser *chooser; QStringList ElementNames; QStringList elements; }; } EditorChooser::EditorChooser(QWidget *parent) : QWidget(parent) { d = new PrivateEditorChooser (); d->chooser = new Ui::EditorChooser(); d->chooser->setupUi(this); KService::List offers = KMimeTypeTrader::self()->query("text/plain", "KTextEditor/Document"); KConfigGroup config = KSharedConfig::openConfig("default_components")->group("KTextEditor"); QString editor = config.readPathEntry("embeddedEditor", QString()); if (editor.isEmpty()) editor = "katepart"; // search default component for (KService::List::Iterator it = offers.begin(); it != offers.end(); ++it) { if ((*it)->desktopEntryName().contains(editor)) { d->chooser->editorCombo->addItem(i18n("System Default (currently: %1)", (*it)->name())); break; } } // add list of all available components for (KService::List::Iterator it = offers.begin(); it != offers.end(); ++it) { d->chooser->editorCombo->addItem((*it)->name()); d->elements.append((*it)->desktopEntryName()); } d->chooser->editorCombo->setCurrentIndex(0); connect(d->chooser->editorCombo,SIGNAL(activated(int)),this,SIGNAL(changed())); } EditorChooser:: ~EditorChooser() { delete d->chooser; delete d; } void EditorChooser::readAppSetting(const QString& postfix) { KConfigGroup cg(KGlobal::config(), "KTEXTEDITOR:" + postfix); QString editor = cg.readPathEntry("editor", QString()); if (editor.isEmpty()) d->chooser->editorCombo->setCurrentIndex(0); else { // + 1, because item 0 is the default one. int idx = d->elements.indexOf(editor) + 1; d->chooser->editorCombo->setCurrentIndex(idx); } } void EditorChooser::writeAppSetting(const QString& postfix) { KConfigGroup cg(KGlobal::config(), "KTEXTEDITOR:" + postfix); cg.writeEntry("DEVELOPER_INFO","NEVER TRY TO USE VALUES FROM THAT GROUP, THEY ARE SUBJECT TO CHANGES"); cg.writePathEntry("editor", (d->chooser->editorCombo->currentIndex()<=0) ? //< for broken installations, where editor list is empty QString() : QString(d->elements.at(d->chooser->editorCombo->currentIndex()-1))); } KTextEditor::Editor *EditorChooser::editor(const QString& postfix, bool fallBackToKatePart) { // try to read the used library from the application's config KConfigGroup cg(KGlobal::config(), "KTEXTEDITOR:" + postfix); QString editor = cg.readPathEntry("editor", QString()); if (editor.isEmpty()) { // there is no library set in the application's config, // fall back to KDE's system default KConfig config("default_components"); editor = config.group("KTextEditor").readPathEntry("embeddedEditor", "katepart"); } KService::Ptr serv = KService::serviceByDesktopName(editor); if (serv) { KTextEditor::Editor *tmpEd = KTextEditor::editor(serv->library().toLatin1()); if (tmpEd) return tmpEd; } if (fallBackToKatePart) return KTextEditor::editor("katepart"); return 0; } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>Enforce minimum size<commit_after>/* This file is part of the KDE libraries * Copyright (C) 2005 Joseph Wenninger <jowenn@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <editorchooser.h> #include <editorchooser.moc> #include <QtGui/QComboBox> #include <QtCore/QStringList> #include <QtGui/QLabel> #include <QtGui/QLayout> #include <kmimetypetrader.h> #include <kconfig.h> #include <klocale.h> #include <kglobal.h> #include "ui_editorchooser_ui.h" #include <kconfiggroup.h> using namespace KTextEditor; namespace KTextEditor { class PrivateEditorChooser { public: PrivateEditorChooser() { } ~PrivateEditorChooser(){} // Data Members Ui::EditorChooser *chooser; QStringList ElementNames; QStringList elements; }; } EditorChooser::EditorChooser(QWidget *parent) : QWidget(parent) { d = new PrivateEditorChooser (); d->chooser = new Ui::EditorChooser(); d->chooser->setupUi(this); KService::List offers = KMimeTypeTrader::self()->query("text/plain", "KTextEditor/Document"); KConfigGroup config = KSharedConfig::openConfig("default_components")->group("KTextEditor"); QString editor = config.readPathEntry("embeddedEditor", QString()); if (editor.isEmpty()) editor = "katepart"; // search default component for (KService::List::Iterator it = offers.begin(); it != offers.end(); ++it) { if ((*it)->desktopEntryName().contains(editor)) { d->chooser->editorCombo->addItem(i18n("System Default (currently: %1)", (*it)->name())); break; } } // add list of all available components for (KService::List::Iterator it = offers.begin(); it != offers.end(); ++it) { d->chooser->editorCombo->addItem((*it)->name()); d->elements.append((*it)->desktopEntryName()); } d->chooser->editorCombo->setCurrentIndex(0); connect(d->chooser->editorCombo,SIGNAL(activated(int)),this,SIGNAL(changed())); setMinimumSize(sizeHint()); } EditorChooser:: ~EditorChooser() { delete d->chooser; delete d; } void EditorChooser::readAppSetting(const QString& postfix) { KConfigGroup cg(KGlobal::config(), "KTEXTEDITOR:" + postfix); QString editor = cg.readPathEntry("editor", QString()); if (editor.isEmpty()) d->chooser->editorCombo->setCurrentIndex(0); else { // + 1, because item 0 is the default one. int idx = d->elements.indexOf(editor) + 1; d->chooser->editorCombo->setCurrentIndex(idx); } } void EditorChooser::writeAppSetting(const QString& postfix) { KConfigGroup cg(KGlobal::config(), "KTEXTEDITOR:" + postfix); cg.writeEntry("DEVELOPER_INFO","NEVER TRY TO USE VALUES FROM THAT GROUP, THEY ARE SUBJECT TO CHANGES"); cg.writePathEntry("editor", (d->chooser->editorCombo->currentIndex()<=0) ? //< for broken installations, where editor list is empty QString() : QString(d->elements.at(d->chooser->editorCombo->currentIndex()-1))); } KTextEditor::Editor *EditorChooser::editor(const QString& postfix, bool fallBackToKatePart) { // try to read the used library from the application's config KConfigGroup cg(KGlobal::config(), "KTEXTEDITOR:" + postfix); QString editor = cg.readPathEntry("editor", QString()); if (editor.isEmpty()) { // there is no library set in the application's config, // fall back to KDE's system default KConfig config("default_components"); editor = config.group("KTextEditor").readPathEntry("embeddedEditor", "katepart"); } KService::Ptr serv = KService::serviceByDesktopName(editor); if (serv) { KTextEditor::Editor *tmpEd = KTextEditor::editor(serv->library().toLatin1()); if (tmpEd) return tmpEd; } if (fallBackToKatePart) return KTextEditor::editor("katepart"); return 0; } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before><commit_msg>WaE: keep msvc happy<commit_after><|endoftext|>
<commit_before>/** * @file lsh_test.cpp * * Unit tests for the 'LSHSearch' class. */ #include <mlpack/core.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" #include <mlpack/methods/lsh/lsh_search.hpp> #include <mlpack/methods/neighbor_search/neighbor_search.hpp> using namespace std; using namespace mlpack; using namespace mlpack::neighbor; double compute_recall( const arma::Mat<size_t>& LSHneighbors, const arma::Mat<size_t>& groundTruth) { const size_t queries = LSHneighbors.n_cols; const size_t neigh = LSHneighbors.n_rows; int same = 0; for (size_t q = 0; q < queries; ++q) { for (size_t n = 0; n < neigh; ++n) { same += (LSHneighbors(n,q) == groundTruth(n,q)); } } return static_cast<double>(same)/ (static_cast<double>(queries*neigh)); } BOOST_AUTO_TEST_SUITE(LSHTest); /** * Test: Run LSH with varying number of tables, keeping all other parameters * constant. Compute the recall, i.e. the number of reported neighbors that * are real neighbors of the query. * LSH's property is that (with high probability), increasing the number of * tables will increase recall. Epsilon ensures that if noise lightly affects * the projections, the test will not fail. * This produces false negatives, so we attempt the test numTries times and * only declare failure if all of them fail. */ BOOST_AUTO_TEST_CASE(numTablesTest) { //math::RandomSeed(time(0)); //kNN and LSH parameters (use LSH default parameters) const int k = 4; const int numProj = 10; const double hashWidth = 0; const int secondHashSize = 99901; const int bucketSize = 500; //test parameters const double epsilon = 0.1; //allowed deviation from expected monotonicity const int numTries = 5; //tries for each test before declaring failure //read iris training and testing data as reference and query const string trainSet="iris_train.csv"; const string testSet="iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); //Run classic knn on reference data AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); bool fail; for (int t = 0; t < numTries; ++t) { fail = false; const int lSize = 6; //number of runs const int lValue[] = {1, 8, 16, 32, 64, 128}; //number of tables double lValueRecall[lSize] = {0.0}; //recall of each LSH run for (size_t l=0; l < lSize; ++l) { //run LSH with only numTables varying (other values default) LSHSearch<> lshTest(rdata, numProj, lValue[l], hashWidth, secondHashSize, bucketSize); arma::Mat<size_t> LSHneighbors; arma::mat LSHdistances; lshTest.Search(qdata, k, LSHneighbors, LSHdistances); //compute recall for each query lValueRecall[l] = compute_recall(LSHneighbors, groundTruth); if (l > 0) { if(lValueRecall[l] < lValueRecall[l-1] - epsilon) { fail = true; //if test fails at one point, stop and retry break; } } } if ( !fail ) break; //if test passes one time, it is sufficient } BOOST_REQUIRE(fail == false); } /*Test: Run LSH with varying hash width, keeping all other parameters * constant. Compute the recall, i.e. the number of reported neighbors that * are real neighbors of the query. * LSH's property is that (with high probability), increasing the hash width * will increase recall. Epsilon ensures that if noise lightly affects the * projections, the test will not fail. */ BOOST_AUTO_TEST_CASE(hashWidthTest) { //math::RandomSeed(time(0)); //kNN and LSH parameters (use LSH default parameters) const int k = 4; const int numTables = 30; const int numProj = 10; const int secondHashSize = 99901; const int bucketSize = 500; //test parameters const double epsilon = 0.1; //allowed deviation from expected monotonicity //read iris training and testing data as reference and query const string trainSet="iris_train.csv"; const string testSet="iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); //Run classic knn on reference data AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); const int hSize = 7; //number of runs const double hValue[] = {0.1, 0.5, 1, 5, 10, 50, 500}; //hash width double hValueRecall[hSize] = {0.0}; //recall of each run for (size_t h = 0; h < hSize; ++h) { //run LSH with only hashWidth varying (other values default) LSHSearch<> lshTest( rdata, numProj, numTables, hValue[h], secondHashSize, bucketSize); arma::Mat<size_t> LSHneighbors; arma::mat LSHdistances; lshTest.Search(qdata, k, LSHneighbors, LSHdistances); //compute recall for each query hValueRecall[h] = compute_recall(LSHneighbors, groundTruth); if (h > 0) BOOST_REQUIRE_GE(hValueRecall[h], hValueRecall[h-1] - epsilon); } } /** * Test: Run LSH with varying number of projections, keeping other parameters * constant. Compute the recall, i.e. the number of reported neighbors that * are real neighbors of the query. * LSH's property is that (with high probability), increasing the number of * projections per table will decrease recall. Epsilon ensures that if noise * lightly affects the projections, the test will not fail. */ BOOST_AUTO_TEST_CASE(numProjTest) { //math::RandomSeed(time(0)); //kNN and LSH parameters (use LSH default parameters) const int k = 4; const int numTables = 30; const double hashWidth = 0; const int secondHashSize = 99901; const int bucketSize = 500; //test parameters const double epsilon = 0.1; //allowed deviation from expected monotonicity //read iris training and testing data as reference and query const string trainSet="iris_train.csv"; const string testSet="iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); //Run classic knn on reference data AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); //LSH test parameters for numProj const int pSize = 5; //number of runs const int pValue[] = {1, 10, 20, 50, 100}; //number of projections double pValueRecall[pSize] = {0.0}; //recall of each run for (size_t p = 0; p < pSize; ++p) { //run LSH with only numProj varying (other values default) LSHSearch<> lshTest( rdata, pValue[p], numTables, hashWidth, secondHashSize, bucketSize); arma::Mat<size_t> LSHneighbors; arma::mat LSHdistances; lshTest.Search(qdata, k, LSHneighbors, LSHdistances); //compute recall for each query pValueRecall[p] = compute_recall(LSHneighbors, groundTruth); if (p > 0) //don't check first run, only that increasing P decreases recall BOOST_REQUIRE_LE(pValueRecall[p] - epsilon, pValueRecall[p-1]); } } /** * Test: Run two LSH searches: * First, a very expensive LSH search, with a large number of hash tables * and a large hash width. This run should return an acceptable recall. We set * the bar very low (recall >= 50%) to make sure that a test fail means bad * implementation. * Second, a very cheap LSH search, with parameters that should cause recall * to be very low. Set the threshhold very high (recall <= 25%) to make sure * that a test fail means bad implementation. */ BOOST_AUTO_TEST_CASE(recallTest) { //math::RandomSeed(time(0)); //kNN and LSH parameters (use LSH default parameters) const int k = 4; const int secondHashSize = 99901; const int bucketSize = 500; //read iris training and testing data as reference and query const string trainSet="iris_train.csv"; const string testSet="iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); //Run classic knn on reference data AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); //Expensive LSH run const int hExp = 10000; //first-level hash width const int kExp = 1; //projections per table const int tExp = 128; //number of tables const double recallThreshExp = 0.5; LSHSearch<> lshTestExp( rdata, kExp, tExp, hExp, secondHashSize, bucketSize); arma::Mat<size_t> LSHneighborsExp; arma::mat LSHdistancesExp; lshTestExp.Search(qdata, k, LSHneighborsExp, LSHdistancesExp); const double recallExp = compute_recall(LSHneighborsExp, groundTruth); //This run should have recall higher than the threshold BOOST_REQUIRE_GE(recallExp, recallThreshExp); //Cheap LSH Run const int hChp = 1; //small first-level hash width const int kChp = 1000; //large number of projections per table const int tChp = 1; //only one table const double recallThreshChp = 0.25; //recall threshold LSHSearch<> lshTestChp( rdata, kChp, tChp, hChp, secondHashSize, bucketSize); arma::Mat<size_t> LSHneighborsChp; arma::mat LSHdistancesChp; lshTestChp.Search(qdata, k, LSHneighborsChp, LSHdistancesChp); const double recallChp = compute_recall(LSHneighborsChp, groundTruth); //This run should have recall lower than the threshold BOOST_REQUIRE_LE(recallChp, recallThreshChp); } BOOST_AUTO_TEST_CASE(LSHTrainTest) { // This is a not very good test that simply checks that the re-trained LSH // model operates on the correct dimensionality and returns the correct number // of results. arma::mat referenceData = arma::randu<arma::mat>(3, 100); arma::mat newReferenceData = arma::randu<arma::mat>(10, 400); arma::mat queryData = arma::randu<arma::mat>(10, 200); LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3); lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4); arma::Mat<size_t> neighbors; arma::mat distances; lsh.Search(queryData, 3, neighbors, distances); BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200); BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3); BOOST_REQUIRE_EQUAL(distances.n_cols, 200); BOOST_REQUIRE_EQUAL(distances.n_rows, 3); } BOOST_AUTO_TEST_CASE(EmptyConstructorTest) { // If we create an empty LSH model and then call Search(), it should throw an // exception. LSHSearch<> lsh; arma::mat dataset = arma::randu<arma::mat>(5, 50); arma::mat distances; arma::Mat<size_t> neighbors; BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances), std::invalid_argument); // Now, train. lsh.Train(dataset, 4, 3, 3.0, 12, 4); lsh.Search(dataset, 3, neighbors, distances); BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50); BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3); BOOST_REQUIRE_EQUAL(distances.n_cols, 50); BOOST_REQUIRE_EQUAL(distances.n_rows, 3); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Style fixes for LSH test.<commit_after>/** * @file lsh_test.cpp * * Unit tests for the 'LSHSearch' class. */ #include <mlpack/core.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" #include <mlpack/methods/lsh/lsh_search.hpp> #include <mlpack/methods/neighbor_search/neighbor_search.hpp> using namespace std; using namespace mlpack; using namespace mlpack::neighbor; double ComputeRecall( const arma::Mat<size_t>& lshNeighbors, const arma::Mat<size_t>& groundTruth) { const size_t queries = lshNeighbors.n_cols; const size_t neigh = lshNeighbors.n_rows; size_t same = 0; for (size_t q = 0; q < queries; ++q) { for (size_t n = 0; n < neigh; ++n) { same += (lshNeighbors(n, q) == groundTruth(n, q)); } } return static_cast<double>(same) / (static_cast<double>(queries * neigh)); } BOOST_AUTO_TEST_SUITE(LSHTest); /** * Test: Run LSH with varying number of tables, keeping all other parameters * constant. Compute the recall, i.e. the number of reported neighbors that * are real neighbors of the query. * LSH's property is that (with high probability), increasing the number of * tables will increase recall. Epsilon ensures that if noise lightly affects * the projections, the test will not fail. * This produces false negatives, so we attempt the test numTries times and * only declare failure if all of them fail. */ BOOST_AUTO_TEST_CASE(NumTablesTest) { // kNN and LSH parameters (use LSH default parameters). const int k = 4; const int numProj = 10; const double hashWidth = 0; const int secondHashSize = 99901; const int bucketSize = 500; // Test parameters. const double epsilon = 0.1; // Allowed deviation from expected monotonicity. const int numTries = 5; // Tries for each test before declaring failure. // Read iris training and testing data as reference and query sets. const string trainSet = "iris_train.csv"; const string testSet = "iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); // Run classic knn on reference data. AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); bool fail; for (int t = 0; t < numTries; ++t) { fail = false; const int lSize = 6; // Number of runs. const int lValue[] = {1, 8, 16, 32, 64, 128}; // Number of tables. double lValueRecall[lSize] = {0.0}; // Recall of each LSH run. for (size_t l = 0; l < lSize; ++l) { // Run LSH with only numTables varying (other values are defaults). LSHSearch<> lshTest(rdata, numProj, lValue[l], hashWidth, secondHashSize, bucketSize); arma::Mat<size_t> lshNeighbors; arma::mat lshDistances; lshTest.Search(qdata, k, lshNeighbors, lshDistances); // Compute recall for each query. lValueRecall[l] = ComputeRecall(lshNeighbors, groundTruth); if (l > 0) { if (lValueRecall[l] < lValueRecall[l - 1] - epsilon) { fail = true; // If test fails at one point, stop and retry. break; } } } if (!fail) break; // If test passes one time, it is sufficient. } BOOST_REQUIRE(fail == false); } /** * Test: Run LSH with varying hash width, keeping all other parameters * constant. Compute the recall, i.e. the number of reported neighbors that * are real neighbors of the query. * LSH's property is that (with high probability), increasing the hash width * will increase recall. Epsilon ensures that if noise lightly affects the * projections, the test will not fail. */ BOOST_AUTO_TEST_CASE(HashWidthTest) { // kNN and LSH parameters (use LSH default parameters). const int k = 4; const int numTables = 30; const int numProj = 10; const int secondHashSize = 99901; const int bucketSize = 500; // Test parameters. const double epsilon = 0.1; // Allowed deviation from expected monotonicity. // Read iris training and testing data as reference and query. const string trainSet = "iris_train.csv"; const string testSet = "iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); // Run classic knn on reference data. AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); const int hSize = 7; // Number of runs. const double hValue[] = {0.1, 0.5, 1, 5, 10, 50, 500}; // Hash width. double hValueRecall[hSize] = {0.0}; // Recall of each run. for (size_t h = 0; h < hSize; ++h) { // Run LSH with only hashWidth varying (other values are defaults). LSHSearch<> lshTest( rdata, numProj, numTables, hValue[h], secondHashSize, bucketSize); arma::Mat<size_t> lshNeighbors; arma::mat lshDistances; lshTest.Search(qdata, k, lshNeighbors, lshDistances); // Compute recall for each query. hValueRecall[h] = ComputeRecall(lshNeighbors, groundTruth); if (h > 0) BOOST_REQUIRE_GE(hValueRecall[h], hValueRecall[h - 1] - epsilon); } } /** * Test: Run LSH with varying number of projections, keeping other parameters * constant. Compute the recall, i.e. the number of reported neighbors that * are real neighbors of the query. * LSH's property is that (with high probability), increasing the number of * projections per table will decrease recall. Epsilon ensures that if noise * lightly affects the projections, the test will not fail. */ BOOST_AUTO_TEST_CASE(NumProjTest) { // kNN and LSH parameters (use LSH default parameters). const int k = 4; const int numTables = 30; const double hashWidth = 0; const int secondHashSize = 99901; const int bucketSize = 500; // Test parameters. const double epsilon = 0.1; // Allowed deviation from expected monotonicity. // Read iris training and testing data as reference and query sets. const string trainSet = "iris_train.csv"; const string testSet = "iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); // Run classic knn on reference data. AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); // LSH test parameters for numProj. const int pSize = 5; // Number of runs. const int pValue[] = {1, 10, 20, 50, 100}; // Number of projections. double pValueRecall[pSize] = {0.0}; // Recall of each run. for (size_t p = 0; p < pSize; ++p) { // Run LSH with only numProj varying (other values are defaults). LSHSearch<> lshTest( rdata, pValue[p], numTables, hashWidth, secondHashSize, bucketSize); arma::Mat<size_t> lshNeighbors; arma::mat lshDistances; lshTest.Search(qdata, k, lshNeighbors, lshDistances); // Compute recall for each query. pValueRecall[p] = ComputeRecall(lshNeighbors, groundTruth); // Don't check the first run; only check that increasing P decreases recall. if (p > 0) BOOST_REQUIRE_LE(pValueRecall[p] - epsilon, pValueRecall[p - 1]); } } /** * Test: Run two LSH searches: * First, a very expensive LSH search, with a large number of hash tables * and a large hash width. This run should return an acceptable recall. We set * the bar very low (recall >= 50%) to make sure that a test fail means bad * implementation. * Second, a very cheap LSH search, with parameters that should cause recall * to be very low. Set the threshhold very high (recall <= 25%) to make sure * that a test fail means bad implementation. */ BOOST_AUTO_TEST_CASE(RecallTest) { // kNN and LSH parameters (use LSH default parameters). const int k = 4; const int secondHashSize = 99901; const int bucketSize = 500; // Read iris training and testing data as reference and query sets. const string trainSet = "iris_train.csv"; const string testSet = "iris_test.csv"; arma::mat rdata; arma::mat qdata; data::Load(trainSet, rdata, true); data::Load(testSet, qdata, true); // Run classic knn on reference data. AllkNN knn(rdata); arma::Mat<size_t> groundTruth; arma::mat groundDistances; knn.Search(qdata, k, groundTruth, groundDistances); // Expensive LSH run. const int hExp = 10000; // First-level hash width. const int kExp = 1; // Projections per table. const int tExp = 128; // Number of tables. const double recallThreshExp = 0.5; LSHSearch<> lshTestExp( rdata, kExp, tExp, hExp, secondHashSize, bucketSize); arma::Mat<size_t> lshNeighborsExp; arma::mat lshDistancesExp; lshTestExp.Search(qdata, k, lshNeighborsExp, lshDistancesExp); const double recallExp = ComputeRecall(lshNeighborsExp, groundTruth); // This run should have recall higher than the threshold. BOOST_REQUIRE_GE(recallExp, recallThreshExp); // Cheap LSH run. const int hChp = 1; // Small first-level hash width. const int kChp = 1000; // Large number of projections per table. const int tChp = 1; // Only one table. const double recallThreshChp = 0.25; // Recall threshold. LSHSearch<> lshTestChp( rdata, kChp, tChp, hChp, secondHashSize, bucketSize); arma::Mat<size_t> lshNeighborsChp; arma::mat lshDistancesChp; lshTestChp.Search(qdata, k, lshNeighborsChp, lshDistancesChp); const double recallChp = ComputeRecall(lshNeighborsChp, groundTruth); // This run should have recall lower than the threshold. BOOST_REQUIRE_LE(recallChp, recallThreshChp); } BOOST_AUTO_TEST_CASE(LSHTrainTest) { // This is a not very good test that simply checks that the re-trained LSH // model operates on the correct dimensionality and returns the correct number // of results. arma::mat referenceData = arma::randu<arma::mat>(3, 100); arma::mat newReferenceData = arma::randu<arma::mat>(10, 400); arma::mat queryData = arma::randu<arma::mat>(10, 200); LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3); lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4); arma::Mat<size_t> neighbors; arma::mat distances; lsh.Search(queryData, 3, neighbors, distances); BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200); BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3); BOOST_REQUIRE_EQUAL(distances.n_cols, 200); BOOST_REQUIRE_EQUAL(distances.n_rows, 3); } BOOST_AUTO_TEST_CASE(EmptyConstructorTest) { // If we create an empty LSH model and then call Search(), it should throw an // exception. LSHSearch<> lsh; arma::mat dataset = arma::randu<arma::mat>(5, 50); arma::mat distances; arma::Mat<size_t> neighbors; BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances), std::invalid_argument); // Now, train. lsh.Train(dataset, 4, 3, 3.0, 12, 4); lsh.Search(dataset, 3, neighbors, distances); BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50); BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3); BOOST_REQUIRE_EQUAL(distances.n_cols, 50); BOOST_REQUIRE_EQUAL(distances.n_rows, 3); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>#include "MaterialElement.h" #include "PhysicalElement.h" #include <iostream> //Constructors & destructor------------------------------- MaterialElement::MaterialElement() {} MaterialElement::MaterialElement(Point P, double masse , double charge_) { position = P; // does a shallow copy of P mass = masse; charge = charge_; } MaterialElement::~MaterialElement() {} //Accessors--------------------------------------------- Point * MaterialElement::pointerToPosition() { Point *pos= NULL; pos = &position; return pos; } double MaterialElement::getMass() { return mass; } //Display----------------------------------------------- void MaterialElement::consoleShow() { position.show(); std::cout<<"mass: "<<mass<<'\n'; } //Modifier---------------------------------------------- void MaterialElement::setPosition(Point &P) { position = P; } void MaterialElement::setPosition(double x, double y, double z) { position.place(x,y,z); } void MaterialElement::setMass(double m) { mass=m; } //Simulation tool------------------------------------- void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt { Acceleration a; a = getAcceleration(); updateSpeedandPosition(a, dt); } Acceleration MaterialElement::getAcceleration() { Acceleration a; a.nullify(); Vector V = netForce.getDirection(); if( mass != 0 ) { V = V*( 1 / mass); a.setDirection(V); } else { std::cout<<"** No mass no accs :-( **"<<'\n'; } return a; } void MaterialElement::updateSpeedandPosition(Acceleration a, double dt) { double Vx,Vy,Vz,X,Y,Z; //Initial speeds Vx = V.getDirection().getx(); Vy = V.getDirection().gety(); Vz = V.getDirection().getz(); //Double integration of the accelerations gives final positions X = 0.5*a.getDirection().getx()*dt*dt + Vx*dt + position.getX(); Y = 0.5*a.getDirection().gety()*dt*dt + Vy*dt + position.getY(); Z = 0.5*a.getDirection().getz()*dt*dt + Vz*dt + position.getZ(); position.place(X,Y,Z); //integration of the accelerations gives final speeds Vx = a.getDirection().getx()*dt + V.getDirection().getx(); Vy = a.getDirection().gety()*dt + V.getDirection().gety(); Vz = a.getDirection().getz()*dt + V.getDirection().getz(); V.setDirection(Vx,Vy,Vz); } <commit_msg>Update MaterialElement.cpp<commit_after>#include "MaterialElement.h" #include "PhysicalElement.h" #include <iostream> //Constructors & destructor------------------------------- MaterialElement::MaterialElement() {} MaterialElement::MaterialElement(Point p, double masse , double charge_) { Position = p; // does a shallow copy of P Mass = masse; Charge = charge_; } MaterialElement::~MaterialElement() {} //Accessors--------------------------------------------- Point * MaterialElement::pointerToPosition() { Point *pos= NULL; pos = &Position; return pos; } double MaterialElement::getMass() { return Mass; } //Display----------------------------------------------- void MaterialElement::consoleShow() { Position.show(); std::cout<<"mass: "<<Mass<<'\n'; } //Modifier---------------------------------------------- void MaterialElement::setPosition(Point &P) { Position = P; } void MaterialElement::setPosition(double x, double y, double z) { Position.set(x,y,z); } void MaterialElement::setMass(double m) { Mass=m; } //Simulation tool------------------------------------- void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt { Acceleration a; a = getAcceleration(); updateSpeedandPosition(a, dt); } Acceleration MaterialElement::getAcceleration() { Acceleration a; a.nullify(); Vect V = NetForce.getDirection(); if( Mass != 0 ) { V = V / Mass; a.setDirection(V); } else { std::cout<<"** No mass no accs :-( **"<<'\n'; } return a; } void MaterialElement::updateSpeedandPosition(Acceleration a, double dt) { double Vx,Vy,Vz,X,Y,Z; //Initial speeds Vx = V.getDirection().getX(); Vy = V.getDirection().getY(); Vz = V.getDirection().getZ(); //Double integration of the accelerations gives final positions X = 0.5*a.getDirection().getX()*dt*dt + Vx*dt + Position.getX(); Y = 0.5*a.getDirection().getY()*dt*dt + Vy*dt + Position.getY(); Z = 0.5*a.getDirection().getZ()*dt*dt + Vz*dt + Position.getZ(); Position.set(X,Y,Z); //integration of the accelerations gives final speeds Vx = a.getDirection().getX()*dt + V.getDirection().getX(); Vy = a.getDirection().getY()*dt + V.getDirection().getY(); Vz = a.getDirection().getZ()*dt + V.getDirection().getZ(); V.setDirection(Vx,Vy,Vz); } <|endoftext|>
<commit_before>#include "MaterialElement.h" #include "Geo.h" #include <iostream> //Constructors & destructor------------------------------- MaterialElement::MaterialElement() {} MaterialElement::MaterialElement(Point p, Vect resultantForce, Vect velocity, double masse, double charge_ ) { Charge = charge_; // in Coulomb Mass = masse; // in kg Velocity = velocity; // m/s NetForce = resultantForce; // Newton Position = p; // m } MaterialElement::~MaterialElement() {} //Accessors--------------------------------------------- Point * MaterialElement::pointerToPosition() { Point *pos = NULL; pos = &Position; return pos; } double MaterialElement::getMass() { return Mass; } double MaterialElement::getCharge() { return Charge; } //Display----------------------------------------------- void MaterialElement::consoleShow() { Position.show(); std::cout << "mass: " << Mass << '\n'; std::cout << "charge: " << Charge << '\n'; } //Modifier---------------------------------------------- void MaterialElement::setPosition(Point &P) { Position = P; } void MaterialElement::setPosition(double x, double y, double z) { Position.place(x, y, z); } void MaterialElement::setMass(double m) { Mass = m; } void MaterialElement::setCharge(double c) { Charge = c; } void MaterialElement::setResultant(Vect force) { NetForce = force; } //Simulation tool------------------------------------- void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt { Vect a; a = getAcceleration(); updateSpeedandPosition(a, dt); } Vect MaterialElement::getAcceleration() { Vect a; a.nullify(); Vect V = NetForce; if (Mass != 0) { a = V / Mass; } else { std::cout << "** No mass no accs :-( **" << '\n'; } return a; } void MaterialElement::updateSpeedandPosition(Vect a, double dt) { CartesianElement Acceleration = a; CartesianElement InitialVelocity = Velocity; //double integration of the acceleration gives final position Position = Acceleration*0.5*dt*dt + InitialVelocity*dt + Position; //integration of the acceleration gives final speeds Velocity = InitialVelocity + Acceleration; } // ------------------- Material Point ---------------- MaterialPoint::MaterialPoint() {} MaterialPoint::~MaterialPoint() {} <commit_msg>external actions used, calculator helper added<commit_after>#include "MaterialElement.h" #include "Geo.h" #include "Calculator.h" #include<vector> #include <iostream> //Constructors & destructor------------------------------- MaterialElement::MaterialElement() {} MaterialElement::MaterialElement(Point p, std::vector<Vect> actions, Vect velocity, double masse, double charge_) { Charge = charge_; // in Coulomb Mass = masse; // in kg Velocity = velocity; // m/s ExternalActions = actions; //Newton Position = p; // m } MaterialElement::~MaterialElement() {} //Accessors--------------------------------------------- Point * MaterialElement::pointerToPosition() { Point *pos = NULL; pos = &Position; return pos; } double MaterialElement::getMass() { return Mass; } double MaterialElement::getCharge() { return Charge; } //Display----------------------------------------------- void MaterialElement::consoleShow() { Position.show(); std::cout << "mass: " << Mass << '\n'; std::cout << "charge: " << Charge << '\n'; } //Modifier---------------------------------------------- void MaterialElement::place(Point &P) { Position = P; } void MaterialElement::place(double x, double y, double z) { Position.place(x, y, z); } void MaterialElement::setMass(double m) { Mass = m; } void MaterialElement::setCharge(double c) { Charge = c; } void MaterialElement::addExternalAction(Vect MechanicalAction) { ExternalActions.push_back(MechanicalAction); } //Simulation tool------------------------------------- void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt { updateSpeedandPosition(dt); } Vect MaterialElement::Acceleration() { Calculator C; return C.acceleration(ExternalActions,Mass); } void MaterialElement::updateSpeedandPosition(double dt) { Calculator C; Position = C.Position(C.acceleration(ExternalActions, Mass), Velocity, Position, dt); Velocity = C.Velocity(C.acceleration(ExternalActions, Mass), Velocity, dt); } // ------------------- Material Point ---------------- MaterialPoint::MaterialPoint() {} MaterialPoint::~MaterialPoint() {} <|endoftext|>
<commit_before>//-------------------------------------------------------------------------------------- // File: SpriteFontTest.cpp // // Developer unit test for DirectXTK SpriteFont // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #include "SpriteFont.h" #include "DirectXColors.h" #include "ScreenGrab.h" using namespace DirectX; std::unique_ptr<SpriteBatch> g_spriteBatch; #pragma warning(push) #pragma warning(disable : 4005) #include <wincodec.h> #pragma warning(pop) LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CLOSE: DestroyWindow(hwnd); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; case WM_KEYDOWN: switch( wParam ) { case VK_LEFT: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE270 ); break; case VK_RIGHT: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE90 ); break; case VK_UP: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_IDENTITY ); break; case VK_DOWN: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE180 ); break; } return 0; default: return DefWindowProc(hwnd, msg, wParam, lParam); } } int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR, _In_ int nCmdShow ) { HRESULT hr; wchar_t *const className = L"TestWindowClass"; WNDCLASSEX wndClass = { 0 }; wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.lpfnWndProc = WndProc; wndClass.hInstance = hInstance; wndClass.lpszClassName = className; wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); RegisterClassEx(&wndClass); UINT width = 1024; UINT height = 768; HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, className, L"Test Window", WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); RECT client; GetClientRect(hwnd, &client); ID3D11Device* device; ID3D11DeviceContext* context; IDXGISwapChain* swapChain; ID3D11Texture2D* backBufferTexture; ID3D11RenderTargetView* backBuffer; ID3D11RasterizerState* scissorState; DXGI_SWAP_CHAIN_DESC swapChainDesc = { 0 }; swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = client.right; swapChainDesc.BufferDesc.Height = client.bottom; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_BACK_BUFFER; swapChainDesc.OutputWindow = hwnd; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.Windowed = TRUE; D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_10_0; DWORD d3dFlags = 0; #ifdef _DEBUG d3dFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif if (FAILED(hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, d3dFlags, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &context))) return 1; if (FAILED(hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBufferTexture))) return 1; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc = { DXGI_FORMAT_UNKNOWN, D3D11_RTV_DIMENSION_TEXTURE2D }; if (FAILED(hr = device->CreateRenderTargetView(backBufferTexture, &renderTargetViewDesc, &backBuffer))) return 1; g_spriteBatch.reset( new SpriteBatch(context) ); SpriteFont comicFont(device, L"comic.spritefont"); SpriteFont italicFont(device, L"italic.spritefont"); SpriteFont scriptFont(device, L"script.spritefont"); SpriteFont nonproportionalFont(device, L"nonproportional.spritefont"); SpriteFont multicoloredFont(device, L"multicolored.spritefont"); SpriteFont japaneseFont(device, L"japanese.spritefont"); SpriteFont ctrlFont(device, L"xboxController.spritefont"); SpriteFont consolasFont(device, L"consolas.spritefont"); comicFont.SetDefaultCharacter('-'); bool quit = false; D3D11_VIEWPORT vp = { 0, 0, (float)client.right, (float)client.bottom, 0, 1 }; context->RSSetViewports(1, &vp); context->OMSetRenderTargets(1, &backBuffer, NULL); CD3D11_RASTERIZER_DESC rsDesc(D3D11_FILL_SOLID, D3D11_CULL_BACK, FALSE, 0, 0.f, 0.f, TRUE, TRUE, TRUE, FALSE); if (FAILED(device->CreateRasterizerState(&rsDesc, &scissorState))) return 1; LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); LARGE_INTEGER start; QueryPerformanceCounter(&start); size_t frame = 0; while (!quit) { MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) quit = true; TranslateMessage(&msg); DispatchMessage(&msg); } LARGE_INTEGER counter; QueryPerformanceCounter(&counter); float time = 60 * (float)(counter.QuadPart - start.QuadPart) / (float)freq.QuadPart; context->ClearRenderTargetView(backBuffer, Colors::CornflowerBlue); g_spriteBatch->Begin(); comicFont.DrawString(g_spriteBatch.get(), L"Hello, world!", XMFLOAT2(0, 0)); italicFont.DrawString(g_spriteBatch.get(), L"This text is in italics.\nIs it well spaced?", XMFLOAT2(220, 0)); scriptFont.DrawString(g_spriteBatch.get(), L"Script font, yo...", XMFLOAT2(0, 50)); SpriteEffects flip = (SpriteEffects)((int)(time / 100) & 3); multicoloredFont.DrawString(g_spriteBatch.get(), L"OMG it's full of stars!", XMFLOAT2(610, 130), Colors::White, XM_PIDIV2, XMFLOAT2(0, 0), 1, flip); comicFont.DrawString(g_spriteBatch.get(), L"This is a larger block\nof text using a\nfont scaled to a\nsmaller size.\nSome c\x1234ha\x1543rac\x2453te\x1634r\x1563s are not in the font, but should show up as hyphens.", XMFLOAT2(10, 90), Colors::Black, 0, XMFLOAT2(0, 0), 0.5f); wchar_t tmp[256]; swprintf_s(tmp, L"%Iu frames", frame ); nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(201, 130), Colors::Black); nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 131), Colors::Black); nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 130), Colors::Red); float scale = sin(time / 100) + 1; auto spinText = L"Spinning\nlike a cat"; auto size = comicFont.MeasureString(spinText); comicFont.DrawString(g_spriteBatch.get(), spinText, XMVectorSet(150, 350, 0, 0), Colors::Blue, time / 60, size / 2, scale); auto mirrorText = L"It's a\nmirror..."; auto mirrorSize = comicFont.MeasureString(mirrorText); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Black, 0, mirrorSize * XMVectorSet(0, 1, 0, 0), 1, SpriteEffects_None); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(1, 1, 0, 0), 1, SpriteEffects_FlipHorizontally); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(0, 0, 0, 0), 1, SpriteEffects_FlipVertically); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::DarkGray, 0, mirrorSize * XMVectorSet(1, 0, 0, 0), 1, SpriteEffects_FlipBoth); japaneseFont.DrawString(g_spriteBatch.get(), L"\x79C1\x306F\x65E5\x672C\x8A9E\x304C\x8A71\x305B\x306A\x3044\x306E\x3067\x3001\n\x79C1\x306F\x3053\x308C\x304C\x4F55\x3092\x610F\x5473\x3059\x308B\x306E\x304B\x308F\x304B\x308A\x307E\x305B\x3093", XMFLOAT2(10, 512)); { char ascii[256] = {0}; int i = 0; for (size_t j = 32; j < 256; ++j) { if (j == L'\n' || j == L'\r' || j == L'\t') continue; if (j > 0 && (j % 128) == 0) { ascii[i++] = L'\n'; ascii[i++] = L'\n'; } ascii[i++] = static_cast<char>(j + 1); } wchar_t unicode[256] = { 0 }; if (!MultiByteToWideChar(437, MB_PRECOMPOSED, ascii, i, unicode, 256)) wcscpy_s(unicode, L"<ERROR!>\n"); consolasFont.DrawString(g_spriteBatch.get(), unicode, XMFLOAT2(10, 600), Colors::Cyan); } ctrlFont.DrawString(g_spriteBatch.get(), L" !\"\n#$%\n&'()\n*+,-", XMFLOAT2(650, 130), Colors::White, 0.f, XMFLOAT2(0.f, 0.f), 0.5f); UINT w, h; switch( g_spriteBatch->GetRotation() ) { case DXGI_MODE_ROTATION_ROTATE90: case DXGI_MODE_ROTATION_ROTATE270: w = height; h = width; break; default: w = width; h = height; break; } for( UINT x = 0; x < w; x += 100 ) { swprintf_s( tmp, L"%u\n", x ); nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float(x), float( h - 100 ) ), Colors::Yellow ); } for( UINT y = 0; y < h; y += 100 ) { swprintf_s( tmp, L"%u\n", y ); nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float( w - 100 ), float(y) ), Colors::Red ); } g_spriteBatch->End(); g_spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, scissorState, [&]() { CD3D11_RECT r(640, 20, 740, 38); context->RSSetScissorRects(1, &r); }); comicFont.DrawString(g_spriteBatch.get(), L"Clipping!", XMFLOAT2(640, 0), Colors::DarkGreen); g_spriteBatch->End(); swapChain->Present(1, 0); ++frame; if ( frame == 10 ) { ID3D11Texture2D* backBufferTex = nullptr; hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTex); if ( SUCCEEDED(hr) ) { hr = SaveWICTextureToFile( context, backBufferTex, GUID_ContainerFormatBmp, L"SCREENSHOT.BMP" ); hr = SaveDDSTextureToFile( context, backBufferTex, L"SCREENSHOT.DDS" ); backBufferTex->Release(); } } } g_spriteBatch.reset(); scissorState->Release(); backBuffer->Release(); backBufferTexture->Release(); swapChain->Release(); context->Release(); device->Release(); return 0; } <commit_msg>Updated SpriteFontTest<commit_after>//-------------------------------------------------------------------------------------- // File: SpriteFontTest.cpp // // Developer unit test for DirectXTK SpriteFont // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #include "SpriteFont.h" #include "DirectXColors.h" #include "ScreenGrab.h" #include <wrl/client.h> using Microsoft::WRL::ComPtr; using namespace DirectX; std::unique_ptr<SpriteBatch> g_spriteBatch; #pragma warning(push) #pragma warning(disable : 4005) #include <wincodec.h> #pragma warning(pop) LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CLOSE: DestroyWindow(hwnd); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; case WM_KEYDOWN: switch( wParam ) { case VK_LEFT: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE270 ); break; case VK_RIGHT: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE90 ); break; case VK_UP: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_IDENTITY ); break; case VK_DOWN: if ( g_spriteBatch ) g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE180 ); break; } return 0; default: return DefWindowProc(hwnd, msg, wParam, lParam); } } int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR, _In_ int nCmdShow ) { HRESULT hr; wchar_t *const className = L"TestWindowClass"; WNDCLASSEX wndClass = { 0 }; wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.lpfnWndProc = WndProc; wndClass.hInstance = hInstance; wndClass.lpszClassName = className; wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); RegisterClassEx(&wndClass); UINT width = 1024; UINT height = 768; HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, className, L"Test Window", WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); RECT client; GetClientRect(hwnd, &client); ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; ComPtr<IDXGISwapChain> swapChain; ComPtr<ID3D11Texture2D> backBufferTexture; ComPtr<ID3D11RenderTargetView> backBuffer; ComPtr<ID3D11RasterizerState> scissorState; DXGI_SWAP_CHAIN_DESC swapChainDesc = { 0 }; swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = client.right; swapChainDesc.BufferDesc.Height = client.bottom; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_BACK_BUFFER; swapChainDesc.OutputWindow = hwnd; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.Windowed = TRUE; D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_10_0; DWORD d3dFlags = 0; #ifdef _DEBUG d3dFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif if (FAILED(hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, d3dFlags, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &context))) return 1; if (FAILED(hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBufferTexture))) return 1; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc = { DXGI_FORMAT_UNKNOWN, D3D11_RTV_DIMENSION_TEXTURE2D }; if (FAILED(hr = device->CreateRenderTargetView(backBufferTexture.Get(), &renderTargetViewDesc, &backBuffer))) return 1; g_spriteBatch.reset( new SpriteBatch(context.Get()) ); SpriteFont comicFont(device.Get(), L"comic.spritefont"); SpriteFont italicFont(device.Get(), L"italic.spritefont"); SpriteFont scriptFont(device.Get(), L"script.spritefont"); SpriteFont nonproportionalFont(device.Get(), L"nonproportional.spritefont"); SpriteFont multicoloredFont(device.Get(), L"multicolored.spritefont"); SpriteFont japaneseFont(device.Get(), L"japanese.spritefont"); SpriteFont ctrlFont(device.Get(), L"xboxController.spritefont"); SpriteFont consolasFont(device.Get(), L"consolas.spritefont"); if ( comicFont.GetDefaultCharacter() != 0 ) { MessageBox( hwnd, L"GetDefaultCharacter failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } // ContainsCharacter tests if ( comicFont.ContainsCharacter( 27 ) || !comicFont.ContainsCharacter( '-' ) ) { MessageBox( hwnd, L"ContainsCharacter failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } // FindGlyph/GetSpriteSheet tests { auto g = comicFont.FindGlyph( '-' ); if ( g->Character != '-' || g->XOffset != 6 || g->YOffset != 24 ) { MessageBox( hwnd, L"FindGlyph failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } ComPtr<ID3D11ShaderResourceView> sheet; comicFont.GetSpriteSheet( sheet.GetAddressOf() ); if ( !sheet ) { MessageBox( hwnd, L"GetSpriteSheet failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } } // DefaultCharacter tests comicFont.SetDefaultCharacter('-'); if ( comicFont.GetDefaultCharacter() != '-' ) { MessageBox( hwnd, L"Get/SetDefaultCharacter failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } // Linespacing tests float s=ctrlFont.GetLineSpacing(); if ( s != 186.f ) { MessageBox( hwnd, L"GetLineSpacing failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } ctrlFont.SetLineSpacing(256.f); s=ctrlFont.GetLineSpacing(); if ( s != 256.f ) { MessageBox( hwnd, L"Get/SetLineSpacing failed", L"SpriteFontTest", MB_OK | MB_ICONERROR ); } ctrlFont.SetLineSpacing(186.f); bool quit = false; D3D11_VIEWPORT vp = { 0, 0, (float)client.right, (float)client.bottom, 0, 1 }; context->RSSetViewports(1, &vp); context->OMSetRenderTargets(1, backBuffer.GetAddressOf(), NULL); CD3D11_RASTERIZER_DESC rsDesc(D3D11_FILL_SOLID, D3D11_CULL_BACK, FALSE, 0, 0.f, 0.f, TRUE, TRUE, TRUE, FALSE); if (FAILED(device->CreateRasterizerState(&rsDesc, &scissorState))) return 1; LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); LARGE_INTEGER start; QueryPerformanceCounter(&start); size_t frame = 0; while (!quit) { MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) quit = true; TranslateMessage(&msg); DispatchMessage(&msg); } LARGE_INTEGER counter; QueryPerformanceCounter(&counter); float time = 60 * (float)(counter.QuadPart - start.QuadPart) / (float)freq.QuadPart; context->ClearRenderTargetView(backBuffer.Get(), Colors::CornflowerBlue); g_spriteBatch->Begin(); comicFont.DrawString(g_spriteBatch.get(), L"Hello, world!", XMFLOAT2(0, 0)); italicFont.DrawString(g_spriteBatch.get(), L"This text is in italics.\nIs it well spaced?", XMFLOAT2(220, 0)); scriptFont.DrawString(g_spriteBatch.get(), L"Script font, yo...", XMFLOAT2(0, 50)); SpriteEffects flip = (SpriteEffects)((int)(time / 100) & 3); multicoloredFont.DrawString(g_spriteBatch.get(), L"OMG it's full of stars!", XMFLOAT2(610, 130), Colors::White, XM_PIDIV2, XMFLOAT2(0, 0), 1, flip); comicFont.DrawString(g_spriteBatch.get(), L"This is a larger block\nof text using a\nfont scaled to a\nsmaller size.\nSome c\x1234ha\x1543rac\x2453te\x1634r\x1563s are not in the font, but should show up as hyphens.", XMFLOAT2(10, 90), Colors::Black, 0, XMFLOAT2(0, 0), 0.5f); wchar_t tmp[256]; swprintf_s(tmp, L"%Iu frames", frame ); nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(201, 130), Colors::Black); nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 131), Colors::Black); nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 130), Colors::Red); float scale = sin(time / 100) + 1; auto spinText = L"Spinning\nlike a cat"; auto size = comicFont.MeasureString(spinText); comicFont.DrawString(g_spriteBatch.get(), spinText, XMVectorSet(150, 350, 0, 0), Colors::Blue, time / 60, size / 2, scale); auto mirrorText = L"It's a\nmirror..."; auto mirrorSize = comicFont.MeasureString(mirrorText); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Black, 0, mirrorSize * XMVectorSet(0, 1, 0, 0), 1, SpriteEffects_None); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(1, 1, 0, 0), 1, SpriteEffects_FlipHorizontally); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(0, 0, 0, 0), 1, SpriteEffects_FlipVertically); comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::DarkGray, 0, mirrorSize * XMVectorSet(1, 0, 0, 0), 1, SpriteEffects_FlipBoth); japaneseFont.DrawString(g_spriteBatch.get(), L"\x79C1\x306F\x65E5\x672C\x8A9E\x304C\x8A71\x305B\x306A\x3044\x306E\x3067\x3001\n\x79C1\x306F\x3053\x308C\x304C\x4F55\x3092\x610F\x5473\x3059\x308B\x306E\x304B\x308F\x304B\x308A\x307E\x305B\x3093", XMFLOAT2(10, 512)); { char ascii[256] = {0}; int i = 0; for (size_t j = 32; j < 256; ++j) { if (j == L'\n' || j == L'\r' || j == L'\t') continue; if (j > 0 && (j % 128) == 0) { ascii[i++] = L'\n'; ascii[i++] = L'\n'; } ascii[i++] = static_cast<char>(j + 1); } wchar_t unicode[256] = { 0 }; if (!MultiByteToWideChar(437, MB_PRECOMPOSED, ascii, i, unicode, 256)) wcscpy_s(unicode, L"<ERROR!>\n"); consolasFont.DrawString(g_spriteBatch.get(), unicode, XMFLOAT2(10, 600), Colors::Cyan); } ctrlFont.DrawString(g_spriteBatch.get(), L" !\"\n#$%\n&'()\n*+,-", XMFLOAT2(650, 130), Colors::White, 0.f, XMFLOAT2(0.f, 0.f), 0.5f); UINT w, h; switch( g_spriteBatch->GetRotation() ) { case DXGI_MODE_ROTATION_ROTATE90: case DXGI_MODE_ROTATION_ROTATE270: w = height; h = width; break; default: w = width; h = height; break; } for( UINT x = 0; x < w; x += 100 ) { swprintf_s( tmp, L"%u\n", x ); nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float(x), float( h - 100 ) ), Colors::Yellow ); } for( UINT y = 0; y < h; y += 100 ) { swprintf_s( tmp, L"%u\n", y ); nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float( w - 100 ), float(y) ), Colors::Red ); } g_spriteBatch->End(); g_spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, scissorState.Get(), [&]() { CD3D11_RECT r(640, 20, 740, 38); context->RSSetScissorRects(1, &r); }); comicFont.DrawString(g_spriteBatch.get(), L"Clipping!", XMFLOAT2(640, 0), Colors::DarkGreen); g_spriteBatch->End(); swapChain->Present(1, 0); ++frame; if ( frame == 10 ) { ComPtr<ID3D11Texture2D> backBufferTex; hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTex); if ( SUCCEEDED(hr) ) { hr = SaveWICTextureToFile( context.Get(), backBufferTex.Get(), GUID_ContainerFormatBmp, L"SCREENSHOT.BMP" ); hr = SaveDDSTextureToFile( context.Get(), backBufferTex.Get(), L"SCREENSHOT.DDS" ); } } } g_spriteBatch.reset(); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. // // // C++ Implementation: $MODULE$ // // Description: // // // Author: sven <sven@ares>, (C) 2003 // // Copyright: See COPYING file that comes with this distribution // // #include "copasi.h" #include "CMetabNameInterface.h" #include "CModel.h" #include "CChemEqParser.h" #include "report/CCopasiContainer.h" #include "report/CKeyFactory.h" #include "copasi/report/CCopasiRootContainer.h" CMetabNameInterface::~CMetabNameInterface() {} std::string CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key, const bool & quoted) { CMetab * metab = dynamic_cast< CMetab * >(CCopasiRootContainer::getKeyFactory()->get(key)); if (metab) return getDisplayName(model, *metab, quoted); else return ""; } std::string CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab, const bool & quoted) { return getDisplayName(model, metab.getObjectName(), metab.getCompartment()->getObjectName(), quoted); } std::string CMetabNameInterface::getDisplayName(const CModel* model, const std::string & metabolite, const std::string & compartment, const bool & quoted) { std::string DefaultCompartment; if (model->getCompartments().size() == 0) DefaultCompartment = "compartment"; else DefaultCompartment = model->getCompartments()[0]->getObjectName(); std::string Metabolite = quoted ? quote(metabolite, "{}") : metabolite; if (quoted && isNumber(Metabolite)) Metabolite = "\"" + Metabolite + "\""; if ((CMetabNameInterface::doesExist(model, metabolite, compartment) && CMetabNameInterface::isUnique(model, metabolite)) || (!CMetabNameInterface::doesExist(model, metabolite, "") && compartment == DefaultCompartment)) return Metabolite; std::string Compartment = quoted ? quote(compartment, "{}") : compartment; if (quoted && isNumber(Compartment)) Compartment = "\"" + Compartment + "\""; return Metabolite + '{' + Compartment + '}'; } std::string CMetabNameInterface::getMetaboliteKey(const CModel* model, const std::string & metabolite, const std::string & compartment) { CMetab * metab = getMetabolite(model, metabolite, compartment); if (metab) return metab->getKey(); else return ""; } CMetab * CMetabNameInterface::getMetabolite(const CModel* model, const std::string & metabolite, const std::string & compartment) { size_t Index; if (compartment != "") { Index = model->getCompartments().getIndex(compartment); if (Index != C_INVALID_INDEX) { CCompartment *pCompartment = model->getCompartments()[Index]; Index = pCompartment->getMetabolites().getIndex(metabolite); if (Index != C_INVALID_INDEX) return pCompartment->getMetabolites()[Index]; } return NULL; } Index = model->findMetabByName(metabolite); if (Index != C_INVALID_INDEX) return model->getMetabolites()[Index]; return NULL; } bool CMetabNameInterface::isUnique(const CModel* model, const std::string & name) { bool unique = true; size_t i; const CCopasiVector< CMetab > & metabs = model->getMetabolites(); std::string metabName; for (i = 0; i < metabs.size(); i++) { metabName = metabs[i]->getObjectName(); if (metabName == name) { if (unique) unique = false; else return false; //return true } } return true; //return unique; } bool CMetabNameInterface::doesExist(const CModel* model, const std::string & metabolite, const std::string & compartment) { if (compartment != "") { size_t Index = model->getCompartments().getIndex(compartment); if (Index == C_INVALID_INDEX) return false; Index = model->getCompartments()[Index]->getMetabolites().getIndex(metabolite); return (Index != C_INVALID_INDEX); } else return (model->findMetabByName(metabolite) != C_INVALID_INDEX); } // static std::pair< std::string, std::string > CMetabNameInterface::splitDisplayName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(quote(name) + " ->"); CChemEqParser Parser(&buffer); std::pair< std::string, std::string > Result; if (Parser.yyparse() != 0) { Result.first = ""; Result.second = ""; } else { Result.first = Parser.getSubstrateNames()[0]; Result.second = Parser.getSubstrateCompartments()[0]; } return Result; } // static std::string CMetabNameInterface::unQuote(const std::string & displayName) { // parse the description into a linked node tree std::stringstream buffer(displayName + " ->"); CChemEqParser Parser(&buffer); std::pair< std::string, std::string > Names; if (Parser.yyparse() != 0) { Names.first = ""; Names.second = ""; } else { Names.first = Parser.getSubstrateNames()[0]; Names.second = Parser.getSubstrateCompartments()[0]; } std::string Name = Names.first; if (Names.second != "") { Name += "{" + Names.second + "}"; } return Name; } #ifdef XXXX std::string CMetabNameInterface::extractCompartmentName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(name); buffer << " ->"; CChemEqParser Parser(&buffer); if (Parser.yyparse() != 0) return ""; return Parser.getSubstrateCompartments()[0]; } std::string CMetabNameInterface::extractMetabName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(name); buffer << " ->"; CChemEqParser Parser(&buffer); if (Parser.yyparse() != 0) return ""; return Parser.getSubstrateNames()[0]; } bool CMetabNameInterface::isValidMetabDisplayName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(name); buffer << " ->"; CChemEqParser Parser(&buffer); return (Parser.yyparse() == 0); } #endif // XXXX <commit_msg>Fixed problem occurring when unquoting a metabolite name which requires quotes has already been unquoted before.<commit_after>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. // // // C++ Implementation: $MODULE$ // // Description: // // // Author: sven <sven@ares>, (C) 2003 // // Copyright: See COPYING file that comes with this distribution // // #include "copasi.h" #include "CMetabNameInterface.h" #include "CModel.h" #include "CChemEqParser.h" #include "report/CCopasiContainer.h" #include "report/CKeyFactory.h" #include "copasi/report/CCopasiRootContainer.h" CMetabNameInterface::~CMetabNameInterface() {} std::string CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key, const bool & quoted) { CMetab * metab = dynamic_cast< CMetab * >(CCopasiRootContainer::getKeyFactory()->get(key)); if (metab) return getDisplayName(model, *metab, quoted); else return ""; } std::string CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab, const bool & quoted) { return getDisplayName(model, metab.getObjectName(), metab.getCompartment()->getObjectName(), quoted); } std::string CMetabNameInterface::getDisplayName(const CModel* model, const std::string & metabolite, const std::string & compartment, const bool & quoted) { std::string DefaultCompartment; if (model->getCompartments().size() == 0) DefaultCompartment = "compartment"; else DefaultCompartment = model->getCompartments()[0]->getObjectName(); std::string Metabolite = quoted ? quote(metabolite, "{}") : metabolite; if (quoted && isNumber(Metabolite)) Metabolite = "\"" + Metabolite + "\""; if ((CMetabNameInterface::doesExist(model, metabolite, compartment) && CMetabNameInterface::isUnique(model, metabolite)) || (!CMetabNameInterface::doesExist(model, metabolite, "") && compartment == DefaultCompartment)) return Metabolite; std::string Compartment = quoted ? quote(compartment, "{}") : compartment; if (quoted && isNumber(Compartment)) Compartment = "\"" + Compartment + "\""; return Metabolite + '{' + Compartment + '}'; } std::string CMetabNameInterface::getMetaboliteKey(const CModel* model, const std::string & metabolite, const std::string & compartment) { CMetab * metab = getMetabolite(model, metabolite, compartment); if (metab) return metab->getKey(); else return ""; } CMetab * CMetabNameInterface::getMetabolite(const CModel* model, const std::string & metabolite, const std::string & compartment) { size_t Index; if (compartment != "") { Index = model->getCompartments().getIndex(compartment); if (Index != C_INVALID_INDEX) { CCompartment *pCompartment = model->getCompartments()[Index]; Index = pCompartment->getMetabolites().getIndex(metabolite); if (Index != C_INVALID_INDEX) return pCompartment->getMetabolites()[Index]; } return NULL; } Index = model->findMetabByName(metabolite); if (Index != C_INVALID_INDEX) return model->getMetabolites()[Index]; return NULL; } bool CMetabNameInterface::isUnique(const CModel* model, const std::string & name) { bool unique = true; size_t i; const CCopasiVector< CMetab > & metabs = model->getMetabolites(); std::string metabName; for (i = 0; i < metabs.size(); i++) { metabName = metabs[i]->getObjectName(); if (metabName == name) { if (unique) unique = false; else return false; //return true } } return true; //return unique; } bool CMetabNameInterface::doesExist(const CModel* model, const std::string & metabolite, const std::string & compartment) { if (compartment != "") { size_t Index = model->getCompartments().getIndex(compartment); if (Index == C_INVALID_INDEX) return false; Index = model->getCompartments()[Index]->getMetabolites().getIndex(metabolite); return (Index != C_INVALID_INDEX); } else return (model->findMetabByName(metabolite) != C_INVALID_INDEX); } // static std::pair< std::string, std::string > CMetabNameInterface::splitDisplayName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(quote(name) + " ->"); CChemEqParser Parser(&buffer); std::pair< std::string, std::string > Result; if (Parser.yyparse() != 0) { Result.first = ""; Result.second = ""; } else { Result.first = Parser.getSubstrateNames()[0]; Result.second = Parser.getSubstrateCompartments()[0]; } return Result; } // static std::string CMetabNameInterface::unQuote(const std::string & displayName) { // parse the description into a linked node tree std::stringstream buffer(displayName + " ->"); CChemEqParser Parser(&buffer); std::pair< std::string, std::string > Names; if (Parser.yyparse() != 0) { Names.first = displayName; Names.second = ""; } else { Names.first = Parser.getSubstrateNames()[0]; Names.second = Parser.getSubstrateCompartments()[0]; } std::string Name = Names.first; if (Names.second != "") { Name += "{" + Names.second + "}"; } return Name; } #ifdef XXXX std::string CMetabNameInterface::extractCompartmentName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(name); buffer << " ->"; CChemEqParser Parser(&buffer); if (Parser.yyparse() != 0) return ""; return Parser.getSubstrateCompartments()[0]; } std::string CMetabNameInterface::extractMetabName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(name); buffer << " ->"; CChemEqParser Parser(&buffer); if (Parser.yyparse() != 0) return ""; return Parser.getSubstrateNames()[0]; } bool CMetabNameInterface::isValidMetabDisplayName(const std::string & name) { // parse the description into a linked node tree std::stringstream buffer(name); buffer << " ->"; CChemEqParser Parser(&buffer); return (Parser.yyparse() == 0); } #endif // XXXX <|endoftext|>
<commit_before>#include "include/vkalloc.h" #include <vector> #include <unordered_map> namespace vka { struct Page { VkDeviceMemory deviceMemory = VK_NULL_HANDLE; Node* head = nullptr; }; struct Node { Node* next = nullptr; uint64_t offset = 0; uint64_t size = 0; }; struct PageMapping { uint32_t heapIndex; uint32_t pageIndex; }; VkPhysicalDevice physicalDevice; VkDevice device; VkPhysicalDeviceMemoryProperties properties; VkAllocationCallbacks* callbacks; std::unordered_map<VkDeviceMemory, PageMapping> pageMap; //caches index into one of the vector<Page> heaps std::vector<Page> heaps[32]; //32 possible heaps } void vkaInit(VkPhysicalDevice physicalDevice, VkDevice device, VkAllocationCallbacks* allocator){ vka::physicalDevice = physicalDevice; vka::device = device; vka::callbacks = allocator; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &vka::properties); } using namespace vka; static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements); static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements); static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements); static void Split(Node* current, Node** last, uint64_t start, uint64_t size); static void Free(VkAllocation allocation, Page& page); static void Merge(VkAllocation allocation, Node* current); void vkaTerminate(){ pageMap.clear(); for (size_t i = 0; i < 32; i++) { for (size_t j = 0; j < heaps[i].size(); j++) { Node* current = heaps[i][j].head; while (current){ Node* next = current->next; delete current; current = next; } } heaps[i].clear(); } } VkAllocation vkAllocFlag(VkMemoryRequirements requirements, VkMemoryPropertyFlags flags) { for (size_t i = 0; i < properties.memoryTypeCount; i++) { if ((requirements.memoryTypeBits & (1 << i)) && properties.memoryTypes[i].propertyFlags == flags) { std::vector<Page> &heap = heaps[i]; VkAllocation result = AttemptAlloc(heap, i, requirements); if (result.deviceMemory != VK_NULL_HANDLE) { return result; } } } return {}; } void vkFree(VkAllocation allocation){ if (allocation.deviceMemory == VK_NULL_HANDLE) return; PageMapping& mapping = pageMap[allocation.deviceMemory]; Page& page = heaps[mapping.heapIndex][mapping.pageIndex]; Free(allocation, page); } VkAllocation vkAlloc(VkMemoryRequirements requirements){ return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } VkAllocation vkAllocHost(VkMemoryRequirements requirements){ return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) { //attempt to allocate from existing pages for (size_t i = 0; i < heap.size(); i++) { Page& page = heap[i]; VkAllocation result = AttemptAlloc(page, requirements); if (result.deviceMemory != VK_NULL_HANDLE) { return result; } } //attempt to allocate from new page Page* newPage = AllocNewPage(heap, heapIndex, requirements); if (newPage) { VkAllocation result = AttemptAlloc(*newPage, requirements); if (result.deviceMemory != VK_NULL_HANDLE) { return result; } } //give up return {}; } static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements) { Node* current = page.head; Node** last = &page.head; while (current) { uint64_t start = current->offset; uint64_t available = current->size; uint64_t unalign = (start % requirements.alignment); uint64_t align; if (unalign == 0) { align = 0; } else { align = requirements.alignment - unalign; } start += align; available -= align; if (available >= requirements.size) { Split(current, last, start, requirements.size); return {page.deviceMemory, start, requirements.size}; } last = &(current->next); current = current->next; } return {}; } static void Split(Node* current, Node** last, uint64_t start, uint64_t size) { uint64_t startSpace = start - current->offset; uint64_t endSpace = current->size - (start + size); if (startSpace == 0 && endSpace == 0) { *last = current->next; delete current; } else if (startSpace == 0 && endSpace > 0) { current->offset = start + size; current->size = endSpace; } else if (startSpace > 0 && endSpace == 0) { current->size = startSpace; } else { //startSpace > 0 && endSpace > 0 Node* newNode = new Node; newNode->next = current->next; newNode->offset = start + size; newNode->size = endSpace; current->next = newNode; current->size = startSpace; } } static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) { uint64_t allocSize = VKA_ALLOC_SIZE; if (requirements.size > allocSize) { allocSize = requirements.size; } VkMemoryAllocateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; info.allocationSize = allocSize; info.memoryTypeIndex = heapIndex; VkDeviceMemory memory; VkResult result = vkAllocateMemory(device, &info, callbacks, &memory); if (result == VK_SUCCESS){ Page page = {}; page.deviceMemory = memory; Node* node = new Node; node->size = allocSize; page.head = node; heap.emplace_back(page); pageMap[memory] = {heapIndex, static_cast<uint32_t>(heap.size() - 1)}; return &(heap[heap.size() - 1]); } else { //TODO: add way for user to check the error return nullptr; } } static void Free(VkAllocation allocation, Page& page) { Node* current = page.head; while (current) { if (allocation.offset > current->offset && allocation.offset < current->next->offset) { Merge(allocation, current); return; } } } static void Merge(VkAllocation allocation, Node* current) { if (allocation.offset == current->offset + current->size) { current->size += allocation.size; } else { Node* newNode = new Node; newNode->next = current->next, newNode->offset = allocation.offset, newNode->size = allocation.size; current = newNode; } Node* next = current->next; if (next->offset == current->offset + current->size) { current->size += next->size; current->next = next->next; delete next; } }<commit_msg>Remove vka::physicalDevice<commit_after>#include "include/vkalloc.h" #include <vector> #include <unordered_map> namespace vka { struct Page { VkDeviceMemory deviceMemory = VK_NULL_HANDLE; Node* head = nullptr; }; struct Node { Node* next = nullptr; uint64_t offset = 0; uint64_t size = 0; }; struct PageMapping { uint32_t heapIndex; uint32_t pageIndex; }; VkDevice device; VkPhysicalDeviceMemoryProperties properties; VkAllocationCallbacks* callbacks; std::unordered_map<VkDeviceMemory, PageMapping> pageMap; //caches index into one of the vector<Page> heaps std::vector<Page> heaps[32]; //32 possible heaps } void vkaInit(VkPhysicalDevice physicalDevice, VkDevice device, VkAllocationCallbacks* allocator){ vka::device = device; vka::callbacks = allocator; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &vka::properties); } using namespace vka; static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements); static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements); static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements); static void Split(Node* current, Node** last, uint64_t start, uint64_t size); static void Free(VkAllocation allocation, Page& page); static void Merge(VkAllocation allocation, Node* current); void vkaTerminate(){ pageMap.clear(); for (size_t i = 0; i < 32; i++) { for (size_t j = 0; j < heaps[i].size(); j++) { Node* current = heaps[i][j].head; while (current){ Node* next = current->next; delete current; current = next; } } heaps[i].clear(); } } VkAllocation vkAllocFlag(VkMemoryRequirements requirements, VkMemoryPropertyFlags flags) { for (size_t i = 0; i < properties.memoryTypeCount; i++) { if ((requirements.memoryTypeBits & (1 << i)) && properties.memoryTypes[i].propertyFlags == flags) { std::vector<Page> &heap = heaps[i]; VkAllocation result = AttemptAlloc(heap, i, requirements); if (result.deviceMemory != VK_NULL_HANDLE) { return result; } } } return {}; } void vkFree(VkAllocation allocation){ if (allocation.deviceMemory == VK_NULL_HANDLE) return; PageMapping& mapping = pageMap[allocation.deviceMemory]; Page& page = heaps[mapping.heapIndex][mapping.pageIndex]; Free(allocation, page); } VkAllocation vkAlloc(VkMemoryRequirements requirements){ return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } VkAllocation vkAllocHost(VkMemoryRequirements requirements){ return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) { //attempt to allocate from existing pages for (size_t i = 0; i < heap.size(); i++) { Page& page = heap[i]; VkAllocation result = AttemptAlloc(page, requirements); if (result.deviceMemory != VK_NULL_HANDLE) { return result; } } //attempt to allocate from new page Page* newPage = AllocNewPage(heap, heapIndex, requirements); if (newPage) { VkAllocation result = AttemptAlloc(*newPage, requirements); if (result.deviceMemory != VK_NULL_HANDLE) { return result; } } //give up return {}; } static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements) { Node* current = page.head; Node** last = &page.head; while (current) { uint64_t start = current->offset; uint64_t available = current->size; uint64_t unalign = (start % requirements.alignment); uint64_t align; if (unalign == 0) { align = 0; } else { align = requirements.alignment - unalign; } start += align; available -= align; if (available >= requirements.size) { Split(current, last, start, requirements.size); return {page.deviceMemory, start, requirements.size}; } last = &(current->next); current = current->next; } return {}; } static void Split(Node* current, Node** last, uint64_t start, uint64_t size) { uint64_t startSpace = start - current->offset; uint64_t endSpace = current->size - (start + size); if (startSpace == 0 && endSpace == 0) { *last = current->next; delete current; } else if (startSpace == 0 && endSpace > 0) { current->offset = start + size; current->size = endSpace; } else if (startSpace > 0 && endSpace == 0) { current->size = startSpace; } else { //startSpace > 0 && endSpace > 0 Node* newNode = new Node; newNode->next = current->next; newNode->offset = start + size; newNode->size = endSpace; current->next = newNode; current->size = startSpace; } } static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) { uint64_t allocSize = VKA_ALLOC_SIZE; if (requirements.size > allocSize) { allocSize = requirements.size; } VkMemoryAllocateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; info.allocationSize = allocSize; info.memoryTypeIndex = heapIndex; VkDeviceMemory memory; VkResult result = vkAllocateMemory(device, &info, callbacks, &memory); if (result == VK_SUCCESS){ Page page = {}; page.deviceMemory = memory; Node* node = new Node; node->size = allocSize; page.head = node; heap.emplace_back(page); pageMap[memory] = {heapIndex, static_cast<uint32_t>(heap.size() - 1)}; return &(heap[heap.size() - 1]); } else { //TODO: add way for user to check the error return nullptr; } } static void Free(VkAllocation allocation, Page& page) { Node* current = page.head; while (current) { if (allocation.offset > current->offset && allocation.offset < current->next->offset) { Merge(allocation, current); return; } } } static void Merge(VkAllocation allocation, Node* current) { if (allocation.offset == current->offset + current->size) { current->size += allocation.size; } else { Node* newNode = new Node; newNode->next = current->next, newNode->offset = allocation.offset, newNode->size = allocation.size; current = newNode; } Node* next = current->next; if (next->offset == current->offset + current->size) { current->size += next->size; current->next = next->next; delete next; } }<|endoftext|>
<commit_before>/* * Written by : BinHong Lee * Last edited : 5/12/2016 */ #include <iostream> #include <string> #include <stack> #include <fstream> #include "Person.cpp" using namespace std; //Declaration of functions void getUser(string); void login(); void adminLogin(); void loggedIn(); void registration(); void editCredentials(); void update(Person); void chgUsername(); void chgPassword(); void chgEmail(); void chgPhoneNo(); void quit(); //Stacks to store the users' personal data stack<Person> users; //Declaration of place holding variables Person currentUser; string username; string password; string password2; string email; string phoneNo; int wrongPass = 0; int main() { //Reading from file to build the database ifstream fin("database.txt"); while (!fin.eof()) { //Reading in line-by-line into the placeholding variables fin >> username >> password >> email >> phoneNo; //Create the Person and push it into the stack Person temp(username, password, email, phoneNo); users.push(temp); } //Pop off the additional data added into the stack due to the empty line users.pop(); getOption: //Display user input options cout << "Please choose one of the following options :" << endl; cout << "Log In - 1" << endl; cout << "Registration - 2" << endl; cout << "Exit - 0" << endl; //Get user input int choice; cin >> choice; //Switch according to user input switch (choice) { case 1: login(); break; case 2: registration(); break; case 0: break; default: //Display error message cout << "Invalid input. Please try again." << endl; goto getOption; } //Saving data into file ofstream fout("database.txt"); //Check if the stack is empty while (!users.empty()) { //Move the data into the files each Person per line fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl; //Pop the Person out of stack after the data is moved users.pop(); } //End the program return 0; } void getUser() { //Duplicate the current stack to be checked through stack<Person> temp = users; //Loop while the temporary stack is not empty while (!temp.empty()) { //Check if the username match the query //If so, set it as the currentUser if (users.top().getName() == username) currentUser = users.top(); //Pop the checked user users.pop(); } //Throw invalid_argument error to be caught if the person is not found throw std::invalid_argument(""); } void login() { //If the user already has 3 fail attempt to login if (wrongPass >= 3) { //Print error message and exit cout << "Too much failed login attempt. The program will now be terminated." << endl; quit(); } try { //Ask for username cout << "Username:"; cin >> username; //Ask for password cout << "Password:"; cin >> password; //Get the user getUser(); } catch (invalid_argument inae) { //Print error message cout << "Invalid username or password. Please try again."; //Increase wrongPass count that indicate the amount of times of invalid //credentials input by the user wrongPass++; login(); } //Check if the password is correct if (!currentUser.checkPassword(password)) { //Print error message cout << "Invalid username or password. Please try again."; //Increase wrongPass count that indicate the amount of times of invalid //credentials input by the user wrongPass++; login(); } //User is successfully logged in loggedIn(); } void registration() { //Initialize boolean bool available; do { try { //Get username cout << "Username: "; cin >> username; //Check if username is already in use //If not, it will throw an invalid_argument error to be caught getUser(); //Print error message cout << "Username unavailable. Please try again." << endl; //Set available as false and continue the loop available = false; //Catch the invalid_argument error thrown by getUser() } catch (invalid_argument inae) { //Set available to true and quit the loop available = true; } } while (available == false); //Print success message cout << "Username is available." << endl; do { //Get password cout << "Password : "; cin >> password; //Confirm password cout << "Confirm password :"; cin >> password2; //Print error message if both password is not the same if (password != password2) cout << "Password unmatched. Please try again."; //Loop until both password input is the same } while (password != password2); //Get email cout << "Email : "; cin >> email; //Get phone number cout << "Phone No. : "; cin >> phoneNo; //Create and push the new 'Person' into stack Person newUser(username, password, email, phoneNo); users.push(newUser); //Print success message cout << "Account is successfully registered." << endl; //Automatically login user currentUser = newUser; loggedIn(); } void loggedIn() { int choice; cout << "Please choose one of the following option :" << endl; cout << "View credentials - 1" << endl; cout << "Edit credentials - 2" << endl; cout << "Exit - 0" << endl; cin >> choice; switch (choice) { case 1: cout << "Username : " << currentUser.getName() << "\nEmail : " << currentUser.getEmail() << "\nPhone No. : " << currentUser.getPhoneNo() << endl; loggedIn(); break; case 2: editCredentials(); loggedIn(); break; case 0: quit(); default: cout << "Invalid option. Please try again." << endl; cout << endl; loggedIn(); } } void editCredentials() { int choice; cout << "Which of the following to edit?" << endl; cout << "Username - 1" << endl; cout << "Password - 2" << endl; cout << "Email - 3" << endl; cout << "Phone No. - 4" << endl; cout << "Exit - 0" << endl; cin >> choice; switch (choice) { case 1: chgUsername(); break; case 2: chgPassword(); break; case 3: chgEmail(); break; case 4: chgPhoneNo(); break; } } void update(Person newUser) { stack<Person> newUsers; while (!users.empty()) { if (users.top().getName() == currentUser.getName()) { cout << "replaced" << endl; newUsers.push(newUser); } else { newUsers.push(users.top()); } users.pop(); } users = newUsers; currentUser = newUser; } void chgUsername() { bool available; Person newUsers; do { available = true; cout << available << endl; cout << "Username : "; cin >> username; stack<Person> temp = users; while (!temp.empty()) { if (temp.top().getName() == username) { cout << "Username unavailable. Please try again." << endl; cout << temp.top().getName() << " " << temp.top().getPhoneNo() << endl; available = false; break; } temp.pop(); } } while (available == false); cout << "Username is available." << endl; Person newPerson(username, currentUser.getPassword(), currentUser.getEmail(), currentUser.getPhoneNo()); update(newPerson); cout << "Username is updated." << endl; } void chgPassword() { cout << "Please input the current password : "; cin >> password; while (!currentUser.checkPassword(password)) { cout << "Wrong password. Please try again." << endl; wrongPass++; cout << "Please input the current password : "; cin >> password; } do { cout << "Please input the new password : "; cin >> password; cout << "Please confirm your new password : "; cin >> password2; } while(password2 != password); currentUser.setPassword(password); update(currentUser); } void chgEmail() { cout << "Please input the new email : "; cin >> email; currentUser.setEmail(email); update(currentUser); } void chgPhoneNo() { cout << "Please input the new phone no. : "; cin >> phoneNo; currentUser.setPhoneNo(phoneNo); update(currentUser); } void quit() { ofstream fout("database.txt"); while (!users.empty()) { fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl; users.pop(); } exit (EXIT_SUCCESS); } <commit_msg>Removed quit()<commit_after>/* * Written by : BinHong Lee * Last edited : 7/7/2016 */ #include <iostream> #include <string> #include <stack> #include <fstream> #include "Person.cpp" using namespace std; //Declaration of functions void getUser(string); void login(); void adminLogin(); void loggedIn(); void registration(); void editCredentials(); void update(Person); void chgUsername(); void chgPassword(); void chgEmail(); void chgPhoneNo(); //void quit(); //Stacks to store the users' personal data stack<Person> users; //Declaration of place holding variables Person currentUser; string username; string password; string password2; string email; string phoneNo; int wrongPass = 0; int main() { //Reading from file to build the database ifstream fin("database.txt"); while (!fin.eof()) { //Reading in line-by-line into the placeholding variables fin >> username >> password >> email >> phoneNo; //Create the Person and push it into the stack Person temp(username, password, email, phoneNo); users.push(temp); } //Pop off the additional data added into the stack due to the empty line users.pop(); getOption: //Display user input options cout << "Please choose one of the following options :" << endl; cout << "Log In - 1" << endl; cout << "Registration - 2" << endl; cout << "Exit - 0" << endl; //Get user input int choice; cin >> choice; //Switch according to user input switch (choice) { case 1: login(); break; case 2: registration(); break; case 0: break; default: //Display error message cout << "Invalid input. Please try again." << endl; goto getOption; } //Saving data into file ofstream fout("database.txt"); //Check if the stack is empty while (!users.empty()) { //Move the data into the files each Person per line fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl; //Pop the Person out of stack after the data is moved users.pop(); } //End the program return 0; } void getUser() { //Duplicate the current stack to be checked through stack<Person> temp = users; //Loop while the temporary stack is not empty while (!temp.empty()) { //Check if the username match the query //If so, set it as the currentUser if (users.top().getName() == username) currentUser = users.top(); //Pop the checked user users.pop(); } //Throw invalid_argument error to be caught if the person is not found throw std::invalid_argument(""); } void login() { //If the user already has 3 fail attempt to login if (wrongPass >= 3) { //Print error message and exit cout << "Too much failed login attempt. The program will now be terminated." << endl; return; } try { //Ask for username cout << "Username:"; cin >> username; //Ask for password cout << "Password:"; cin >> password; //Get the user getUser(); } catch (invalid_argument inae) { //Print error message cout << "Invalid username or password. Please try again."; //Increase wrongPass count that indicate the amount of times of invalid //credentials input by the user wrongPass++; login(); } //Check if the password is correct if (!currentUser.checkPassword(password)) { //Print error message cout << "Invalid username or password. Please try again."; //Increase wrongPass count that indicate the amount of times of invalid //credentials input by the user wrongPass++; login(); } //User is successfully logged in loggedIn(); } void registration() { //Initialize boolean bool available; do { try { //Get username cout << "Username: "; cin >> username; //Check if username is already in use //If not, it will throw an invalid_argument error to be caught getUser(); //Print error message cout << "Username unavailable. Please try again." << endl; //Set available as false and continue the loop available = false; //Catch the invalid_argument error thrown by getUser() } catch (invalid_argument inae) { //Set available to true and quit the loop available = true; } } while (available == false); //Print success message cout << "Username is available." << endl; do { //Get password cout << "Password : "; cin >> password; //Confirm password cout << "Confirm password :"; cin >> password2; //Print error message if both password is not the same if (password != password2) cout << "Password unmatched. Please try again."; //Loop until both password input is the same } while (password != password2); //Get email cout << "Email : "; cin >> email; //Get phone number cout << "Phone No. : "; cin >> phoneNo; //Create and push the new 'Person' into stack Person newUser(username, password, email, phoneNo); users.push(newUser); //Print success message cout << "Account is successfully registered." << endl; //Automatically login user currentUser = newUser; loggedIn(); } void loggedIn() { //Declare space to save user's option int choice; //Print options cout << "Please choose one of the following option :" << endl; cout << "View credentials - 1" << endl; cout << "Edit credentials - 2" << endl; cout << "Exit - 0" << endl; //Get user selection cin >> choice; switch (choice) { case 1: //Print out user credentials cout << "Username : " << currentUser.getName() << "\nEmail : " << currentUser.getEmail() << "\nPhone No. : " << currentUser.getPhoneNo() << endl; //Nested call back into the menu loggedIn(); break; case 2: editCredentials(); //Nested call back into the menu loggedIn(); break; case 0: break; default: cout << "Invalid option. Please try again." << endl; cout << endl; loggedIn(); } } void editCredentials() { int choice; cout << "Which of the following to edit?" << endl; cout << "Username - 1" << endl; cout << "Password - 2" << endl; cout << "Email - 3" << endl; cout << "Phone No. - 4" << endl; cout << "Exit - 0" << endl; cin >> choice; switch (choice) { case 1: chgUsername(); break; case 2: chgPassword(); break; case 3: chgEmail(); break; case 4: chgPhoneNo(); break; } } void update(Person newUser) { stack<Person> newUsers; while (!users.empty()) { if (users.top().getName() == currentUser.getName()) { cout << "replaced" << endl; newUsers.push(newUser); } else { newUsers.push(users.top()); } users.pop(); } users = newUsers; currentUser = newUser; } void chgUsername() { bool available; Person newUsers; do { available = true; cout << available << endl; cout << "Username : "; cin >> username; stack<Person> temp = users; while (!temp.empty()) { if (temp.top().getName() == username) { cout << "Username unavailable. Please try again." << endl; cout << temp.top().getName() << " " << temp.top().getPhoneNo() << endl; available = false; break; } temp.pop(); } } while (available == false); cout << "Username is available." << endl; Person newPerson(username, currentUser.getPassword(), currentUser.getEmail(), currentUser.getPhoneNo()); update(newPerson); cout << "Username is updated." << endl; } void chgPassword() { cout << "Please input the current password : "; cin >> password; while (!currentUser.checkPassword(password)) { cout << "Wrong password. Please try again." << endl; wrongPass++; cout << "Please input the current password : "; cin >> password; } do { cout << "Please input the new password : "; cin >> password; cout << "Please confirm your new password : "; cin >> password2; } while(password2 != password); currentUser.setPassword(password); update(currentUser); } void chgEmail() { cout << "Please input the new email : "; cin >> email; currentUser.setEmail(email); update(currentUser); } void chgPhoneNo() { cout << "Please input the new phone no. : "; cin >> phoneNo; currentUser.setPhoneNo(phoneNo); update(currentUser); } /* void quit() { ofstream fout("database.txt"); while (!users.empty()) { fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl; users.pop(); } exit (EXIT_SUCCESS); } */ <|endoftext|>
<commit_before>/* Copyright (c) 2015 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #define ARDUINO_MAIN #include "Arduino.h" // Weak empty variant initialization function. // May be redefined by variant files. //void initVariant(void) __attribute__((weak)); //void initVariant(void) { } /* * \brief Main entry point of Arduino application */ int main( void ) { /* Setup vectors in RAM */ vectorSetOrigin( &exception_table ); /* Initialize watchdog */ watchdogSetup(); /* Initialize the Arduino Core API */ init(); /* Initialize the variant */ initVariant(); delay(1); #if 0 #if defined(USBCON) USBDevice.init(); USBDevice.attach(); #endif #endif setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } return 0; } <commit_msg>Rolling back unnecessary change to core_main.cpp<commit_after>/* Copyright (c) 2015 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #define ARDUINO_MAIN #include "Arduino.h" // Weak empty variant initialization function. // May be redefined by variant files. //void initVariant(void) __attribute__((weak)); //void initVariant(void) { } /* * \brief Main entry point of Arduino application */ int main( void ) { /* Setup vectors in RAM */ vectorSetOrigin( &exception_table ); /* Initialize watchdog */ watchdogSetup(); /* Initialize the Arduino Core API */ init(); /* Initialize the variant */ initVariant(); delay(1); #if defined(USBCON) USBDevice.init(); USBDevice.attach(); #endif setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } return 0; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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 "itkImage.h" #include "itkImageFileWriter.h" #include "itkImageFileReader.h" #include "itkCropImageFilter.h" #include "itksys/SystemTools.hxx" #ifdef ENABLE_QUICKVIEW # include "QuickView.h" #endif using PixelType = itk::RGBPixel<unsigned char>; using ImageType = itk::Image<PixelType, 2>; static void CreateImage(ImageType::Pointer image); int main(int argc, char * argv[]) { ImageType::Pointer image = ImageType::New(); ImageType::SizeType cropSize; std::stringstream desc; if (argc > 1) { using ReaderType = itk::ImageFileReader<ImageType>; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); if (argc > 2) { cropSize[0] = std::stoi(argv[2]); cropSize[1] = std::stoi(argv[3]); } reader->Update(); image = reader->GetOutput(); desc << itksys::SystemTools::GetFilenameName(argv[1]); } else { CreateImage(image); cropSize[0] = 10; cropSize[1] = 14; desc << "Synthetic image"; } using CropImageFilterType = itk::CropImageFilter<ImageType, ImageType>; CropImageFilterType::Pointer cropFilter = CropImageFilterType::New(); cropFilter->SetInput(image); // The SetBoundaryCropSize( cropSize ) method specifies the size of // the boundary to be cropped at both the uppper & lower ends of the // image eg. cropSize/2 pixels will be removed at both upper & lower // extents cropFilter->SetBoundaryCropSize(cropSize); // The below three lines are equivalent to the above two lines: // ImageType::SizeType halfCropSize = {5,7}; // cropFilter->SetUpperBoundaryCropSize(halfCropSize); // cropFilter->SetLowerBoundaryCropSize(halfCropSize); #ifdef ENABLE_QUICKVIEW QuickView viewer; viewer.AddRGBImage(image.GetPointer(), true, desc.str()); std::stringstream desc2; desc2 << "CropImageFilter, crop size = {" << cropSize[0] << ", " << cropSize[1] << "}"; viewer.AddRGBImage(cropFilter->GetOutput(), true, desc2.str()); viewer.Visualize(); #endif return EXIT_SUCCESS; } void CreateImage(ImageType::Pointer image) { // Create an image with 2 connected components ImageType::RegionType region; ImageType::IndexType start; start[0] = 0; start[1] = 0; ImageType::SizeType size; unsigned int NumRows = 200; unsigned int NumCols = 300; size[0] = NumRows; size[1] = NumCols; region.SetSize(size); region.SetIndex(start); image->SetRegions(region); image->Allocate(); image->FillBuffer(itk::NumericTraits<ImageType::PixelType>::Zero); // Make a rectangle, centered at (100,150) with sides 160 & 240 // This provides a 20 x 30 border around the square for the crop filter to remove for (unsigned int r = 20; r < 180; r++) { for (unsigned int c = 30; c < 270; c++) { ImageType::IndexType pixelIndex; pixelIndex[0] = r; pixelIndex[1] = c; image->SetPixel(pixelIndex, 200); } } } <commit_msg>DOC: updating comments to reflect actual behavior<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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 "itkImage.h" #include "itkImageFileWriter.h" #include "itkImageFileReader.h" #include "itkCropImageFilter.h" #include "itksys/SystemTools.hxx" #ifdef ENABLE_QUICKVIEW # include "QuickView.h" #endif using PixelType = itk::RGBPixel<unsigned char>; using ImageType = itk::Image<PixelType, 2>; static void CreateImage(ImageType::Pointer image); int main(int argc, char * argv[]) { ImageType::Pointer image = ImageType::New(); ImageType::SizeType cropSize; std::stringstream desc; if (argc > 1) { using ReaderType = itk::ImageFileReader<ImageType>; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(argv[1]); if (argc > 2) { cropSize[0] = std::stoi(argv[2]); cropSize[1] = std::stoi(argv[3]); } reader->Update(); image = reader->GetOutput(); desc << itksys::SystemTools::GetFilenameName(argv[1]); } else { CreateImage(image); cropSize[0] = 10; cropSize[1] = 14; desc << "Synthetic image"; } using CropImageFilterType = itk::CropImageFilter<ImageType, ImageType>; CropImageFilterType::Pointer cropFilter = CropImageFilterType::New(); cropFilter->SetInput(image); // The SetBoundaryCropSize( cropSize ) method specifies the size of // the boundary to be cropped at both the uppper & lower ends of the // image eg. cropSize pixels will be removed at both upper & lower // extents cropFilter->SetBoundaryCropSize(cropSize); // The below two lines are equivalent to the above line: // cropFilter->SetUpperBoundaryCropSize(cropSize); // cropFilter->SetLowerBoundaryCropSize(cropSize); #ifdef ENABLE_QUICKVIEW QuickView viewer; viewer.AddRGBImage(image.GetPointer(), true, desc.str()); std::stringstream desc2; desc2 << "CropImageFilter, crop size = {" << cropSize[0] << ", " << cropSize[1] << "}"; viewer.AddRGBImage(cropFilter->GetOutput(), true, desc2.str()); viewer.Visualize(); #endif return EXIT_SUCCESS; } void CreateImage(ImageType::Pointer image) { // Create an image with 2 connected components ImageType::RegionType region; ImageType::IndexType start; start[0] = 0; start[1] = 0; ImageType::SizeType size; unsigned int NumRows = 200; unsigned int NumCols = 300; size[0] = NumRows; size[1] = NumCols; region.SetSize(size); region.SetIndex(start); image->SetRegions(region); image->Allocate(); image->FillBuffer(itk::NumericTraits<ImageType::PixelType>::Zero); // Make a rectangle, centered at (100,150) with sides 160 & 240 // This provides a 20 x 30 border around the square for the crop filter to remove for (unsigned int r = 20; r < 180; r++) { for (unsigned int c = 30; c < 270; c++) { ImageType::IndexType pixelIndex; pixelIndex[0] = r; pixelIndex[1] = c; image->SetPixel(pixelIndex, 200); } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: frame.cpp // Purpose: Implementation of wxExFrame class // Author: Anton van Wezenbeek // Created: 2010-03-26 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/persist/toplevel.h> #include <wx/extension/frame.h> #include <wx/extension/frd.h> #include <wx/extension/grid.h> #include <wx/extension/lexers.h> #include <wx/extension/listview.h> #include <wx/extension/printing.h> #include <wx/extension/stc.h> #include <wx/extension/tool.h> #include <wx/extension/util.h> #if wxUSE_GUI #if wxUSE_STATUSBAR wxExStatusBar* wxExFrame::m_StatusBar = NULL; #endif #if wxUSE_DRAG_AND_DROP class FileDropTarget : public wxFileDropTarget { public: FileDropTarget(wxExFrame* frame) : m_Frame(frame){;}; private: virtual bool OnDropFiles( wxCoord x, wxCoord y, const wxArrayString& filenames) { wxExOpenFiles(m_Frame, filenames); return true;} wxExFrame* m_Frame; }; #endif BEGIN_EVENT_TABLE(wxExFrame, wxFrame) EVT_FIND(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_CLOSE(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_NEXT(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_REPLACE(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_REPLACE_ALL(wxID_ANY, wxExFrame::OnFindDialog) EVT_MENU(wxID_FIND, wxExFrame::OnCommand) EVT_MENU(wxID_REPLACE, wxExFrame::OnCommand) EVT_MENU(ID_EDIT_FIND_NEXT, wxExFrame::OnCommand) EVT_MENU(ID_EDIT_FIND_PREVIOUS, wxExFrame::OnCommand) EVT_MENU(ID_FOCUS_GRID, wxExFrame::OnCommand) EVT_MENU(ID_FOCUS_LISTVIEW, wxExFrame::OnCommand) EVT_MENU(ID_FOCUS_STC, wxExFrame::OnCommand) EVT_MENU(ID_VIEW_MENUBAR, wxExFrame::OnCommand) EVT_MENU(ID_VIEW_STATUSBAR, wxExFrame::OnCommand) EVT_UPDATE_UI(ID_VIEW_MENUBAR, wxExFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATUSBAR, wxExFrame::OnUpdateUI) #if wxUSE_STATUSBAR EVT_UPDATE_UI(ID_EDIT_STATUS_BAR, wxExFrame::OnUpdateUI) #endif END_EVENT_TABLE() wxExFrame::wxExFrame(wxWindow* parent, wxWindowID id, const wxString& title, long style) : wxFrame(parent, id, title, wxDefaultPosition, wxDefaultSize, style) , m_FindReplaceDialog(NULL) , m_FocusGrid(NULL) , m_FocusListView(NULL) , m_FocusSTC(NULL) { Initialize(); SetName("wxExFrame"); wxPersistentRegisterAndRestore(this); #if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE wxExPrinting::Get()->GetHtmlPrinter()->SetParentWindow(this); #endif } wxExFrame::~wxExFrame() { if (m_FindReplaceDialog != NULL) { m_FindReplaceDialog->Destroy(); } wxConfigBase::Get()->Write("ShowMenuBar", GetMenuBar() != NULL && GetMenuBar()->IsShown()); #if wxUSE_STATUSBAR delete m_StatusBar; #endif } void wxExFrame::FindIn(wxFindDialogEvent& event, wxExGrid* grid) { if ( event.GetEventType() == wxEVT_COMMAND_FIND || event.GetEventType() == wxEVT_COMMAND_FIND_NEXT) { grid->FindNext( wxExFindReplaceData::Get()->GetFindString(), wxExFindReplaceData::Get()->SearchDown()); } else { wxFAIL; } } void wxExFrame::FindIn(wxFindDialogEvent& event, wxExListView* lv) { if ( event.GetEventType() == wxEVT_COMMAND_FIND || event.GetEventType() == wxEVT_COMMAND_FIND_NEXT) { lv->FindNext( wxExFindReplaceData::Get()->GetFindString(), wxExFindReplaceData::Get()->SearchDown()); } else { wxFAIL; } } void wxExFrame::FindIn(wxFindDialogEvent& event, wxExSTC* stc) { auto* frd = wxExFindReplaceData::Get(); // Match word and regular expression do not work together. if (frd->MatchWord()) { frd->SetUseRegularExpression(false); } if ( event.GetEventType() == wxEVT_COMMAND_FIND || event.GetEventType() == wxEVT_COMMAND_FIND_NEXT) { stc->FindNext(frd->SearchDown()); } else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE) { stc->ReplaceNext(frd->SearchDown()); } else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL) { stc->ReplaceAll( frd->GetFindString(), frd->GetReplaceString()); } else { wxFAIL; } } void wxExFrame::GetFindString() { if (m_FocusSTC != NULL) { m_FocusSTC->GetFindString(); } else if (m_FocusGrid != NULL) { m_FocusGrid->GetFindString(); } else { auto* stc = GetSTC(); if (stc != NULL && stc->IsShown()) { stc->GetFindString(); } else { wxExGrid* grid = GetGrid(); if (grid != NULL && grid->IsShown() ) { grid->GetFindString(); } } } } void wxExFrame::Initialize() { #if wxUSE_DRAG_AND_DROP SetDropTarget(new FileDropTarget(this)); #endif wxAcceleratorEntry entries[5]; entries[0].Set(wxACCEL_NORMAL, WXK_F3, ID_EDIT_FIND_NEXT); entries[1].Set(wxACCEL_NORMAL, WXK_F4, ID_EDIT_FIND_PREVIOUS); entries[2].Set(wxACCEL_NORMAL, WXK_F5, wxID_FIND); entries[3].Set(wxACCEL_NORMAL, WXK_F6, wxID_REPLACE); entries[4].Set(wxACCEL_CTRL, (int)'B', ID_VIEW_MENUBAR); wxAcceleratorTable accel(WXSIZEOF(entries), entries); SetAcceleratorTable(accel); } void wxExFrame::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_FIND: GetFindString(); if (m_FindReplaceDialog != NULL) { if (m_FindReplaceDialog->GetWindowStyle() & wxFR_REPLACEDIALOG) { m_FindReplaceDialog->Destroy(); m_FindReplaceDialog = NULL; } } if (m_FindReplaceDialog == NULL) { m_FindReplaceDialog = new wxFindReplaceDialog( this, wxExFindReplaceData::Get(), _("Find")); } m_FindReplaceDialog->Show(); break; case wxID_REPLACE: GetFindString(); if (m_FindReplaceDialog != NULL) { if (!(m_FindReplaceDialog->GetWindowStyle() & wxFR_REPLACEDIALOG)) { m_FindReplaceDialog->Destroy(); m_FindReplaceDialog = NULL; } } if (m_FindReplaceDialog == NULL) { m_FindReplaceDialog = new wxFindReplaceDialog( this, wxExFindReplaceData::Get(), _("Replace"), wxFR_REPLACEDIALOG); } m_FindReplaceDialog->Show(); break; case ID_EDIT_FIND_NEXT: case ID_EDIT_FIND_PREVIOUS: if (m_FocusSTC != NULL) { m_FocusSTC->GetFindString(); m_FocusSTC->FindNext(command.GetId() == ID_EDIT_FIND_NEXT); } else if (m_FocusListView != NULL) { m_FocusListView->FindNext( wxExFindReplaceData::Get()->GetFindString(), command.GetId() == ID_EDIT_FIND_NEXT); } else if (m_FocusGrid != NULL) { m_FocusGrid->GetFindString(); m_FocusGrid->FindNext( wxExFindReplaceData::Get()->GetFindString(), command.GetId() == ID_EDIT_FIND_NEXT); } break; case ID_FOCUS_GRID: m_FocusGrid = (wxExGrid*)command.GetEventObject(); break; case ID_FOCUS_LISTVIEW: m_FocusListView = (wxExListView*)command.GetEventObject();; break; case ID_FOCUS_STC: m_FocusSTC = (wxExSTC*)command.GetEventObject();; break; case ID_VIEW_MENUBAR: { static wxMenuBar* oldbar = NULL; if (GetMenuBar() != NULL) { oldbar = GetMenuBar(); SetMenuBar(NULL); } else { SetMenuBar(oldbar); } } break; case ID_VIEW_STATUSBAR: if (GetStatusBar() != NULL) { GetStatusBar()->Show(!GetStatusBar()->IsShown()); SendSizeEvent(); } break; default: wxFAIL; break; } } #if wxUSE_STATUSBAR wxStatusBar* wxExFrame::OnCreateStatusBar( int number, long style, wxWindowID id, const wxString& name) { m_StatusBar = new wxExStatusBar(this, id, style, name); m_StatusBar->SetFieldsCount(number); return m_StatusBar; } #endif void wxExFrame::OnFindDialog(wxFindDialogEvent& event) { wxASSERT(m_FindReplaceDialog != NULL); if (event.GetEventType() == wxEVT_COMMAND_FIND_CLOSE) { // Hiding instead of destroying, does not // show the dialog next time. m_FindReplaceDialog->Destroy(); m_FindReplaceDialog = NULL; return; } if (m_FocusSTC != NULL) { FindIn(event, m_FocusSTC); } else if (m_FocusListView != NULL) { FindIn(event, m_FocusListView); } else if (m_FocusGrid != NULL) { FindIn(event, m_FocusGrid); } else { auto* stc = GetSTC(); auto* lv = GetListView(); auto* grid = GetGrid(); if (stc != NULL && stc->IsShown()) { FindIn(event, stc); } else if (lv != NULL && lv->IsShown()) { FindIn(event, lv); } else if (grid != NULL && grid->IsShown()) { FindIn(event, grid); } } } void wxExFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_MENUBAR: if (GetMenuBar() != NULL) { event.Check(GetMenuBar()->IsShown()); } else { event.Check(false); } break; case ID_VIEW_STATUSBAR: if (GetStatusBar() != NULL) { event.Check(GetStatusBar()->IsShown()); } else { event.Check(false); } break; #if wxUSE_STATUSBAR case ID_EDIT_STATUS_BAR: { auto* stc = GetFocusedSTC(); if (stc == NULL) return; stc->UpdateStatusBar("PaneLines"); } break; #endif default: wxFAIL; break; } } bool wxExFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { auto* stc = GetFocusedSTC(); if (stc != NULL) { return stc->Open(filename, line_number, match, flags); } return false; } void wxExFrame::SetMenuBar(wxMenuBar* bar) { if (bar != NULL) { m_MenuBar = bar; } if (!wxConfigBase::Get()->ReadBool("ShowMenuBar", true)) { wxFrame::SetMenuBar(NULL); } else { wxASSERT(m_MenuBar != NULL); wxFrame::SetMenuBar(m_MenuBar); } } #if wxUSE_STATUSBAR wxExStatusBar* wxExFrame::SetupStatusBar( const std::vector<wxExPane>& panes, long style, wxWindowID id, const wxString& name) { if (wxFrame::CreateStatusBar(panes.size(), style, id, name) != NULL) { if (m_StatusBar->SetPanes(panes) != panes.size()) { return NULL; } } return m_StatusBar; } #endif // wxUSE_STATUSBAR #if wxUSE_STATUSBAR void wxExFrame::StatusBarDoubleClicked( const wxString& pane) { if (pane == "PaneLines") { auto* stc = GetSTC(); if (stc != NULL) stc->GotoDialog(); } else if (pane == "PaneLexer") { auto* stc = GetSTC(); if (stc != NULL && wxExLexers::Get()->Count() > 0) { wxString lexer = stc->GetLexer().GetScintillaLexer(); if (wxExLexers::Get()->ShowDialog(this, lexer)) { stc->SetLexer(lexer); } } } else if (pane == "PaneFileType") { auto* stc = GetSTC(); if (stc != NULL) stc->FileTypeMenu(); } else if (pane == "PaneItems") { wxExListView* list = GetListView(); if (list != NULL) list->GotoDialog(); } else { // Clicking on another field, do nothing. } } // This is a static method, so you cannot call wxFrame::SetStatusText. void wxExFrame::StatusText(const wxString& text, const wxString& pane) { if (m_StatusBar != NULL) { m_StatusBar->SetStatusText(text, pane); } } void wxExFrame::StatusText(const wxExFileName& filename, long flags) { // Clear status bar for empty or not existing or not initialized file names. wxString text; if (filename.IsOk()) { const wxString path = (flags & STAT_FULLPATH ? filename.GetFullPath(): filename.GetFullName()); text += path; if (filename.GetStat().IsOk()) { const wxString what = (flags & STAT_SYNC ? _("Synchronized"): _("Modified")); const wxString time = (flags & STAT_SYNC ? wxDateTime::Now().Format(): filename.GetStat().GetModificationTime()); text += " " + what + " " + time; } } StatusText(text); } #endif // wxUSE_STATUSBAR #endif // wxUSE_GUI <commit_msg>menubar code simpler<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: frame.cpp // Purpose: Implementation of wxExFrame class // Author: Anton van Wezenbeek // Created: 2010-03-26 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/persist/toplevel.h> #include <wx/extension/frame.h> #include <wx/extension/frd.h> #include <wx/extension/grid.h> #include <wx/extension/lexers.h> #include <wx/extension/listview.h> #include <wx/extension/printing.h> #include <wx/extension/stc.h> #include <wx/extension/tool.h> #include <wx/extension/util.h> #if wxUSE_GUI #if wxUSE_STATUSBAR wxExStatusBar* wxExFrame::m_StatusBar = NULL; #endif #if wxUSE_DRAG_AND_DROP class FileDropTarget : public wxFileDropTarget { public: FileDropTarget(wxExFrame* frame) : m_Frame(frame){;}; private: virtual bool OnDropFiles( wxCoord x, wxCoord y, const wxArrayString& filenames) { wxExOpenFiles(m_Frame, filenames); return true;} wxExFrame* m_Frame; }; #endif BEGIN_EVENT_TABLE(wxExFrame, wxFrame) EVT_FIND(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_CLOSE(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_NEXT(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_REPLACE(wxID_ANY, wxExFrame::OnFindDialog) EVT_FIND_REPLACE_ALL(wxID_ANY, wxExFrame::OnFindDialog) EVT_MENU(wxID_FIND, wxExFrame::OnCommand) EVT_MENU(wxID_REPLACE, wxExFrame::OnCommand) EVT_MENU(ID_EDIT_FIND_NEXT, wxExFrame::OnCommand) EVT_MENU(ID_EDIT_FIND_PREVIOUS, wxExFrame::OnCommand) EVT_MENU(ID_FOCUS_GRID, wxExFrame::OnCommand) EVT_MENU(ID_FOCUS_LISTVIEW, wxExFrame::OnCommand) EVT_MENU(ID_FOCUS_STC, wxExFrame::OnCommand) EVT_MENU(ID_VIEW_MENUBAR, wxExFrame::OnCommand) EVT_MENU(ID_VIEW_STATUSBAR, wxExFrame::OnCommand) EVT_UPDATE_UI(ID_VIEW_MENUBAR, wxExFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATUSBAR, wxExFrame::OnUpdateUI) #if wxUSE_STATUSBAR EVT_UPDATE_UI(ID_EDIT_STATUS_BAR, wxExFrame::OnUpdateUI) #endif END_EVENT_TABLE() wxExFrame::wxExFrame(wxWindow* parent, wxWindowID id, const wxString& title, long style) : wxFrame(parent, id, title, wxDefaultPosition, wxDefaultSize, style) , m_FindReplaceDialog(NULL) , m_FocusGrid(NULL) , m_FocusListView(NULL) , m_FocusSTC(NULL) { Initialize(); SetName("wxExFrame"); wxPersistentRegisterAndRestore(this); #if wxUSE_HTML & wxUSE_PRINTING_ARCHITECTURE wxExPrinting::Get()->GetHtmlPrinter()->SetParentWindow(this); #endif } wxExFrame::~wxExFrame() { if (m_FindReplaceDialog != NULL) { m_FindReplaceDialog->Destroy(); } wxConfigBase::Get()->Write("ShowMenuBar", GetMenuBar() != NULL && GetMenuBar()->IsShown()); #if wxUSE_STATUSBAR delete m_StatusBar; #endif } void wxExFrame::FindIn(wxFindDialogEvent& event, wxExGrid* grid) { if ( event.GetEventType() == wxEVT_COMMAND_FIND || event.GetEventType() == wxEVT_COMMAND_FIND_NEXT) { grid->FindNext( wxExFindReplaceData::Get()->GetFindString(), wxExFindReplaceData::Get()->SearchDown()); } else { wxFAIL; } } void wxExFrame::FindIn(wxFindDialogEvent& event, wxExListView* lv) { if ( event.GetEventType() == wxEVT_COMMAND_FIND || event.GetEventType() == wxEVT_COMMAND_FIND_NEXT) { lv->FindNext( wxExFindReplaceData::Get()->GetFindString(), wxExFindReplaceData::Get()->SearchDown()); } else { wxFAIL; } } void wxExFrame::FindIn(wxFindDialogEvent& event, wxExSTC* stc) { auto* frd = wxExFindReplaceData::Get(); // Match word and regular expression do not work together. if (frd->MatchWord()) { frd->SetUseRegularExpression(false); } if ( event.GetEventType() == wxEVT_COMMAND_FIND || event.GetEventType() == wxEVT_COMMAND_FIND_NEXT) { stc->FindNext(frd->SearchDown()); } else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE) { stc->ReplaceNext(frd->SearchDown()); } else if (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL) { stc->ReplaceAll( frd->GetFindString(), frd->GetReplaceString()); } else { wxFAIL; } } void wxExFrame::GetFindString() { if (m_FocusSTC != NULL) { m_FocusSTC->GetFindString(); } else if (m_FocusGrid != NULL) { m_FocusGrid->GetFindString(); } else { auto* stc = GetSTC(); if (stc != NULL && stc->IsShown()) { stc->GetFindString(); } else { wxExGrid* grid = GetGrid(); if (grid != NULL && grid->IsShown() ) { grid->GetFindString(); } } } } void wxExFrame::Initialize() { #if wxUSE_DRAG_AND_DROP SetDropTarget(new FileDropTarget(this)); #endif wxAcceleratorEntry entries[5]; entries[0].Set(wxACCEL_NORMAL, WXK_F3, ID_EDIT_FIND_NEXT); entries[1].Set(wxACCEL_NORMAL, WXK_F4, ID_EDIT_FIND_PREVIOUS); entries[2].Set(wxACCEL_NORMAL, WXK_F5, wxID_FIND); entries[3].Set(wxACCEL_NORMAL, WXK_F6, wxID_REPLACE); entries[4].Set(wxACCEL_CTRL, (int)'B', ID_VIEW_MENUBAR); wxAcceleratorTable accel(WXSIZEOF(entries), entries); SetAcceleratorTable(accel); } void wxExFrame::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_FIND: GetFindString(); if (m_FindReplaceDialog != NULL) { if (m_FindReplaceDialog->GetWindowStyle() & wxFR_REPLACEDIALOG) { m_FindReplaceDialog->Destroy(); m_FindReplaceDialog = NULL; } } if (m_FindReplaceDialog == NULL) { m_FindReplaceDialog = new wxFindReplaceDialog( this, wxExFindReplaceData::Get(), _("Find")); } m_FindReplaceDialog->Show(); break; case wxID_REPLACE: GetFindString(); if (m_FindReplaceDialog != NULL) { if (!(m_FindReplaceDialog->GetWindowStyle() & wxFR_REPLACEDIALOG)) { m_FindReplaceDialog->Destroy(); m_FindReplaceDialog = NULL; } } if (m_FindReplaceDialog == NULL) { m_FindReplaceDialog = new wxFindReplaceDialog( this, wxExFindReplaceData::Get(), _("Replace"), wxFR_REPLACEDIALOG); } m_FindReplaceDialog->Show(); break; case ID_EDIT_FIND_NEXT: case ID_EDIT_FIND_PREVIOUS: if (m_FocusSTC != NULL) { m_FocusSTC->GetFindString(); m_FocusSTC->FindNext(command.GetId() == ID_EDIT_FIND_NEXT); } else if (m_FocusListView != NULL) { m_FocusListView->FindNext( wxExFindReplaceData::Get()->GetFindString(), command.GetId() == ID_EDIT_FIND_NEXT); } else if (m_FocusGrid != NULL) { m_FocusGrid->GetFindString(); m_FocusGrid->FindNext( wxExFindReplaceData::Get()->GetFindString(), command.GetId() == ID_EDIT_FIND_NEXT); } break; case ID_FOCUS_GRID: m_FocusGrid = (wxExGrid*)command.GetEventObject(); break; case ID_FOCUS_LISTVIEW: m_FocusListView = (wxExListView*)command.GetEventObject();; break; case ID_FOCUS_STC: m_FocusSTC = (wxExSTC*)command.GetEventObject();; break; case ID_VIEW_MENUBAR: if (GetMenuBar() != NULL) { SetMenuBar(NULL); } else { SetMenuBar(m_MenuBar); } break; case ID_VIEW_STATUSBAR: if (GetStatusBar() != NULL) { GetStatusBar()->Show(!GetStatusBar()->IsShown()); SendSizeEvent(); } break; default: wxFAIL; break; } } #if wxUSE_STATUSBAR wxStatusBar* wxExFrame::OnCreateStatusBar( int number, long style, wxWindowID id, const wxString& name) { m_StatusBar = new wxExStatusBar(this, id, style, name); m_StatusBar->SetFieldsCount(number); return m_StatusBar; } #endif void wxExFrame::OnFindDialog(wxFindDialogEvent& event) { wxASSERT(m_FindReplaceDialog != NULL); if (event.GetEventType() == wxEVT_COMMAND_FIND_CLOSE) { // Hiding instead of destroying, does not // show the dialog next time. m_FindReplaceDialog->Destroy(); m_FindReplaceDialog = NULL; return; } if (m_FocusSTC != NULL) { FindIn(event, m_FocusSTC); } else if (m_FocusListView != NULL) { FindIn(event, m_FocusListView); } else if (m_FocusGrid != NULL) { FindIn(event, m_FocusGrid); } else { auto* stc = GetSTC(); auto* lv = GetListView(); auto* grid = GetGrid(); if (stc != NULL && stc->IsShown()) { FindIn(event, stc); } else if (lv != NULL && lv->IsShown()) { FindIn(event, lv); } else if (grid != NULL && grid->IsShown()) { FindIn(event, grid); } } } void wxExFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_MENUBAR: if (GetMenuBar() != NULL) { event.Check(GetMenuBar()->IsShown()); } else { event.Check(false); } break; case ID_VIEW_STATUSBAR: if (GetStatusBar() != NULL) { event.Check(GetStatusBar()->IsShown()); } else { event.Check(false); } break; #if wxUSE_STATUSBAR case ID_EDIT_STATUS_BAR: { auto* stc = GetFocusedSTC(); if (stc == NULL) return; stc->UpdateStatusBar("PaneLines"); } break; #endif default: wxFAIL; break; } } bool wxExFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { auto* stc = GetFocusedSTC(); if (stc != NULL) { return stc->Open(filename, line_number, match, flags); } return false; } void wxExFrame::SetMenuBar(wxMenuBar* bar) { if (bar != NULL) { m_MenuBar = bar; } if (!wxConfigBase::Get()->ReadBool("ShowMenuBar", true)) { wxFrame::SetMenuBar(NULL); } else { wxASSERT(m_MenuBar != NULL); wxFrame::SetMenuBar(m_MenuBar); } } #if wxUSE_STATUSBAR wxExStatusBar* wxExFrame::SetupStatusBar( const std::vector<wxExPane>& panes, long style, wxWindowID id, const wxString& name) { if (wxFrame::CreateStatusBar(panes.size(), style, id, name) != NULL) { if (m_StatusBar->SetPanes(panes) != panes.size()) { return NULL; } } return m_StatusBar; } #endif // wxUSE_STATUSBAR #if wxUSE_STATUSBAR void wxExFrame::StatusBarDoubleClicked( const wxString& pane) { if (pane == "PaneLines") { auto* stc = GetSTC(); if (stc != NULL) stc->GotoDialog(); } else if (pane == "PaneLexer") { auto* stc = GetSTC(); if (stc != NULL && wxExLexers::Get()->Count() > 0) { wxString lexer = stc->GetLexer().GetScintillaLexer(); if (wxExLexers::Get()->ShowDialog(this, lexer)) { stc->SetLexer(lexer); } } } else if (pane == "PaneFileType") { auto* stc = GetSTC(); if (stc != NULL) stc->FileTypeMenu(); } else if (pane == "PaneItems") { wxExListView* list = GetListView(); if (list != NULL) list->GotoDialog(); } else { // Clicking on another field, do nothing. } } // This is a static method, so you cannot call wxFrame::SetStatusText. void wxExFrame::StatusText(const wxString& text, const wxString& pane) { if (m_StatusBar != NULL) { m_StatusBar->SetStatusText(text, pane); } } void wxExFrame::StatusText(const wxExFileName& filename, long flags) { // Clear status bar for empty or not existing or not initialized file names. wxString text; if (filename.IsOk()) { const wxString path = (flags & STAT_FULLPATH ? filename.GetFullPath(): filename.GetFullName()); text += path; if (filename.GetStat().IsOk()) { const wxString what = (flags & STAT_SYNC ? _("Synchronized"): _("Modified")); const wxString time = (flags & STAT_SYNC ? wxDateTime::Now().Format(): filename.GetStat().GetModificationTime()); text += " " + what + " " + time; } } StatusText(text); } #endif // wxUSE_STATUSBAR #endif // wxUSE_GUI <|endoftext|>
<commit_before>// // precise-generator.cpp // // Created by Peter Gusev on 19 March 2016. // Copyright 2013-2016 Regents of the University of California // // #define DEBUG_PG #include "precise-generator.hpp" #include <boost/make_shared.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/thread/mutex.hpp> #include <boost/atomic.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/lock_guard.hpp> #define STEADY_TIMER #ifdef STEADY_TIMER #include <boost/asio/steady_timer.hpp> typedef boost::asio::steady_timer timer_type; typedef lib_chrono::milliseconds ms; typedef lib_chrono::nanoseconds ns; typedef lib_chrono::high_resolution_clock::time_point time_point_type; typedef lib_chrono::high_resolution_clock::duration duration_type; #define duration_cast_ms(a) (lib_chrono::duration_cast<ms>(a)) #define duration_cast_ns(a) (lib_chrono::duration_cast<ns>(a)) #define duration_cast_double_ns(a) double(lib_chrono::duration_cast<ns>(a).count()) #define duration_count(a) (a).count() #define now_time() (lib_chrono::high_resolution_clock::now()) #define is_time_point_zero(pt) (pt.time_since_epoch() == lib_chrono::high_resolution_clock::duration::zero()) #define print_duration_ns(d) (d.count()) #else // deadline timer // requires posix_time #include <boost/asio/deadline_timer.hpp> typedef boost::asio::deadline_timer timer_type; typedef boost::posix_time::ptime time_point_type; typedef boost::posix_time::milliseconds ms; typedef boost::posix_time::nanoseconds ns; typedef boost::posix_time::time_duration duration_type; #define duration_cast_ms(a) ms((a).total_milliseconds()) #define duration_cast_ns(a) ns((a).total_nanoseconds()) #define duration_cast_double_ns(a) double((a).total_nanoseconds()) #define duration_count(a) (a).ticks() #define now_time() (boost::posix_time::microsec_clock::local_time()) #define is_time_point_zero(pt) (pt == boost::posix_time::not_a_date_time) #define print_duration_ns(d) (d.total_nanoseconds()) #endif using namespace std; using namespace std::placeholders; class PreciseGeneratorImpl : public boost::enable_shared_from_this<PreciseGeneratorImpl> { public: PreciseGeneratorImpl(boost::asio::io_service& io, const double& ratePerSec, const PreciseGenerator::Task& task); void start(); void stop(); bool isRunning(){ return isRunning_; } long long getFireCount() { return fireCount_; } double getMeanProcessingOverheadNs() { return (meanProcOverheadNs_); }// - meanTaskTimeNs_); } double getMeanTaskTimeNs() { return meanTaskTimeNs_; } boost::recursive_mutex setupMutex_; boost::atomic<bool> isRunning_; long long fireCount_; double meanProcOverheadNs_, meanTaskTimeNs_; double rate_; PreciseGenerator::Task task_; boost::asio::io_service& io_; timer_type timer_; time_point_type iterStart_; duration_type lagNs_, lastTaskDurationNs_; ms lastIterIntervalMs_; void setupTimer(); void onFire(const boost::system::error_code& code); ms getAdjustedInterval(const time_point_type& lastIterStart, const time_point_type& thisIterStart, const ms lastIterIntervalMs, const ns lastTaskDurationNs, const double& rate); }; //****************************************************************************** PreciseGenerator::PreciseGenerator(boost::asio::io_service& io, const double& ratePerSec, const Task& task): pimpl_(boost::make_shared<PreciseGeneratorImpl>(io, ratePerSec, task)){} PreciseGenerator::~PreciseGenerator(){ pimpl_->stop(); } void PreciseGenerator::start(){ pimpl_->start(); } void PreciseGenerator::stop(){ pimpl_->stop(); } bool PreciseGenerator::isRunning(){ return pimpl_->isRunning(); } long long PreciseGenerator::getFireCount(){ return pimpl_->getFireCount(); } double PreciseGenerator::getMeanProcessingOverheadNs(){ return pimpl_->getMeanProcessingOverheadNs(); } double PreciseGenerator::getMeanTaskTimeNs(){ return pimpl_->getMeanTaskTimeNs(); } //****************************************************************************** PreciseGeneratorImpl::PreciseGeneratorImpl(boost::asio::io_service& io, const double& ratePerSec, const PreciseGenerator::Task& task): io_(io), timer_(io), rate_(ratePerSec), task_(task), lastIterIntervalMs_(0), meanProcOverheadNs_(0), meanTaskTimeNs_(0) #ifdef STEADY_TIMER , lagNs_(0), lastTaskDurationNs_(0) #endif {} void PreciseGeneratorImpl::start() { fireCount_ = 0; isRunning_ = true; setupTimer(); } void PreciseGeneratorImpl::stop() { if (isRunning_) { boost::lock_guard<boost::recursive_mutex> scopedLock(setupMutex_); isRunning_ = false; timer_.cancel(); } } void PreciseGeneratorImpl::setupTimer() { time_point_type lastIterStart = iterStart_; iterStart_ = now_time(); ms interval = getAdjustedInterval(lastIterStart, iterStart_, lastIterIntervalMs_, lastTaskDurationNs_, rate_); timer_.expires_from_now(interval); timer_.async_wait(lib_bind::bind(&PreciseGeneratorImpl::onFire, shared_from_this(), _1)); lastIterIntervalMs_ = interval; } void PreciseGeneratorImpl::onFire(const boost::system::error_code& code) { if (!code) { boost::lock_guard<boost::recursive_mutex> scopedLock(setupMutex_); if (isRunning_) { time_point_type tstart = now_time(); task_(); time_point_type tend = now_time(); fireCount_++; lastTaskDurationNs_ = duration_cast_ns((tend-tstart)); meanTaskTimeNs_ += (double)(duration_cast_double_ns(lastTaskDurationNs_) - meanTaskTimeNs_)/(double)fireCount_; setupTimer(); } } } ms PreciseGeneratorImpl::getAdjustedInterval(const time_point_type& lastIterStart, const time_point_type& thisIterStart, const ms lastIterIntervalMs, const ns lastTaskDurationNs, const double& rate) { ns originalInterval = ns((int)(1000000000./rate)); ms adjustedIntervalMs = duration_cast_ms(originalInterval); ms originalIntervalMs = duration_cast_ms(originalInterval); ns diff = duration_cast_ns(originalInterval - duration_cast_ns(duration_cast_ms((originalInterval)))); lagNs_ -= diff; #ifdef DEBUG_PG cout << "remainder " << print_duration_ns(diff) << endl; #endif if (!is_time_point_zero(lastIterStart)) { ns lastIterDurationNs = duration_cast_ns((thisIterStart-lastIterStart)); ns iterLag = duration_cast_ns(lastIterDurationNs-lastIterIntervalMs); lagNs_ += iterLag; meanProcOverheadNs_ += (double)(duration_cast_double_ns(iterLag-lastTaskDurationNs) - meanProcOverheadNs_)/(double)fireCount_; #ifdef DEBUG_PG cout << "last iter time " << print_duration_ns(lastIterDurationNs) << " (should " << print_duration_ns(lastIterIntervalMs) << ", " << print_duration_ns(iterLag) << " lag, " << print_duration_ns(lastTaskDurationNs) << " task)" << endl; cout << "accum lag " << print_duration_ns(lagNs_) << endl; #endif if (lagNs_ > originalIntervalMs) { lagNs_ -= originalIntervalMs; adjustedIntervalMs = ms(0); } else if (abs(duration_count(duration_cast_ms(lagNs_))) > 0) { adjustedIntervalMs = duration_cast_ms(originalIntervalMs - duration_cast_ms(lagNs_)); lagNs_ -= duration_cast_ms(lagNs_); } } #ifdef DEBUG_PG cout << "interval " << print_duration_ns(adjustedIntervalMs) << endl; cout << "adjusted lag " << print_duration_ns(lagNs_) << endl << "-" << endl; #endif return adjustedIntervalMs; } <commit_msg>fixed ubuntu compatibility<commit_after>// // precise-generator.cpp // // Created by Peter Gusev on 19 March 2016. // Copyright 2013-2016 Regents of the University of California // // #define DEBUG_PG #include "precise-generator.hpp" #include <boost/make_shared.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/thread/mutex.hpp> #include <boost/atomic.hpp> #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/lock_guard.hpp> #define STEADY_TIMER #ifdef STEADY_TIMER #include <boost/asio/steady_timer.hpp> typedef boost::asio::steady_timer timer_type; typedef lib_chrono::milliseconds ms; typedef lib_chrono::nanoseconds ns; typedef lib_chrono::high_resolution_clock::time_point time_point_type; typedef lib_chrono::high_resolution_clock::duration duration_type; #define duration_cast_ms(a) (lib_chrono::duration_cast<ms>(a)) #define duration_cast_ns(a) (lib_chrono::duration_cast<ns>(a)) #define duration_cast_double_ns(a) double(lib_chrono::duration_cast<ns>(a).count()) #define duration_count(a) (a).count() #define now_time() (lib_chrono::high_resolution_clock::now()) #define is_time_point_zero(pt) (pt.time_since_epoch() == lib_chrono::high_resolution_clock::duration::zero()) #define print_duration_ns(d) (d.count()) #else // deadline timer // requires posix_time #include <boost/asio/deadline_timer.hpp> typedef boost::asio::deadline_timer timer_type; typedef boost::posix_time::ptime time_point_type; typedef boost::posix_time::milliseconds ms; typedef boost::posix_time::nanoseconds ns; typedef boost::posix_time::time_duration duration_type; #define duration_cast_ms(a) ms((a).total_milliseconds()) #define duration_cast_ns(a) ns((a).total_nanoseconds()) #define duration_cast_double_ns(a) double((a).total_nanoseconds()) #define duration_count(a) (a).ticks() #define now_time() (boost::posix_time::microsec_clock::local_time()) #define is_time_point_zero(pt) (pt == boost::posix_time::not_a_date_time) #define print_duration_ns(d) (d.total_nanoseconds()) #endif using namespace std; using namespace std::placeholders; class PreciseGeneratorImpl : public boost::enable_shared_from_this<PreciseGeneratorImpl> { public: PreciseGeneratorImpl(boost::asio::io_service& io, const double& ratePerSec, const PreciseGenerator::Task& task); void start(); void stop(); bool isRunning(){ return isRunning_; } long long getFireCount() { return fireCount_; } double getMeanProcessingOverheadNs() { return (meanProcOverheadNs_); }// - meanTaskTimeNs_); } double getMeanTaskTimeNs() { return meanTaskTimeNs_; } boost::recursive_mutex setupMutex_; boost::atomic<bool> isRunning_; long long fireCount_; double meanProcOverheadNs_, meanTaskTimeNs_; double rate_; PreciseGenerator::Task task_; boost::asio::io_service& io_; timer_type timer_; time_point_type iterStart_; duration_type lagNs_, lastTaskDurationNs_; ms lastIterIntervalMs_; void setupTimer(); void onFire(const boost::system::error_code& code); ms getAdjustedInterval(const time_point_type& lastIterStart, const time_point_type& thisIterStart, const ms lastIterIntervalMs, const ns lastTaskDurationNs, const double& rate); }; //****************************************************************************** PreciseGenerator::PreciseGenerator(boost::asio::io_service& io, const double& ratePerSec, const Task& task): pimpl_(boost::make_shared<PreciseGeneratorImpl>(io, ratePerSec, task)){} PreciseGenerator::~PreciseGenerator(){ pimpl_->stop(); } void PreciseGenerator::start(){ pimpl_->start(); } void PreciseGenerator::stop(){ pimpl_->stop(); } bool PreciseGenerator::isRunning(){ return pimpl_->isRunning(); } long long PreciseGenerator::getFireCount(){ return pimpl_->getFireCount(); } double PreciseGenerator::getMeanProcessingOverheadNs(){ return pimpl_->getMeanProcessingOverheadNs(); } double PreciseGenerator::getMeanTaskTimeNs(){ return pimpl_->getMeanTaskTimeNs(); } //****************************************************************************** PreciseGeneratorImpl::PreciseGeneratorImpl(boost::asio::io_service& io, const double& ratePerSec, const PreciseGenerator::Task& task): io_(io), timer_(io), rate_(ratePerSec), task_(task), lastIterIntervalMs_(0), meanProcOverheadNs_(0), meanTaskTimeNs_(0) #ifdef STEADY_TIMER , lagNs_(0), lastTaskDurationNs_(0) #endif {} void PreciseGeneratorImpl::start() { fireCount_ = 0; isRunning_ = true; setupTimer(); } void PreciseGeneratorImpl::stop() { if (isRunning_) { boost::lock_guard<boost::recursive_mutex> scopedLock(setupMutex_); isRunning_ = false; timer_.cancel(); } } void PreciseGeneratorImpl::setupTimer() { time_point_type lastIterStart = iterStart_; iterStart_ = now_time(); ms interval = getAdjustedInterval(lastIterStart, iterStart_, lastIterIntervalMs_, lastTaskDurationNs_, rate_); timer_.expires_from_now(interval); #ifdef OS_DARWIN timer_.async_wait(lib_bind::bind(&PreciseGeneratorImpl::onFire, shared_from_this(), _1)); #else timer_.async_wait(lib_bind::bind(&PreciseGeneratorImpl::onFire, shared_from_this(), boost::arg<1>())); #endif lastIterIntervalMs_ = interval; } void PreciseGeneratorImpl::onFire(const boost::system::error_code& code) { if (!code) { boost::lock_guard<boost::recursive_mutex> scopedLock(setupMutex_); if (isRunning_) { time_point_type tstart = now_time(); task_(); time_point_type tend = now_time(); fireCount_++; lastTaskDurationNs_ = duration_cast_ns((tend-tstart)); meanTaskTimeNs_ += (double)(duration_cast_double_ns(lastTaskDurationNs_) - meanTaskTimeNs_)/(double)fireCount_; setupTimer(); } } } ms PreciseGeneratorImpl::getAdjustedInterval(const time_point_type& lastIterStart, const time_point_type& thisIterStart, const ms lastIterIntervalMs, const ns lastTaskDurationNs, const double& rate) { ns originalInterval = ns((int)(1000000000./rate)); ms adjustedIntervalMs = duration_cast_ms(originalInterval); ms originalIntervalMs = duration_cast_ms(originalInterval); ns diff = duration_cast_ns(originalInterval - duration_cast_ns(duration_cast_ms((originalInterval)))); lagNs_ -= diff; #ifdef DEBUG_PG cout << "remainder " << print_duration_ns(diff) << endl; #endif if (!is_time_point_zero(lastIterStart)) { ns lastIterDurationNs = duration_cast_ns((thisIterStart-lastIterStart)); ns iterLag = duration_cast_ns(lastIterDurationNs-lastIterIntervalMs); lagNs_ += iterLag; meanProcOverheadNs_ += (double)(duration_cast_double_ns(iterLag-lastTaskDurationNs) - meanProcOverheadNs_)/(double)fireCount_; #ifdef DEBUG_PG cout << "last iter time " << print_duration_ns(lastIterDurationNs) << " (should " << print_duration_ns(lastIterIntervalMs) << ", " << print_duration_ns(iterLag) << " lag, " << print_duration_ns(lastTaskDurationNs) << " task)" << endl; cout << "accum lag " << print_duration_ns(lagNs_) << endl; #endif if (lagNs_ > originalIntervalMs) { lagNs_ -= originalIntervalMs; adjustedIntervalMs = ms(0); } else if (abs(duration_count(duration_cast_ms(lagNs_))) > 0) { adjustedIntervalMs = duration_cast_ms(originalIntervalMs - duration_cast_ms(lagNs_)); lagNs_ -= duration_cast_ms(lagNs_); } } #ifdef DEBUG_PG cout << "interval " << print_duration_ns(adjustedIntervalMs) << endl; cout << "adjusted lag " << print_duration_ns(lagNs_) << endl << "-" << endl; #endif return adjustedIntervalMs; } <|endoftext|>
<commit_before>/******************************************************************************\ * File: shell.cpp * Purpose: Implementation of class wxExSTCShell * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/app.h> #if wxUSE_GUI using namespace std; BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, long menu_flags) : wxExSTC(parent, menu_flags) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig == -1) { // Fill the list with an empty command. KeepCommand(); } else { // Get all previous commands. wxStringTokenizer tkz(wxExApp::GetConfig("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } // Take care that m_CommandsIterator is valid. if (!m_Commands.empty()) { m_CommandsIterator = m_Commands.end(); } else { KeepCommand(); } } } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < m_CommandsSaveInConfig; it++) { values += *it + m_CommandsInConfigDelimiter; items++; } wxExApp::SetConfig("Shell", values); } } const wxString wxExSTCShell::GetHistory() const { wxString commands; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { commands += *it + "\n"; } return commands; } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); if (m_Commands.size() == 1) { m_CommandsIterator = m_Commands.end(); } } void wxExSTCShell::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_PASTE: // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } Paste(); break; default: command.Skip(); break; } } void wxExSTCShell::OnKey(wxKeyEvent& event) { const int key = event.GetKeyCode(); // Enter key pressed, we might have entered a command. if (key == WXK_RETURN) { // First get the command. SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { m_Command = GetText().substr( GetTargetStart() + m_Prompt.length(), GetTextLength() - 1); m_Command.Trim(); } if (m_Command.empty()) { Prompt(); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(m_Command); KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } else { Prompt(m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } m_Command.clear(); } else { if (m_Echo) event.Skip(); } if (m_Commands.size() > 1) { m_CommandsIterator = m_Commands.end(); } } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { // There is always an empty command in the list. if (m_Commands.size() > 1) { ShowCommand(key); } } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q') { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(GetParent(), event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd(); if (m_Echo) event.Skip(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } if (m_Commands.size() > 1) { m_CommandsIterator = m_Commands.end(); } if (m_Echo) event.Skip(); } } void wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!text.empty()) { AppendText(text); } if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const int no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } // using a const_reverse_iterator here does not compile under MSW for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend(); it++) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { ReplaceTarget(m_Prompt + *m_CommandsIterator); } else { ReplaceTarget(m_Prompt); } DocumentEnd(); } } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( list < wxString >::iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { const wxString command = *it; if (!command.empty()) { AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } } #endif // wxUSE_GUI <commit_msg>wxExSTCShell now works more similar to bash shell<commit_after>/******************************************************************************\ * File: shell.cpp * Purpose: Implementation of class wxExSTCShell * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/app.h> #if wxUSE_GUI using namespace std; BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, long menu_flags) : wxExSTC(parent, menu_flags) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig == -1) { // Fill the list with an empty command. KeepCommand(); } else { // Get all previous commands. wxStringTokenizer tkz(wxExApp::GetConfig("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } // Take care that m_CommandsIterator is valid. if (!m_Commands.empty()) { m_CommandsIterator = m_Commands.end(); } else { KeepCommand(); } } } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < m_CommandsSaveInConfig; it++) { values += *it + m_CommandsInConfigDelimiter; items++; } wxExApp::SetConfig("Shell", values); } } const wxString wxExSTCShell::GetHistory() const { wxString commands; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { commands += *it + "\n"; } return commands; } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); if (m_Commands.size() == 1) { m_CommandsIterator = m_Commands.end(); } } void wxExSTCShell::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_PASTE: // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } Paste(); break; default: command.Skip(); break; } } void wxExSTCShell::OnKey(wxKeyEvent& event) { const int key = event.GetKeyCode(); // Enter key pressed, we might have entered a command. if (key == WXK_RETURN) { // First get the command. SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { m_Command = GetText().substr( GetTargetStart() + m_Prompt.length(), GetTextLength() - 1); m_Command.Trim(); } if (m_Command.empty()) { Prompt(); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } else { Prompt(m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } m_Command.clear(); } else { if (m_Echo) event.Skip(); } if (m_Commands.size() > 1) { m_CommandsIterator = m_Commands.end(); } } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { // There is always an empty command in the list. if (m_Commands.size() > 1) { ShowCommand(key); } } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q') { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(GetParent(), event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd(); if (m_Echo) event.Skip(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } if (m_Commands.size() > 1) { m_CommandsIterator = m_Commands.end(); } if (m_Echo) event.Skip(); } } void wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!text.empty()) { AppendText(text); } if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const int no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 0; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } // using a const_reverse_iterator here does not compile under MSW for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend(); it++) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { ReplaceTarget(m_Prompt + *m_CommandsIterator); } else { ReplaceTarget(m_Prompt); } DocumentEnd(); } } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( list < wxString >::iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { const wxString command = *it; if (!command.empty()) { AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void exTestFixture::setUp() { m_Config = new exConfig("test.cfg", wxCONFIG_USE_LOCAL_FILE); m_File = new exFile("test.h"); m_FileName = new exFileName("test.h"); m_FileNameStatistics = new exFileNameStatistics("test.h"); m_Lexer = new exLexer(); m_Lexers = new exLexers(exFileName("../data/lexers.xml")); m_RCS = new exRCS(); m_Stat = new exStat("test.h"); m_Statistics = new exStatistics<long>(); m_TextFile = new exTextFile(exFileName("test.h"), m_Config, m_Lexers); m_Tool = new exTool(ID_TOOL_REPORT_COUNT); } void exTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void exTestFixture::testMethods() { // test exConfig CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val"); CPPUNIT_ASSERT(m_Config->Get("keylong", 12) == 12); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true)); CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL); m_Config->Set("keystring", "val2"); CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val2"); m_Config->Set("keylong", 15); CPPUNIT_ASSERT(m_Config->Get("keylong", 7) == 15); m_Config->SetBool("keybool", false); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true) == false); m_Config->Toggle("keybool"); CPPUNIT_ASSERT(m_Config->GetBool("keybool", false)); // test exFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetStat().GetFullPath() == m_File->GetFileName().GetFullPath()); // The fullpath should be normalized, test it. CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() != "test.h"); // test exFileName CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty()); CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); m_FileName->Assign("xxx"); m_FileName->GetStat().Update("xxx"); CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk()); // test exFileNameStatistics CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty()); CPPUNIT_ASSERT(m_FileNameStatistics->Get("xx") == 0); // test exLexer *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers m_Lexer->SetKeywords("test11 test21:1 test31:1 test12:2 test22:2"); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test11")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test21")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test12")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test22")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("te")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xx")); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); // test exLexers CPPUNIT_ASSERT(m_Lexers->Read()); *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName("test.h")).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByName("cpp").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->Count() > 0); CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty()); CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty()); CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty()); CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty()); CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty()); CPPUNIT_ASSERT(m_Lexer->IsKeyword("class")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("const")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("cla")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xxx")); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", true).empty()); CPPUNIT_ASSERT(m_Lexer->UsableCharactersPerLine() == 74); // 80 - 4 (comments) - 2 (spaces) // test exRCS CPPUNIT_ASSERT(m_RCS->GetAuthor().empty()); CPPUNIT_ASSERT(m_RCS->GetDescription().empty()); CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test exStat CPPUNIT_ASSERT(!m_Stat->IsLink()); CPPUNIT_ASSERT(m_Stat->IsOk()); CPPUNIT_ASSERT(!m_Stat->IsReadOnly()); CPPUNIT_ASSERT(m_Stat->Update("testlink")); // CPPUNIT_ASSERT(m_Stat->IsLink()); // test exStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test exTextFile CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); // do the same test CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_HEADER)); CPPUNIT_ASSERT(m_TextFile->GetTool().GetId() == ID_TOOL_REPORT_HEADER); //wxLogMessage(m_TextFile->GetStatistics().Get() + m_TextFile->GetRCS().GetDescription()); // CPPUNIT_ASSERT(m_TextFile->GetRCS().GetDescription() == // "Declaration of classes for wxextension cpp unit testing"); CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_KEYWORD)); // CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty()); // test exTool CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0); } void exTestFixture::testTiming() { exFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { wxString* buffer = file.Read(); CPPUNIT_ASSERT(buffer != NULL); delete buffer; } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "exFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void exTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const exFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void exTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { m_Config->Get("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { m_Config->Read("test", 0l); } const long config = sw.Time(); printf( "exConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void exTestFixture::tearDown() { } void exAppTestFixture::setUp() { m_Dir = new exDir("./"); m_Grid = new exGrid(wxTheApp->GetTopWindow()); m_ListView = new exListView(wxTheApp->GetTopWindow()); m_STC = new exSTC(wxTheApp->GetTopWindow(), exFileName("test.h")); m_STCShell = new exSTCShell(wxTheApp->GetTopWindow()); m_SVN = new exSVN(SVN_STAT, "test.h"); } void exAppTestFixture::testConstructors() { } void exAppTestFixture::testMethods() { // test exApp CPPUNIT_ASSERT(exApp::GetConfig() != NULL); CPPUNIT_ASSERT(exApp::GetLexers() != NULL); CPPUNIT_ASSERT(exApp::GetPrinter() != NULL); // test exDir CPPUNIT_ASSERT(m_Dir->FindFiles() > 0); CPPUNIT_ASSERT(m_Dir->GetFiles().GetCount() > 0); // test exGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test exListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", exColumn::COL_STRING); m_ListView->InsertColumn("Number", exColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test exSTC CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h"); // test exSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history... // TODO: Make a better test. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // test exSVN CPPUNIT_ASSERT(m_SVN->GetInfo(false) == 0); // do not use a dialog // The contents depends on the svn stat, of course, // so do not assert on it. m_SVN->GetContents(); // test util CPPUNIT_ASSERT(exClipboardAdd("test")); CPPUNIT_ASSERT(exClipboardGet() == "test"); CPPUNIT_ASSERT(exGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(exGetLineNumberFromText("test on line: 1200") == 1200); CPPUNIT_ASSERT(exLog("hello from wxextension test")); CPPUNIT_ASSERT(!exMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(exMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(exSkipWhiteSpace("t es t") == "t es t"); } void exAppTestFixture::tearDown() { } exTestSuite::exTestSuite() : CppUnit::TestSuite("wxextension test suite") { #ifndef APP_TEST // Add the tests. addTest(new CppUnit::TestCaller<exTestFixture>( "testConstructors", &exTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exTestFixture>( "testMethods", &exTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTiming", &exTestFixture::testTiming)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingAttrib", &exTestFixture::testTimingAttrib)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingConfig", &exTestFixture::testTimingConfig)); #else addTest(new CppUnit::TestCaller<exAppTestFixture>( "testConstructors", &exAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testMethods", &exAppTestFixture::testMethods)); #endif } <commit_msg>added tests for syncing<commit_after>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void exTestFixture::setUp() { m_Config = new exConfig("test.cfg", wxCONFIG_USE_LOCAL_FILE); m_File = new exFile("test.h"); m_FileName = new exFileName("test.h"); m_FileNameStatistics = new exFileNameStatistics("test.h"); m_Lexer = new exLexer(); m_Lexers = new exLexers(exFileName("../data/lexers.xml")); m_RCS = new exRCS(); m_Stat = new exStat("test.h"); m_Statistics = new exStatistics<long>(); m_TextFile = new exTextFile(exFileName("test.h"), m_Config, m_Lexers); m_Tool = new exTool(ID_TOOL_REPORT_COUNT); } void exTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void exTestFixture::testMethods() { // test exConfig CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val"); CPPUNIT_ASSERT(m_Config->Get("keylong", 12) == 12); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true)); CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL); m_Config->Set("keystring", "val2"); CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val2"); m_Config->Set("keylong", 15); CPPUNIT_ASSERT(m_Config->Get("keylong", 7) == 15); m_Config->SetBool("keybool", false); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true) == false); m_Config->Toggle("keybool"); CPPUNIT_ASSERT(m_Config->GetBool("keybool", false)); // test exFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetStat().GetFullPath() == m_File->GetFileName().GetFullPath()); // The fullpath should be normalized, test it. CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() != "test.h"); CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly()); CPPUNIT_ASSERT(!m_File->CheckSyncNeeded()); CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly()); // test exFileName CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty()); CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); m_FileName->Assign("xxx"); m_FileName->GetStat().Update("xxx"); CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk()); // test exFileNameStatistics CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty()); CPPUNIT_ASSERT(m_FileNameStatistics->Get("xx") == 0); // test exLexer *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers m_Lexer->SetKeywords("test11 test21:1 test31:1 test12:2 test22:2"); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test11")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test21")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test12")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test22")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("te")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xx")); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); // test exLexers CPPUNIT_ASSERT(m_Lexers->Read()); *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName("test.h")).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByName("cpp").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->Count() > 0); CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty()); CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty()); CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty()); CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty()); CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty()); CPPUNIT_ASSERT(m_Lexer->IsKeyword("class")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("const")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("cla")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xxx")); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", true).empty()); CPPUNIT_ASSERT(m_Lexer->UsableCharactersPerLine() == 74); // 80 - 4 (comments) - 2 (spaces) // test exRCS CPPUNIT_ASSERT(m_RCS->GetAuthor().empty()); CPPUNIT_ASSERT(m_RCS->GetDescription().empty()); CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test exStat CPPUNIT_ASSERT(!m_Stat->IsLink()); CPPUNIT_ASSERT(m_Stat->IsOk()); CPPUNIT_ASSERT(!m_Stat->IsReadOnly()); CPPUNIT_ASSERT(m_Stat->Update("testlink")); // CPPUNIT_ASSERT(m_Stat->IsLink()); // test exStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test exTextFile CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); // do the same test CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_HEADER)); CPPUNIT_ASSERT(m_TextFile->GetTool().GetId() == ID_TOOL_REPORT_HEADER); //wxLogMessage(m_TextFile->GetStatistics().Get() + m_TextFile->GetRCS().GetDescription()); // CPPUNIT_ASSERT(m_TextFile->GetRCS().GetDescription() == // "Declaration of classes for wxextension cpp unit testing"); CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_KEYWORD)); // CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty()); // test exTool CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0); } void exTestFixture::testTiming() { exFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { wxString* buffer = file.Read(); CPPUNIT_ASSERT(buffer != NULL); delete buffer; } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "exFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void exTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const exFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void exTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { m_Config->Get("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { m_Config->Read("test", 0l); } const long config = sw.Time(); printf( "exConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void exTestFixture::tearDown() { } void exAppTestFixture::setUp() { m_Dir = new exDir("./"); m_Grid = new exGrid(wxTheApp->GetTopWindow()); m_ListView = new exListView(wxTheApp->GetTopWindow()); m_STC = new exSTC(wxTheApp->GetTopWindow(), exFileName("test.h")); m_STCShell = new exSTCShell(wxTheApp->GetTopWindow()); m_SVN = new exSVN(SVN_STAT, "test.h"); } void exAppTestFixture::testConstructors() { } void exAppTestFixture::testMethods() { // test exApp CPPUNIT_ASSERT(exApp::GetConfig() != NULL); CPPUNIT_ASSERT(exApp::GetLexers() != NULL); CPPUNIT_ASSERT(exApp::GetPrinter() != NULL); // test exDir CPPUNIT_ASSERT(m_Dir->FindFiles() > 0); CPPUNIT_ASSERT(m_Dir->GetFiles().GetCount() > 0); // test exGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test exListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", exColumn::COL_STRING); m_ListView->InsertColumn("Number", exColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test exSTC CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h"); // test exSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history... // TODO: Make a better test. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // test exSVN CPPUNIT_ASSERT(m_SVN->GetInfo(false) == 0); // do not use a dialog // The contents depends on the svn stat, of course, // so do not assert on it. m_SVN->GetContents(); // test util CPPUNIT_ASSERT(exClipboardAdd("test")); CPPUNIT_ASSERT(exClipboardGet() == "test"); CPPUNIT_ASSERT(exGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(exGetLineNumberFromText("test on line: 1200") == 1200); CPPUNIT_ASSERT(exLog("hello from wxextension test")); CPPUNIT_ASSERT(!exMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(exMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(exSkipWhiteSpace("t es t") == "t es t"); } void exAppTestFixture::tearDown() { } exTestSuite::exTestSuite() : CppUnit::TestSuite("wxextension test suite") { #ifndef APP_TEST // Add the tests. addTest(new CppUnit::TestCaller<exTestFixture>( "testConstructors", &exTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exTestFixture>( "testMethods", &exTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTiming", &exTestFixture::testTiming)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingAttrib", &exTestFixture::testTimingAttrib)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingConfig", &exTestFixture::testTimingConfig)); #else addTest(new CppUnit::TestCaller<exAppTestFixture>( "testConstructors", &exAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testMethods", &exAppTestFixture::testMethods)); #endif } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013-2015 SRS(ossrs) 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 <srs_app_log.hpp> #include <stdarg.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <srs_app_config.hpp> #include <srs_kernel_error.hpp> #include <srs_app_utility.hpp> #include <srs_kernel_utility.hpp> SrsThreadContext::SrsThreadContext() { } SrsThreadContext::~SrsThreadContext() { } int SrsThreadContext::generate_id() { static int id = 100; int gid = id++; cache[st_thread_self()] = gid; return gid; } int SrsThreadContext::get_id() { return cache[st_thread_self()]; } int SrsThreadContext::set_id(int v) { st_thread_t self = st_thread_self(); int ov = 0; if (cache.find(self) != cache.end()) { ov = cache[self]; } cache[self] = v; return ov; } void SrsThreadContext::clear_cid() { st_thread_t self = st_thread_self(); std::map<st_thread_t, int>::iterator it = cache.find(self); if (it != cache.end()) { cache.erase(it); } } // the max size of a line of log. #define LOG_MAX_SIZE 4096 // the tail append to each log. #define LOG_TAIL '\n' // reserved for the end of log data, it must be strlen(LOG_TAIL) #define LOG_TAIL_SIZE 1 SrsFastLog::SrsFastLog() { _level = SrsLogLevel::Trace; log_data = new char[LOG_MAX_SIZE]; fd = -1; log_to_file_tank = false; utc = false; } SrsFastLog::~SrsFastLog() { srs_freepa(log_data); if (fd > 0) { ::close(fd); fd = -1; } if (_srs_config) { _srs_config->unsubscribe(this); } } int SrsFastLog::initialize() { int ret = ERROR_SUCCESS; if (_srs_config) { _srs_config->subscribe(this); log_to_file_tank = _srs_config->get_log_tank_file(); _level = srs_get_log_level(_srs_config->get_log_level()); utc = _srs_config->get_utc_time(); } return ret; } void SrsFastLog::verbose(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Verbose) { return; } int size = 0; if (!generate_header(false, tag, context_id, "verb", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Verbose); } void SrsFastLog::info(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Info) { return; } int size = 0; if (!generate_header(false, tag, context_id, "debug", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Info); } void SrsFastLog::trace(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Trace) { return; } int size = 0; if (!generate_header(false, tag, context_id, "trace", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Trace); } void SrsFastLog::warn(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Warn) { return; } int size = 0; if (!generate_header(true, tag, context_id, "warn", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Warn); } void SrsFastLog::error(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Error) { return; } int size = 0; if (!generate_header(true, tag, context_id, "error", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); // add strerror() to error msg. if (errno != 0) { size += snprintf(log_data + size, LOG_MAX_SIZE - size, "(%s)", strerror(errno)); } write_log(fd, log_data, size, SrsLogLevel::Error); } int SrsFastLog::on_reload_utc_time() { utc = _srs_config->get_utc_time(); return ERROR_SUCCESS; } int SrsFastLog::on_reload_log_tank() { int ret = ERROR_SUCCESS; if (!_srs_config) { return ret; } bool tank = log_to_file_tank; log_to_file_tank = _srs_config->get_log_tank_file(); if (tank) { return ret; } if (!log_to_file_tank) { return ret; } if (fd > 0) { ::close(fd); } open_log_file(); return ret; } int SrsFastLog::on_reload_log_level() { int ret = ERROR_SUCCESS; if (!_srs_config) { return ret; } _level = srs_get_log_level(_srs_config->get_log_level()); return ret; } int SrsFastLog::on_reload_log_file() { int ret = ERROR_SUCCESS; if (!_srs_config) { return ret; } if (!log_to_file_tank) { return ret; } if (fd > 0) { ::close(fd); } open_log_file(); return ret; } bool SrsFastLog::generate_header(bool error, const char* tag, int context_id, const char* level_name, int* header_size) { // clock time timeval tv; if (gettimeofday(&tv, NULL) == -1) { return false; } // to calendar time struct tm* tm; if (utc) { if ((tm = gmtime(&tv.tv_sec)) == NULL) { return false; } } else { if ((tm = localtime(&tv.tv_sec)) == NULL) { return false; } } // write log header int log_header_size = -1; if (error) { if (tag) { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%s][%d][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, tag, getpid(), context_id, errno); } else { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%d][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, getpid(), context_id, errno); } } else { if (tag) { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%s][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, tag, getpid(), context_id); } else { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, getpid(), context_id); } } if (log_header_size == -1) { return false; } // write the header size. *header_size = srs_min(LOG_MAX_SIZE - 1, log_header_size); return true; } void SrsFastLog::write_log(int& fd, char *str_log, int size, int level) { // ensure the tail and EOF of string // LOG_TAIL_SIZE for the TAIL char. // 1 for the last char(0). size = srs_min(LOG_MAX_SIZE - 1 - LOG_TAIL_SIZE, size); // add some to the end of char. str_log[size++] = LOG_TAIL; // if not to file, to console and return. if (!log_to_file_tank) { // if is error msg, then print color msg. // \033[31m : red text code in shell // \033[32m : green text code in shell // \033[33m : yellow text code in shell // \033[0m : normal text code if (level <= SrsLogLevel::Trace) { printf("%.*s", size, str_log); } else if (level == SrsLogLevel::Warn) { printf("\033[33m%.*s\033[0m", size, str_log); } else{ printf("\033[31m%.*s\033[0m", size, str_log); } fflush(stdout); return; } // open log file. if specified if (fd < 0) { open_log_file(); } // write log to file. if (fd > 0) { ::write(fd, str_log, size); } } void SrsFastLog::open_log_file() { if (!_srs_config) { return; } std::string filename = _srs_config->get_log_file(); if (filename.empty()) { return; } fd = ::open(filename.c_str(), O_RDWR | O_APPEND); if(fd == -1 && errno == ENOENT) { fd = open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH ); } } <commit_msg>fix logrotate empty file hole issue (#1561)<commit_after>/* The MIT License (MIT) Copyright (c) 2013-2015 SRS(ossrs) 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 <srs_app_log.hpp> #include <stdarg.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <srs_app_config.hpp> #include <srs_kernel_error.hpp> #include <srs_app_utility.hpp> #include <srs_kernel_utility.hpp> SrsThreadContext::SrsThreadContext() { } SrsThreadContext::~SrsThreadContext() { } int SrsThreadContext::generate_id() { static int id = 100; int gid = id++; cache[st_thread_self()] = gid; return gid; } int SrsThreadContext::get_id() { return cache[st_thread_self()]; } int SrsThreadContext::set_id(int v) { st_thread_t self = st_thread_self(); int ov = 0; if (cache.find(self) != cache.end()) { ov = cache[self]; } cache[self] = v; return ov; } void SrsThreadContext::clear_cid() { st_thread_t self = st_thread_self(); std::map<st_thread_t, int>::iterator it = cache.find(self); if (it != cache.end()) { cache.erase(it); } } // the max size of a line of log. #define LOG_MAX_SIZE 4096 // the tail append to each log. #define LOG_TAIL '\n' // reserved for the end of log data, it must be strlen(LOG_TAIL) #define LOG_TAIL_SIZE 1 SrsFastLog::SrsFastLog() { _level = SrsLogLevel::Trace; log_data = new char[LOG_MAX_SIZE]; fd = -1; log_to_file_tank = false; utc = false; } SrsFastLog::~SrsFastLog() { srs_freepa(log_data); if (fd > 0) { ::close(fd); fd = -1; } if (_srs_config) { _srs_config->unsubscribe(this); } } int SrsFastLog::initialize() { int ret = ERROR_SUCCESS; if (_srs_config) { _srs_config->subscribe(this); log_to_file_tank = _srs_config->get_log_tank_file(); _level = srs_get_log_level(_srs_config->get_log_level()); utc = _srs_config->get_utc_time(); } return ret; } void SrsFastLog::verbose(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Verbose) { return; } int size = 0; if (!generate_header(false, tag, context_id, "verb", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Verbose); } void SrsFastLog::info(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Info) { return; } int size = 0; if (!generate_header(false, tag, context_id, "debug", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Info); } void SrsFastLog::trace(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Trace) { return; } int size = 0; if (!generate_header(false, tag, context_id, "trace", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Trace); } void SrsFastLog::warn(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Warn) { return; } int size = 0; if (!generate_header(true, tag, context_id, "warn", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); write_log(fd, log_data, size, SrsLogLevel::Warn); } void SrsFastLog::error(const char* tag, int context_id, const char* fmt, ...) { if (_level > SrsLogLevel::Error) { return; } int size = 0; if (!generate_header(true, tag, context_id, "error", &size)) { return; } va_list ap; va_start(ap, fmt); // we reserved 1 bytes for the new line. size += vsnprintf(log_data + size, LOG_MAX_SIZE - size, fmt, ap); va_end(ap); // add strerror() to error msg. if (errno != 0) { size += snprintf(log_data + size, LOG_MAX_SIZE - size, "(%s)", strerror(errno)); } write_log(fd, log_data, size, SrsLogLevel::Error); } int SrsFastLog::on_reload_utc_time() { utc = _srs_config->get_utc_time(); return ERROR_SUCCESS; } int SrsFastLog::on_reload_log_tank() { int ret = ERROR_SUCCESS; if (!_srs_config) { return ret; } bool tank = log_to_file_tank; log_to_file_tank = _srs_config->get_log_tank_file(); if (tank) { return ret; } if (!log_to_file_tank) { return ret; } if (fd > 0) { ::close(fd); } open_log_file(); return ret; } int SrsFastLog::on_reload_log_level() { int ret = ERROR_SUCCESS; if (!_srs_config) { return ret; } _level = srs_get_log_level(_srs_config->get_log_level()); return ret; } int SrsFastLog::on_reload_log_file() { int ret = ERROR_SUCCESS; if (!_srs_config) { return ret; } if (!log_to_file_tank) { return ret; } if (fd > 0) { ::close(fd); } open_log_file(); return ret; } bool SrsFastLog::generate_header(bool error, const char* tag, int context_id, const char* level_name, int* header_size) { // clock time timeval tv; if (gettimeofday(&tv, NULL) == -1) { return false; } // to calendar time struct tm* tm; if (utc) { if ((tm = gmtime(&tv.tv_sec)) == NULL) { return false; } } else { if ((tm = localtime(&tv.tv_sec)) == NULL) { return false; } } // write log header int log_header_size = -1; if (error) { if (tag) { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%s][%d][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, tag, getpid(), context_id, errno); } else { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%d][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, getpid(), context_id, errno); } } else { if (tag) { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%s][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, tag, getpid(), context_id); } else { log_header_size = snprintf(log_data, LOG_MAX_SIZE, "[%d-%02d-%02d %02d:%02d:%02d.%03d][%s][%d][%d] ", 1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec / 1000), level_name, getpid(), context_id); } } if (log_header_size == -1) { return false; } // write the header size. *header_size = srs_min(LOG_MAX_SIZE - 1, log_header_size); return true; } void SrsFastLog::write_log(int& fd, char *str_log, int size, int level) { // ensure the tail and EOF of string // LOG_TAIL_SIZE for the TAIL char. // 1 for the last char(0). size = srs_min(LOG_MAX_SIZE - 1 - LOG_TAIL_SIZE, size); // add some to the end of char. str_log[size++] = LOG_TAIL; // if not to file, to console and return. if (!log_to_file_tank) { // if is error msg, then print color msg. // \033[31m : red text code in shell // \033[32m : green text code in shell // \033[33m : yellow text code in shell // \033[0m : normal text code if (level <= SrsLogLevel::Trace) { printf("%.*s", size, str_log); } else if (level == SrsLogLevel::Warn) { printf("\033[33m%.*s\033[0m", size, str_log); } else{ printf("\033[31m%.*s\033[0m", size, str_log); } fflush(stdout); return; } // open log file. if specified if (fd < 0) { open_log_file(); } // write log to file. if (fd > 0) { ::write(fd, str_log, size); } } void SrsFastLog::open_log_file() { if (!_srs_config) { return; } std::string filename = _srs_config->get_log_file(); if (filename.empty()) { return; } fd = ::open(filename.c_str(), O_RDWR | O_APPEND); if(fd == -1 && errno == ENOENT) { fd = open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_APPEND/*logrotate copytruncate need this flag*/, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH ); } } <|endoftext|>
<commit_before>// Halide tutorial lesson 1. // This lesson demonstrates basic usage of Halide as a JIT compiler for imaging. // This lesson can be built by invoking the command: // make tutorial_lesson_01_basics // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_01 // LD_LIBRARY_PATH=../bin ./lesson_01 // On os x: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -o lesson_01 // DYLD_LIBRARY_PATH=../bin ./lesson_01 // The only Halide header file you need is Halide.h. It includes all of Halide. #include "Halide.h" // We'll also include stdio for printf. #include <stdio.h> int main(int argc, char **argv) { // This program defines a single-stage imaging pipeline that // outputs a grayscale diagonal gradient. // A 'Func' object represents a pipeline stage. It's a pure // function that defines what value each pixel should have. You // can think of it as a computed image. Halide::Func gradient; // Var objects are names to use as variables in the definition of // a Func. They have no meaning by themselves. Halide::Var x, y; // We typically use Vars named 'x' and 'y' to correspond to the x // and y axes of an image, and we write them in that order. If // you're used to thinking of images as having rows and columns, // then x is the column index, and y is the row index. // Funcs are defined at any integer coordinate of its variables as // an Expr in terms of those variables and other functions. // Here, we'll define an Expr which has the value x + y. Vars have // appropriate operator overloading so that expressions like // 'x + y' become 'Expr' objects. Halide::Expr e = x + y; // Now we'll add a definition for the Func object. At pixel x, y, // the image will have the value of the Expr e. On the left hand // side we have the Func we're defining and some Vars. On the right // hand side we have some Expr object that uses those same Vars. gradient(x, y) = e; // This is the same as writing: // // gradient(x, y) = x + y; // // which is the more common form, but we are showing the // intermediate Expr here for completeness. // That line of code defined the Func, but it didn't actually // compute the output image yet. At this stage it's just Funcs, // Exprs, and Vars in memory, representing the structure of our // imaging pipeline. We're meta-programming. This C++ program is // constructing a Halide program in memory. Actually computing // pixel data comes next. // Now we 'realize' the Func, which JIT compiles some code that // implements the pipeline we've defined, and then runs it. We // also need to tell Halide the domain over which to evaluate the // Func, which determines the range of x and y above, and the // resolution of the output image. Halide.h also provides a basic // templatized Image type we can use. We'll make an 800 x 600 // image. Halide::Image<int32_t> output = gradient.realize(800, 600); // Halide does type inference for you. Var objects represent // 32-bit integers, so the Expr object 'x + y' also represents a // 32-bit integer, and so 'gradient' defines a 32-bit image, and // so we got a 32-bit signed integer image out when we call // 'realize'. Halide types and type-casting rules are equivalent // to C. // Let's check everything worked, and we got the output we were // expecting: for (int j = 0; j < output.height(); j++) { for (int i = 0; i < output.width(); i++) { // We can access a pixel of an Image object using similar // syntax to defining and using functions. if (output(i, j) != i + j) { printf("Something went wrong!\n" "Pixel %d, %d was supposed to be %d, but instead it's %d\n", i, j, i+j, output(i, j)); return -1; } } } // Everything worked! We defined a Func, then called 'realize' on // it to generate and run machine code that produced an Image. printf("Success!\n"); return 0; } <commit_msg>Update lesson_01_basics.cpp<commit_after>// Halide tutorial lesson 1. // This lesson demonstrates basic usage of Halide as a JIT compiler for imaging. // This lesson can be built by invoking the command: // make tutorial_lesson_01_basics // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_01 -std=c++1 // LD_LIBRARY_PATH=../bin ./lesson_01 // On os x: // g++ lesson_01*.cpp -g -I ../include -L ../bin -lHalide -o lesson_01 // DYLD_LIBRARY_PATH=../bin ./lesson_01 // The only Halide header file you need is Halide.h. It includes all of Halide. #include "Halide.h" // We'll also include stdio for printf. #include <stdio.h> int main(int argc, char **argv) { // This program defines a single-stage imaging pipeline that // outputs a grayscale diagonal gradient. // A 'Func' object represents a pipeline stage. It's a pure // function that defines what value each pixel should have. You // can think of it as a computed image. Halide::Func gradient; // Var objects are names to use as variables in the definition of // a Func. They have no meaning by themselves. Halide::Var x, y; // We typically use Vars named 'x' and 'y' to correspond to the x // and y axes of an image, and we write them in that order. If // you're used to thinking of images as having rows and columns, // then x is the column index, and y is the row index. // Funcs are defined at any integer coordinate of its variables as // an Expr in terms of those variables and other functions. // Here, we'll define an Expr which has the value x + y. Vars have // appropriate operator overloading so that expressions like // 'x + y' become 'Expr' objects. Halide::Expr e = x + y; // Now we'll add a definition for the Func object. At pixel x, y, // the image will have the value of the Expr e. On the left hand // side we have the Func we're defining and some Vars. On the right // hand side we have some Expr object that uses those same Vars. gradient(x, y) = e; // This is the same as writing: // // gradient(x, y) = x + y; // // which is the more common form, but we are showing the // intermediate Expr here for completeness. // That line of code defined the Func, but it didn't actually // compute the output image yet. At this stage it's just Funcs, // Exprs, and Vars in memory, representing the structure of our // imaging pipeline. We're meta-programming. This C++ program is // constructing a Halide program in memory. Actually computing // pixel data comes next. // Now we 'realize' the Func, which JIT compiles some code that // implements the pipeline we've defined, and then runs it. We // also need to tell Halide the domain over which to evaluate the // Func, which determines the range of x and y above, and the // resolution of the output image. Halide.h also provides a basic // templatized Image type we can use. We'll make an 800 x 600 // image. Halide::Image<int32_t> output = gradient.realize(800, 600); // Halide does type inference for you. Var objects represent // 32-bit integers, so the Expr object 'x + y' also represents a // 32-bit integer, and so 'gradient' defines a 32-bit image, and // so we got a 32-bit signed integer image out when we call // 'realize'. Halide types and type-casting rules are equivalent // to C. // Let's check everything worked, and we got the output we were // expecting: for (int j = 0; j < output.height(); j++) { for (int i = 0; i < output.width(); i++) { // We can access a pixel of an Image object using similar // syntax to defining and using functions. if (output(i, j) != i + j) { printf("Something went wrong!\n" "Pixel %d, %d was supposed to be %d, but instead it's %d\n", i, j, i+j, output(i, j)); return -1; } } } // Everything worked! We defined a Func, then called 'realize' on // it to generate and run machine code that produced an Image. printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>// Halide tutorial lesson 13: Tuples // This lesson describes how to write Funcs that evaluate to multiple // values. // On linux, you can compile and run it like so: // g++ lesson_13*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_13 -std=c++11 // LD_LIBRARY_PATH=../bin ./lesson_13 // On os x: // g++ lesson_13*.cpp -g -I ../include -L ../bin -lHalide -o lesson_13 -std=c++11 // DYLD_LIBRARY_PATH=../bin ./lesson_13 // If you have the entire Halide source tree, you can also build it by // running: // make tutorial_lesson_13_tuples // in a shell with the current directory at the top of the halide // source tree. #include "Halide.h" #include <stdio.h> #include <algorithm> using namespace Halide; int main(int argc, char **argv) { // So far Funcs (such as the one below) have evaluated to a single // scalar value for each point in their domain. Func single_valued; Var x, y; single_valued(x, y) = x + y; // One way to write a Func that returns a collection of values is // to add an additional dimension that indexes that // collection. This is how we typically deal with color. For // example, the Func below represents a collection of three values // for every x, y coordinate indexed by c. Func color_image; Var c; color_image(x, y, c) = select(c == 0, 245, // Red value c == 1, 42, // Green value 132); // Blue value // This method is often convenient because it makes it easy to // operate on this Func in a way that treats each item in the // collection equally: Func brighter; brighter(x, y, c) = color_image(x, y, c) + 10; // However this method is also inconvenient for three reasons. // // 1) Funcs are defined over an infinite domain, so users of this // Func can for example access color_image(x, y, -17), which is // not a meaningful value and is probably indicative of a bug. // // 2) It requires a select, which can impact performance if not // bounded and unrolled: // brighter.bound(c, 0, 3).unroll(c); // // 3) With this method, all values in the collection must have the // same type. While the above two issues are merely inconvenient, // this one is a hard limitation that makes it impossible to // express certain things in this way. // It is also possible to represent a collection of values as a // collection of Funcs: Func func_array[3]; func_array[0](x, y) = x + y; func_array[1](x, y) = sin(x); func_array[2](x, y) = cos(y); // This method avoids the three problems above, but introduces a // new annoyance. Because these are separate Funcs, it is // difficult to schedule them so that they are all computed // together inside a single loop over x, y. // A third alternative is to define a Func as evaluating to a // Tuple instead of an Expr. A Tuple is a fixed-size collection of // Exprs. Each Expr in a Tuple may have a different type. The // following function evaluates to an integer value (x+y), and a // floating point value (sin(x*y)). Func multi_valued; multi_valued(x, y) = Tuple(x + y, sin(x * y)); // Realizing a tuple-valued Func returns a collection of // Buffers. We call this a Realization. It's equivalent to a // std::vector of Buffer objects: { Realization r = multi_valued.realize(80, 60); assert(r.size() == 2); Buffer<int> im0 = r[0]; Buffer<float> im1 = r[1]; assert(im0(30, 40) == 30 + 40); assert(im1(30, 40) == sinf(30 * 40)); } // All Tuple elements are evaluated together over the same domain // in the same loop nest, but stored in distinct allocations. The // equivalent C++ code to the above is: { int multi_valued_0[80*60]; float multi_valued_1[80*60]; for (int y = 0; y < 80; y++) { for (int x = 0; x < 60; x++) { multi_valued_0[x + 60*y] = x + y; multi_valued_1[x + 60*y] = sinf(x*y); } } } // When compiling ahead-of-time, a Tuple-valued Func evaluates // into multiple distinct output buffer_t structs. These appear in // order at the end of the function signature: // int multi_valued(...input buffers and params..., // buffer_t *output_1, buffer_t *output_2); // You can construct a Tuple by passing multiple Exprs to the // Tuple constructor as we did above. Perhaps more elegantly, you // can also take advantage of C++11 initializer lists and just // enclose your Exprs in braces: Func multi_valued_2; multi_valued_2(x, y) = {x + y, sin(x*y)}; // Calls to a multi-valued Func cannot be treated as Exprs. The // following is a syntax error: // Func consumer; // consumer(x, y) = multi_valued_2(x, y) + 10; // Instead you must index a Tuple with square brackets to retrieve // the individual Exprs: Expr integer_part = multi_valued_2(x, y)[0]; Expr floating_part = multi_valued_2(x, y)[1]; Func consumer; consumer(x, y) = {integer_part + 10, floating_part + 10.0f}; // Tuple reductions. { // Tuples are particularly useful in reductions, as they allow // the reduction to maintain complex state as it walks along // its domain. The simplest example is an argmax. // First we create a Buffer to take the argmax over. Func input_func; input_func(x) = sin(x); Buffer<float> input = input_func.realize(100); // Then we define a 2-valued Tuple which tracks the index of // the maximum value and the value itself. Func arg_max; // Pure definition. arg_max() = {0, input(0)}; // Update definition. RDom r(1, 99); Expr old_index = arg_max()[0]; Expr old_max = arg_max()[1]; Expr new_index = select(old_max < input(r), r, old_index); Expr new_max = max(input(r), old_max); arg_max() = {new_index, new_max}; // The equivalent C++ is: int arg_max_0 = 0; float arg_max_1 = input(0); for (int r = 1; r < 100; r++) { int old_index = arg_max_0; float old_max = arg_max_1; int new_index = old_max < input(r) ? r : old_index; float new_max = std::max(input(r), old_max); // In a tuple update definition, all loads and computation // are done before any stores, so that all Tuple elements // are updated atomically with respect to recursive calls // to the same Func. arg_max_0 = new_index; arg_max_1 = new_max; } // Let's verify that the Halide and C++ found the same maximum // value and index. { Realization r = arg_max.realize(); Buffer<int> r0 = r[0]; Buffer<float> r1 = r[1]; assert(arg_max_0 == r0(0)); assert(arg_max_1 == r1(0)); } // Halide provides argmax and argmin as built-in reductions // similar to sum, product, maximum, and minimum. They return // a Tuple consisting of the point in the reduction domain // corresponding to that value, and the value itself. In the // case of ties they return the first value found. We'll use // one of these in the following section. } // Tuples for user-defined types. { // Tuples can also be a convenient way to represent compound // objects such as complex numbers. Defining an object that // can be converted to and from a Tuple is one way to extend // Halide's type system with user-defined types. struct Complex { Expr real, imag; // Construct from a Tuple Complex(Tuple t) : real(t[0]), imag(t[1]) {} // Construct from a pair of Exprs Complex(Expr r, Expr i) : real(r), imag(i) {} // Construct from a call to a Func by treating it as a Tuple Complex(FuncRef t) : Complex(Tuple(t)) {} // Convert to a Tuple operator Tuple() const { return {real, imag}; } // Complex addition Complex operator+(const Complex &other) const { return {real + other.real, imag + other.imag}; } // Complex multiplication Complex operator*(const Complex &other) const { return {real * other.real - imag * other.imag, real * other.imag + imag * other.real}; } // Complex magnitude Expr magnitude() const { return real * real + imag * imag; } // Other complex operators would go here. The above are // sufficient for this example. }; // Let's use the Complex struct to compute a Mandelbrot set. Func mandelbrot; // The initial complex value corresponding to an x, y coordinate // in our Func. Complex initial(x/15.0f - 2.5f, y/6.0f - 2.0f); // Pure definition. Var t; mandelbrot(x, y, t) = Complex(0.0f, 0.0f); // We'll use an update definition to take 12 steps. RDom r(1, 12); Complex current = mandelbrot(x, y, r-1); // The following line uses the complex multiplication and // addition we defined above. mandelbrot(x, y, r) = current*current + initial; // We'll use another tuple reduction to compute the iteration // number where the value first escapes a circle of radius 4. // This can be expressed as an argmin of a boolean - we want // the index of the first time the given boolean expression is // false (we consider false to be less than true). The argmax // would return the index of the first time the expression is // true. Expr escape_condition = Complex(mandelbrot(x, y, r)).magnitude() < 16.0f; Tuple first_escape = argmin(escape_condition); // We only want the index, not the value, but argmin returns // both, so we'll index the argmin Tuple expression using // square brackets to get the Expr representing the index. Func escape; escape(x, y) = first_escape[0]; // Realize the pipeline and print the result as ascii art. Buffer<int> result = escape.realize(61, 25); const char *code = " .:-~*={}&%#@"; for (int y = 0; y < result.height(); y++) { for (int x = 0; x < result.width(); x++) { printf("%c", code[result(x, y)]); } printf("\n"); } } printf("Success!\n"); return 0; } <commit_msg>Fix https://github.com/halide/Halide/issues/2199 .<commit_after>// Halide tutorial lesson 13: Tuples // This lesson describes how to write Funcs that evaluate to multiple // values. // On linux, you can compile and run it like so: // g++ lesson_13*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_13 -std=c++11 // LD_LIBRARY_PATH=../bin ./lesson_13 // On os x: // g++ lesson_13*.cpp -g -I ../include -L ../bin -lHalide -o lesson_13 -std=c++11 // DYLD_LIBRARY_PATH=../bin ./lesson_13 // If you have the entire Halide source tree, you can also build it by // running: // make tutorial_lesson_13_tuples // in a shell with the current directory at the top of the halide // source tree. #include "Halide.h" #include <stdio.h> #include <algorithm> using namespace Halide; int main(int argc, char **argv) { // So far Funcs (such as the one below) have evaluated to a single // scalar value for each point in their domain. Func single_valued; Var x, y; single_valued(x, y) = x + y; // One way to write a Func that returns a collection of values is // to add an additional dimension that indexes that // collection. This is how we typically deal with color. For // example, the Func below represents a collection of three values // for every x, y coordinate indexed by c. Func color_image; Var c; color_image(x, y, c) = select(c == 0, 245, // Red value c == 1, 42, // Green value 132); // Blue value // This method is often convenient because it makes it easy to // operate on this Func in a way that treats each item in the // collection equally: Func brighter; brighter(x, y, c) = color_image(x, y, c) + 10; // However this method is also inconvenient for three reasons. // // 1) Funcs are defined over an infinite domain, so users of this // Func can for example access color_image(x, y, -17), which is // not a meaningful value and is probably indicative of a bug. // // 2) It requires a select, which can impact performance if not // bounded and unrolled: // brighter.bound(c, 0, 3).unroll(c); // // 3) With this method, all values in the collection must have the // same type. While the above two issues are merely inconvenient, // this one is a hard limitation that makes it impossible to // express certain things in this way. // It is also possible to represent a collection of values as a // collection of Funcs: Func func_array[3]; func_array[0](x, y) = x + y; func_array[1](x, y) = sin(x); func_array[2](x, y) = cos(y); // This method avoids the three problems above, but introduces a // new annoyance. Because these are separate Funcs, it is // difficult to schedule them so that they are all computed // together inside a single loop over x, y. // A third alternative is to define a Func as evaluating to a // Tuple instead of an Expr. A Tuple is a fixed-size collection of // Exprs. Each Expr in a Tuple may have a different type. The // following function evaluates to an integer value (x+y), and a // floating point value (sin(x*y)). Func multi_valued; multi_valued(x, y) = Tuple(x + y, sin(x * y)); // Realizing a tuple-valued Func returns a collection of // Buffers. We call this a Realization. It's equivalent to a // std::vector of Buffer objects: { Realization r = multi_valued.realize(80, 60); assert(r.size() == 2); Buffer<int> im0 = r[0]; Buffer<float> im1 = r[1]; assert(im0(30, 40) == 30 + 40); assert(im1(30, 40) == sinf(30 * 40)); } // All Tuple elements are evaluated together over the same domain // in the same loop nest, but stored in distinct allocations. The // equivalent C++ code to the above is: { int multi_valued_0[80*60]; float multi_valued_1[80*60]; for (int y = 0; y < 80; y++) { for (int x = 0; x < 60; x++) { multi_valued_0[x + 60*y] = x + y; multi_valued_1[x + 60*y] = sinf(x*y); } } } // When compiling ahead-of-time, a Tuple-valued Func evaluates // into multiple distinct output buffer_t structs. These appear in // order at the end of the function signature: // int multi_valued(...input buffers and params..., // buffer_t *output_1, buffer_t *output_2); // You can construct a Tuple by passing multiple Exprs to the // Tuple constructor as we did above. Perhaps more elegantly, you // can also take advantage of C++11 initializer lists and just // enclose your Exprs in braces: Func multi_valued_2; multi_valued_2(x, y) = {x + y, sin(x*y)}; // Calls to a multi-valued Func cannot be treated as Exprs. The // following is a syntax error: // Func consumer; // consumer(x, y) = multi_valued_2(x, y) + 10; // Instead you must index a Tuple with square brackets to retrieve // the individual Exprs: Expr integer_part = multi_valued_2(x, y)[0]; Expr floating_part = multi_valued_2(x, y)[1]; Func consumer; consumer(x, y) = {integer_part + 10, floating_part + 10.0f}; // Tuple reductions. { // Tuples are particularly useful in reductions, as they allow // the reduction to maintain complex state as it walks along // its domain. The simplest example is an argmax. // First we create a Buffer to take the argmax over. Func input_func; input_func(x) = sin(x); Buffer<float> input = input_func.realize(100); // Then we define a 2-valued Tuple which tracks the index of // the maximum value and the value itself. Func arg_max; // Pure definition. arg_max() = {0, input(0)}; // Update definition. RDom r(1, 99); Expr old_index = arg_max()[0]; Expr old_max = arg_max()[1]; Expr new_index = select(old_max < input(r), r, old_index); Expr new_max = max(input(r), old_max); arg_max() = {new_index, new_max}; // The equivalent C++ is: int arg_max_0 = 0; float arg_max_1 = input(0); for (int r = 1; r < 100; r++) { int old_index = arg_max_0; float old_max = arg_max_1; int new_index = old_max < input(r) ? r : old_index; float new_max = std::max(input(r), old_max); // In a tuple update definition, all loads and computation // are done before any stores, so that all Tuple elements // are updated atomically with respect to recursive calls // to the same Func. arg_max_0 = new_index; arg_max_1 = new_max; } // Let's verify that the Halide and C++ found the same maximum // value and index. { Realization r = arg_max.realize(); Buffer<int> r0 = r[0]; Buffer<float> r1 = r[1]; assert(arg_max_0 == r0(0)); assert(arg_max_1 == r1(0)); } // Halide provides argmax and argmin as built-in reductions // similar to sum, product, maximum, and minimum. They return // a Tuple consisting of the point in the reduction domain // corresponding to that value, and the value itself. In the // case of ties they return the first value found. We'll use // one of these in the following section. } // Tuples for user-defined types. { // Tuples can also be a convenient way to represent compound // objects such as complex numbers. Defining an object that // can be converted to and from a Tuple is one way to extend // Halide's type system with user-defined types. struct Complex { Expr real, imag; // Construct from a Tuple Complex(Tuple t) : real(t[0]), imag(t[1]) {} // Construct from a pair of Exprs Complex(Expr r, Expr i) : real(r), imag(i) {} // Construct from a call to a Func by treating it as a Tuple Complex(FuncRef t) : Complex(Tuple(t)) {} // Convert to a Tuple operator Tuple() const { return {real, imag}; } // Complex addition Complex operator+(const Complex &other) const { return {real + other.real, imag + other.imag}; } // Complex multiplication Complex operator*(const Complex &other) const { return {real * other.real - imag * other.imag, real * other.imag + imag * other.real}; } // Complex magnitude, squared for efficiency Expr magnitude_squared() const { return real * real + imag * imag; } // Other complex operators would go here. The above are // sufficient for this example. }; // Let's use the Complex struct to compute a Mandelbrot set. Func mandelbrot; // The initial complex value corresponding to an x, y coordinate // in our Func. Complex initial(x/15.0f - 2.5f, y/6.0f - 2.0f); // Pure definition. Var t; mandelbrot(x, y, t) = Complex(0.0f, 0.0f); // We'll use an update definition to take 12 steps. RDom r(1, 12); Complex current = mandelbrot(x, y, r-1); // The following line uses the complex multiplication and // addition we defined above. mandelbrot(x, y, r) = current*current + initial; // We'll use another tuple reduction to compute the iteration // number where the value first escapes a circle of radius 4. // This can be expressed as an argmin of a boolean - we want // the index of the first time the given boolean expression is // false (we consider false to be less than true). The argmax // would return the index of the first time the expression is // true. Expr escape_condition = Complex(mandelbrot(x, y, r)).magnitude_squared() < 16.0f; Tuple first_escape = argmin(escape_condition); // We only want the index, not the value, but argmin returns // both, so we'll index the argmin Tuple expression using // square brackets to get the Expr representing the index. Func escape; escape(x, y) = first_escape[0]; // Realize the pipeline and print the result as ascii art. Buffer<int> result = escape.realize(61, 25); const char *code = " .:-~*={}&%#@"; for (int y = 0; y < result.height(); y++) { for (int x = 0; x < result.width(); x++) { printf("%c", code[result(x, y)]); } printf("\n"); } } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "default.h" #include "distribution2d.h" #include "../common/tutorial/obj_loader.h" #include "../common/tutorial/xml_loader.h" #include "../common/image/image.h" namespace embree { /* name of the tutorial */ const char* tutorialName = "convert"; struct HeightField : public RefCount { HeightField (Ref<Image> texture, const BBox3fa& bounds) : texture(texture), bounds(bounds) {} const Vec3fa at(const size_t x, const size_t y) { const size_t width = texture->width; const size_t height = texture->height; const Color4 c = texture->get(x,y); const Vec2f p(x/(width-1),y/(height-1)); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return Vec3fa(px,py,pz); } const AffineSpace3fa get(Vec2f p) { const size_t width = texture->width; const size_t height = texture->height; const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1); const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1); const Color4 c = texture->get(x,y); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return AffineSpace3fa::translate(Vec3fa(px,py,pz)); } Ref<SceneGraph::Node> geometry() { OBJMaterial material(1.0f,Vec3fa(0.5f),Vec3fa(0.0f),1.0f); Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material); Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode); const size_t width = texture->width; const size_t height = texture->height; mesh->v.resize(height*width); for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) mesh->v[y*width+x] = at(x,y); mesh->triangles.resize(2*(height-1)*(width-1)); for (size_t y=0; y<height-1; y++) { for (size_t x=0; x<width-1; x++) { const size_t p00 = (y+0)*width+(x+0); const size_t p01 = (y+0)*width+(x+1); const size_t p10 = (y+1)*width+(x+0); const size_t p11 = (y+1)*width+(x+1); const size_t tri = y*(width-1)+x; mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(p00,p01,p10); mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(p01,p11,p10); } } return mesh.dynamicCast<SceneGraph::Node>(); } private: Ref<Image> texture; BBox3fa bounds; }; struct Instantiator : public RefCount { Instantiator(const Ref<HeightField>& heightField, const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N) : heightField(heightField), object(object), dist(nullptr), minDistance(minDistance), N(N) { /* create distribution */ size_t width = distribution->width; size_t height = distribution->height; float* values = new float[width*height]; for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) values[y*width+x] = luminance(distribution->get(x,y)); dist = new Distribution2D(values,width,height); delete values; } void instantiate(Ref<SceneGraph::GroupNode>& group) { for (size_t i=0; i<N; i++) { Vec2f r = Vec2f(random<float>(),random<float>()); Vec2f p = dist->sample(r); p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height)); const AffineSpace3fa space = heightField->get(p); group->add(new SceneGraph::TransformNode(space,object)); } } private: Ref<HeightField> heightField; Ref<SceneGraph::Node> object; Ref<Distribution2D> dist; float minDistance; size_t N; }; /* scene */ Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode; Ref<HeightField> g_height_field = nullptr; static void parseCommandLine(Ref<ParseStream> cin, const FileName& path) { while (true) { std::string tag = cin->getString(); if (tag == "") return; /* parse command line parameters from a file */ else if (tag == "-c") { FileName file = path + cin->getFileName(); parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path()); } /* load model */ else if (tag == "-i") { g_scene->add(SceneGraph::load(path + cin->getFileName())); } /* load terrain */ else if (tag == "-terrain") { Ref<Image> tex = loadImage(path + cin->getFileName()); const Vec3fa lower = cin->getVec3fa(); const Vec3fa upper = cin->getVec3fa(); g_height_field = new HeightField(tex,BBox3fa(lower,upper)); g_scene->add(g_height_field->geometry()); } /* instantiate model */ else if (tag == "-instantiate") { Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName()); Ref<Image> distribution = loadImage(path + cin->getFileName()); const float minDistance = cin->getFloat(); const size_t N = cin->getInt(); Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N); instantiator->instantiate(g_scene); } /* output filename */ else if (tag == "-o") { SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName()); } /* skip unknown command line parameter */ else { std::cerr << "unknown command line parameter: " << tag << " "; while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " "; std::cerr << std::endl; } } } /* main function in embree namespace */ int main(int argc, char** argv) { /* create stream for parsing */ Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv)); /* parse command line */ parseCommandLine(stream, FileName()); return 0; } } int main(int argc, char** argv) { try { return embree::main(argc, argv); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return 1; } catch (...) { std::cout << "Error: unknown exception caught." << std::endl; return 1; } } <commit_msg>bugfix in terrain tessellation<commit_after>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "default.h" #include "distribution2d.h" #include "../common/tutorial/obj_loader.h" #include "../common/tutorial/xml_loader.h" #include "../common/image/image.h" namespace embree { /* name of the tutorial */ const char* tutorialName = "convert"; struct HeightField : public RefCount { HeightField (Ref<Image> texture, const BBox3fa& bounds) : texture(texture), bounds(bounds) {} const Vec3fa at(const size_t x, const size_t y) { const size_t width = texture->width; const size_t height = texture->height; const Color4 c = texture->get(x,y); const Vec2f p(x/float(width-1),y/float(height-1)); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return Vec3fa(px,py,pz); } const AffineSpace3fa get(Vec2f p) { const size_t width = texture->width; const size_t height = texture->height; const size_t x = clamp((size_t)(p.x*(width-1)),(size_t)0,width-1); const size_t y = clamp((size_t)(p.y*(height-1)),(size_t)0,height-1); const Color4 c = texture->get(x,y); const float px = p.x*(bounds.upper.x-bounds.lower.x) + bounds.lower.x; const float py = c.r*(bounds.upper.y-bounds.lower.y) + bounds.lower.y; const float pz = p.y*(bounds.upper.z-bounds.lower.z) + bounds.lower.z; return AffineSpace3fa::translate(Vec3fa(px,py,pz)); } Ref<SceneGraph::Node> geometry() { OBJMaterial material(1.0f,Vec3fa(0.5f),Vec3fa(0.0f),1.0f); Ref<SceneGraph::MaterialNode> mnode = new SceneGraph::MaterialNode((Material&)material); Ref<SceneGraph::TriangleMeshNode> mesh = new SceneGraph::TriangleMeshNode(mnode); const size_t width = texture->width; const size_t height = texture->height; mesh->v.resize(height*width); for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) mesh->v[y*width+x] = at(x,y); mesh->triangles.resize(2*(height-1)*(width-1)); for (size_t y=0; y<height-1; y++) { for (size_t x=0; x<width-1; x++) { const size_t p00 = (y+0)*width+(x+0); const size_t p01 = (y+0)*width+(x+1); const size_t p10 = (y+1)*width+(x+0); const size_t p11 = (y+1)*width+(x+1); const size_t tri = y*(width-1)+x; mesh->triangles[2*tri+0] = SceneGraph::TriangleMeshNode::Triangle(p00,p01,p10); mesh->triangles[2*tri+1] = SceneGraph::TriangleMeshNode::Triangle(p01,p11,p10); } } return mesh.dynamicCast<SceneGraph::Node>(); } private: Ref<Image> texture; BBox3fa bounds; }; struct Instantiator : public RefCount { Instantiator(const Ref<HeightField>& heightField, const Ref<SceneGraph::Node>& object, const Ref<Image>& distribution, float minDistance, size_t N) : heightField(heightField), object(object), dist(nullptr), minDistance(minDistance), N(N) { /* create distribution */ size_t width = distribution->width; size_t height = distribution->height; float* values = new float[width*height]; for (size_t y=0; y<height; y++) for (size_t x=0; x<width; x++) values[y*width+x] = luminance(distribution->get(x,y)); dist = new Distribution2D(values,width,height); delete values; } void instantiate(Ref<SceneGraph::GroupNode>& group) { for (size_t i=0; i<N; i++) { Vec2f r = Vec2f(random<float>(),random<float>()); Vec2f p = dist->sample(r); p.x *= rcp(float(dist->width)); p.y *= rcp(float(dist->height)); const AffineSpace3fa space = heightField->get(p); group->add(new SceneGraph::TransformNode(space,object)); } } private: Ref<HeightField> heightField; Ref<SceneGraph::Node> object; Ref<Distribution2D> dist; float minDistance; size_t N; }; /* scene */ Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode; Ref<HeightField> g_height_field = nullptr; static void parseCommandLine(Ref<ParseStream> cin, const FileName& path) { while (true) { std::string tag = cin->getString(); if (tag == "") return; /* parse command line parameters from a file */ else if (tag == "-c") { FileName file = path + cin->getFileName(); parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path()); } /* load model */ else if (tag == "-i") { g_scene->add(SceneGraph::load(path + cin->getFileName())); } /* load terrain */ else if (tag == "-terrain") { Ref<Image> tex = loadImage(path + cin->getFileName()); const Vec3fa lower = cin->getVec3fa(); const Vec3fa upper = cin->getVec3fa(); g_height_field = new HeightField(tex,BBox3fa(lower,upper)); g_scene->add(g_height_field->geometry()); } /* instantiate model */ else if (tag == "-instantiate") { Ref<SceneGraph::Node> object = SceneGraph::load(path + cin->getFileName()); Ref<Image> distribution = loadImage(path + cin->getFileName()); const float minDistance = cin->getFloat(); const size_t N = cin->getInt(); Ref<Instantiator> instantiator = new Instantiator(g_height_field,object,distribution,minDistance,N); instantiator->instantiate(g_scene); } /* output filename */ else if (tag == "-o") { SceneGraph::store(g_scene.dynamicCast<SceneGraph::Node>(),path + cin->getFileName()); } /* skip unknown command line parameter */ else { std::cerr << "unknown command line parameter: " << tag << " "; while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " "; std::cerr << std::endl; } } } /* main function in embree namespace */ int main(int argc, char** argv) { /* create stream for parsing */ Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv)); /* parse command line */ parseCommandLine(stream, FileName()); return 0; } } int main(int argc, char** argv) { try { return embree::main(argc, argv); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return 1; } catch (...) { std::cout << "Error: unknown exception caught." << std::endl; return 1; } } <|endoftext|>
<commit_before>#define ProofNtuple_cxx ////////////////////////////////////////////////////////// // // Example of TSelector implementation to do generic // processing (filling a simple ntuple, in this case). // See tutorials/proof/runProof.C, option "ntuple", for an // example of how to run this selector. // ////////////////////////////////////////////////////////// #include "ProofNtuple.h" #include <TCanvas.h> #include <TFrame.h> #include <TPaveText.h> #include <TMath.h> #include <TNtuple.h> #include <TRandom3.h> #include <TROOT.h> #include <TString.h> #include <TStyle.h> #include <TSystem.h> #include <TFile.h> #include <TProofOutputFile.h> //_____________________________________________________________________________ ProofNtuple::~ProofNtuple() { // Destructor SafeDelete(fNtp); SafeDelete(fNtp2); SafeDelete(fFile); SafeDelete(fRandom); } //_____________________________________________________________________________ void ProofNtuple::PlotNtuple(TNtuple *ntp, const char *ntptitle) { // Make some plots from the ntuple 'ntp' // // Create a canvas, with 2 pads // TCanvas *c1 = new TCanvas(Form("cv-%s", ntp->GetName()), ntptitle,800,10,700,780); c1->Divide(1,2); TPad *pad1 = (TPad *) c1->GetPad(1); TPad *pad2 = (TPad *) c1->GetPad(2); // // Display a function of one ntuple column imposing a condition // on another column. pad1->cd(); pad1->SetGrid(); pad1->SetLogy(); pad1->GetFrame()->SetFillColor(15); ntp->SetLineColor(1); ntp->SetFillStyle(1001); ntp->SetFillColor(45); ntp->Draw("3*px+2","px**2+py**2>1"); ntp->SetFillColor(38); ntp->Draw("2*px+2","pz>2","same"); ntp->SetFillColor(5); ntp->Draw("1.3*px+2","(px^2+py^2>4) && py>0","same"); pad1->RedrawAxis(); // // Display a 3-D scatter plot of 3 columns. Superimpose a different selection. pad2->cd(); ntp->Draw("pz:py:px","(pz<10 && pz>6)+(pz<4 && pz>3)"); ntp->SetMarkerColor(4); ntp->Draw("pz:py:px","pz<6 && pz>4","same"); ntp->SetMarkerColor(5); ntp->Draw("pz:py:px","pz<4 && pz>3","same"); TPaveText *l2 = new TPaveText(0.,0.6,0.9,0.95); l2->SetFillColor(42); l2->SetTextAlign(12); l2->AddText("You can interactively rotate this view in 2 ways:"); l2->AddText(" - With the RotateCube in clicking in this pad"); l2->AddText(" - Selecting View with x3d in the View menu"); l2->Draw(); // Final update c1->cd(); c1->Update(); } //_____________________________________________________________________________ void ProofNtuple::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); TNamed *out = (TNamed *) fInput->FindObject("PROOF_NTUPLE_DONT_PLOT"); if (out) fPlotNtuple = kFALSE; } //_____________________________________________________________________________ void ProofNtuple::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); // We may be creating a dataset or a merge file: check it TNamed *nm = dynamic_cast<TNamed *>(fInput->FindObject("SimpleNtuple.root")); if (nm) { // Just create the object UInt_t opt = TProofOutputFile::kRegister | TProofOutputFile::kOverwrite | TProofOutputFile::kVerify; fProofFile = new TProofOutputFile("SimpleNtuple.root", TProofOutputFile::kDataset, opt, nm->GetTitle()); } else { // For the ntuple, we use the automatic file merging facility // Check if an output URL has been given TNamed *out = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE_LOCATION"); Info("SlaveBegin", "PROOF_OUTPUTFILE_LOCATION: %s", (out ? out->GetTitle() : "undef")); fProofFile = new TProofOutputFile("SimpleNtuple.root", (out ? out->GetTitle() : "M")); out = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE"); if (out) fProofFile->SetOutputFileName(out->GetTitle()); } // Open the file fFile = fProofFile->OpenFile("RECREATE"); if (fFile && fFile->IsZombie()) SafeDelete(fFile); // Cannot continue if (!fFile) { Info("SlaveBegin", "could not create '%s': instance is invalid!", fProofFile->GetName()); return; } // Now we create the ntuple fNtp = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i"); // File resident fNtp->SetDirectory(fFile); fNtp->AutoSave(); // Now we create the second ntuple fNtp2 = new TNtuple("ntuple2","Demo ntuple2","vx:vy:vz"); // File resident fNtp2->SetDirectory(fFile); fNtp2->AutoSave(); // Should we generate the random numbers or take them from the ntuple ? TNamed *unr = (TNamed *) fInput->FindObject("PROOF_USE_NTP_RNDM"); if (unr) { // Get the ntuple from the input list if (!(fNtpRndm = dynamic_cast<TNtuple *>(fInput->FindObject("NtpRndm")))) { Warning("SlaveBegin", "asked to use rndm ntuple but 'NtpRndm' not found in the" " input list! Using the random generator"); fInput->Print(); } else { Info("SlaveBegin", "taking randoms from input ntuple 'NtpRndm'"); } } // Init the random generator, if required if (!fNtpRndm) fRandom = new TRandom3(0); } //_____________________________________________________________________________ Bool_t ProofNtuple::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either ProofNtuple::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. if (!fNtp) return kTRUE; // Fill ntuple Float_t px, py, random; if (fNtpRndm) { // Get the entry Float_t *ar = fNtpRndm->GetArgs(); Long64_t ent = entry % fNtpRndm->GetEntries(); fNtpRndm->GetEntry(ent); random = ar[0]; px = (Float_t) TMath::ErfInverse((Double_t)(ar[1]*2 - 1.)) * TMath::Sqrt(2.); py = (Float_t) TMath::ErfInverse((Double_t)(ar[2]*2 - 1.)) * TMath::Sqrt(2.); } else if (fRandom) { fRandom->Rannor(px,py); random = fRandom->Rndm(); } else { Abort("no way to get random numbers! Stop processing", kAbortProcess); return kTRUE; } Float_t pz = px*px + py*py; Int_t i = (Int_t) entry; fNtp->Fill(px,py,pz,random,i); if (!fNtp2) return kTRUE; // The second ntuple Float_t vz = random * 2. - 1.; fNtp2->Fill(px,py,vz); return kTRUE; } //_____________________________________________________________________________ void ProofNtuple::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. // Write the ntuple to the file if (fFile) { if (!fNtp) { Error("SlaveTerminate", "'ntuple' is undefined!"); return; } Bool_t cleanup = kFALSE; TDirectory *savedir = gDirectory; if (fNtp->GetEntries() > 0) { fFile->cd(); fNtp->Write(); if (fNtp2 && fNtp2->GetEntries() > 0) fNtp2->Write(); fProofFile->Print(); fOutput->Add(fProofFile); } else { cleanup = kTRUE; } fNtp->SetDirectory(0); if (fNtp2) fNtp2->SetDirectory(0); gDirectory = savedir; fFile->Close(); // Cleanup, if needed if (cleanup) { TUrl uf(*(fFile->GetEndpointUrl())); SafeDelete(fFile); gSystem->Unlink(uf.GetFile()); SafeDelete(fProofFile); } } } //_____________________________________________________________________________ void ProofNtuple::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. // Do nothing is not requested (dataset creation run) if (!fPlotNtuple) return; // Get the ntuple from the file if ((fProofFile = dynamic_cast<TProofOutputFile*>(fOutput->FindObject("SimpleNtuple.root")))) { TString outputFile(fProofFile->GetOutputFileName()); TString outputName(fProofFile->GetName()); outputName += ".root"; Printf("outputFile: %s", outputFile.Data()); // Read the ntuple from the file fFile = TFile::Open(outputFile); if (fFile) { Printf("Managed to open file: %s", outputFile.Data()); fNtp = (TNtuple *) fFile->Get("ntuple"); } else { Error("Terminate", "could not open file: %s", outputFile.Data()); } if (!fFile) return; } else { Error("Terminate", "TProofOutputFile not found"); return; } // Plot ntuples if (fNtp) PlotNtuple(fNtp, "proof ntuple"); } <commit_msg>Make sure that there is only one copy of the ntuple in the output file<commit_after>#define ProofNtuple_cxx ////////////////////////////////////////////////////////// // // Example of TSelector implementation to do generic // processing (filling a simple ntuple, in this case). // See tutorials/proof/runProof.C, option "ntuple", for an // example of how to run this selector. // ////////////////////////////////////////////////////////// #include "ProofNtuple.h" #include <TCanvas.h> #include <TFrame.h> #include <TPaveText.h> #include <TMath.h> #include <TNtuple.h> #include <TRandom3.h> #include <TROOT.h> #include <TString.h> #include <TStyle.h> #include <TSystem.h> #include <TFile.h> #include <TProofOutputFile.h> //_____________________________________________________________________________ ProofNtuple::~ProofNtuple() { // Destructor SafeDelete(fNtp); SafeDelete(fNtp2); SafeDelete(fFile); SafeDelete(fRandom); } //_____________________________________________________________________________ void ProofNtuple::PlotNtuple(TNtuple *ntp, const char *ntptitle) { // Make some plots from the ntuple 'ntp' // // Create a canvas, with 2 pads // TCanvas *c1 = new TCanvas(Form("cv-%s", ntp->GetName()), ntptitle,800,10,700,780); c1->Divide(1,2); TPad *pad1 = (TPad *) c1->GetPad(1); TPad *pad2 = (TPad *) c1->GetPad(2); // // Display a function of one ntuple column imposing a condition // on another column. pad1->cd(); pad1->SetGrid(); pad1->SetLogy(); pad1->GetFrame()->SetFillColor(15); ntp->SetLineColor(1); ntp->SetFillStyle(1001); ntp->SetFillColor(45); ntp->Draw("3*px+2","px**2+py**2>1"); ntp->SetFillColor(38); ntp->Draw("2*px+2","pz>2","same"); ntp->SetFillColor(5); ntp->Draw("1.3*px+2","(px^2+py^2>4) && py>0","same"); pad1->RedrawAxis(); // // Display a 3-D scatter plot of 3 columns. Superimpose a different selection. pad2->cd(); ntp->Draw("pz:py:px","(pz<10 && pz>6)+(pz<4 && pz>3)"); ntp->SetMarkerColor(4); ntp->Draw("pz:py:px","pz<6 && pz>4","same"); ntp->SetMarkerColor(5); ntp->Draw("pz:py:px","pz<4 && pz>3","same"); TPaveText *l2 = new TPaveText(0.,0.6,0.9,0.95); l2->SetFillColor(42); l2->SetTextAlign(12); l2->AddText("You can interactively rotate this view in 2 ways:"); l2->AddText(" - With the RotateCube in clicking in this pad"); l2->AddText(" - Selecting View with x3d in the View menu"); l2->Draw(); // Final update c1->cd(); c1->Update(); } //_____________________________________________________________________________ void ProofNtuple::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); TNamed *out = (TNamed *) fInput->FindObject("PROOF_NTUPLE_DONT_PLOT"); if (out) fPlotNtuple = kFALSE; } //_____________________________________________________________________________ void ProofNtuple::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); // We may be creating a dataset or a merge file: check it TNamed *nm = dynamic_cast<TNamed *>(fInput->FindObject("SimpleNtuple.root")); if (nm) { // Just create the object UInt_t opt = TProofOutputFile::kRegister | TProofOutputFile::kOverwrite | TProofOutputFile::kVerify; fProofFile = new TProofOutputFile("SimpleNtuple.root", TProofOutputFile::kDataset, opt, nm->GetTitle()); } else { // For the ntuple, we use the automatic file merging facility // Check if an output URL has been given TNamed *out = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE_LOCATION"); Info("SlaveBegin", "PROOF_OUTPUTFILE_LOCATION: %s", (out ? out->GetTitle() : "undef")); fProofFile = new TProofOutputFile("SimpleNtuple.root", (out ? out->GetTitle() : "M")); out = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE"); if (out) fProofFile->SetOutputFileName(out->GetTitle()); } // Open the file fFile = fProofFile->OpenFile("RECREATE"); if (fFile && fFile->IsZombie()) SafeDelete(fFile); // Cannot continue if (!fFile) { Info("SlaveBegin", "could not create '%s': instance is invalid!", fProofFile->GetName()); return; } // Now we create the ntuple fNtp = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i"); // File resident fNtp->SetDirectory(fFile); fNtp->AutoSave(); // Now we create the second ntuple fNtp2 = new TNtuple("ntuple2","Demo ntuple2","vx:vy:vz"); // File resident fNtp2->SetDirectory(fFile); fNtp2->AutoSave(); // Should we generate the random numbers or take them from the ntuple ? TNamed *unr = (TNamed *) fInput->FindObject("PROOF_USE_NTP_RNDM"); if (unr) { // Get the ntuple from the input list if (!(fNtpRndm = dynamic_cast<TNtuple *>(fInput->FindObject("NtpRndm")))) { Warning("SlaveBegin", "asked to use rndm ntuple but 'NtpRndm' not found in the" " input list! Using the random generator"); fInput->Print(); } else { Info("SlaveBegin", "taking randoms from input ntuple 'NtpRndm'"); } } // Init the random generator, if required if (!fNtpRndm) fRandom = new TRandom3(0); } //_____________________________________________________________________________ Bool_t ProofNtuple::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either ProofNtuple::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. if (!fNtp) return kTRUE; // Fill ntuple Float_t px, py, random; if (fNtpRndm) { // Get the entry Float_t *ar = fNtpRndm->GetArgs(); Long64_t ent = entry % fNtpRndm->GetEntries(); fNtpRndm->GetEntry(ent); random = ar[0]; px = (Float_t) TMath::ErfInverse((Double_t)(ar[1]*2 - 1.)) * TMath::Sqrt(2.); py = (Float_t) TMath::ErfInverse((Double_t)(ar[2]*2 - 1.)) * TMath::Sqrt(2.); } else if (fRandom) { fRandom->Rannor(px,py); random = fRandom->Rndm(); } else { Abort("no way to get random numbers! Stop processing", kAbortProcess); return kTRUE; } Float_t pz = px*px + py*py; Int_t i = (Int_t) entry; fNtp->Fill(px,py,pz,random,i); if (!fNtp2) return kTRUE; // The second ntuple Float_t vz = random * 2. - 1.; fNtp2->Fill(px,py,vz); return kTRUE; } //_____________________________________________________________________________ void ProofNtuple::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. // Write the ntuple to the file if (fFile) { if (!fNtp) { Error("SlaveTerminate", "'ntuple' is undefined!"); return; } Bool_t cleanup = kFALSE; TDirectory *savedir = gDirectory; if (fNtp->GetEntries() > 0) { fFile->cd(); fNtp->Write(0, TObject::kOverwrite); if (fNtp2 && fNtp2->GetEntries() > 0) fNtp2->Write(); fProofFile->Print(); fOutput->Add(fProofFile); } else { cleanup = kTRUE; } fNtp->SetDirectory(0); if (fNtp2) fNtp2->SetDirectory(0); gDirectory = savedir; fFile->Close(); // Cleanup, if needed if (cleanup) { TUrl uf(*(fFile->GetEndpointUrl())); SafeDelete(fFile); gSystem->Unlink(uf.GetFile()); SafeDelete(fProofFile); } } } //_____________________________________________________________________________ void ProofNtuple::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. // Do nothing is not requested (dataset creation run) if (!fPlotNtuple) return; // Get the ntuple from the file if ((fProofFile = dynamic_cast<TProofOutputFile*>(fOutput->FindObject("SimpleNtuple.root")))) { TString outputFile(fProofFile->GetOutputFileName()); TString outputName(fProofFile->GetName()); outputName += ".root"; Printf("outputFile: %s", outputFile.Data()); // Read the ntuple from the file fFile = TFile::Open(outputFile); if (fFile) { Printf("Managed to open file: %s", outputFile.Data()); fNtp = (TNtuple *) fFile->Get("ntuple"); } else { Error("Terminate", "could not open file: %s", outputFile.Data()); } if (!fFile) return; } else { Error("Terminate", "TProofOutputFile not found"); return; } // Plot ntuples if (fNtp) PlotNtuple(fNtp, "proof ntuple"); } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2021 Inviwo 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/basegl/processors/background.h> #include <inviwo/core/util/stringconversion.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/image/imagegl.h> #include <modules/opengl/image/layergl.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/inviwoopengl.h> namespace inviwo { const ProcessorInfo Background::processorInfo_{ "org.inviwo.Background", // Class identifier "Background", // Display name "Image Operation", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo Background::getProcessorInfo() const { return processorInfo_; } Background::Background() : Processor() , inport_("inport") , outport_("outport") , backgroundStyle_("backgroundStyle", "Style", {{"linearGradientVertical", "Linear gradient (Vertical)", BackgroundStyle::LinearVertical}, {"linearGradientHorizontal", "Linear gradient (Horizontal)", BackgroundStyle::LinearHorizontal}, {"linearGradientSpherical", "Linear gradient (Spherical)", BackgroundStyle::LinearSpherical}, {"uniformColor", "Uniform color", BackgroundStyle::Uniform}, {"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}}, 0, InvalidationLevel::InvalidResources) , bgColor1_("bgColor1", "Color 1", vec4(0.0f, 0.0f, 0.0f, 1.0f)) , bgColor2_("bgColor2", "Color 2", vec4(1.0f)) , checkerBoardSize_("checkerBoardSize", "Checker Board Size", ivec2(10, 10), ivec2(1, 1), ivec2(256, 256)) , switchColors_("switchColors", "Switch Colors", InvalidationLevel::Valid) , blendMode_("blendMode", "Blend mode", {{"backtofront", "Back To Front (Pre-multiplied)", BlendMode::BackToFront}, {"alphamixing", "Alpha Mixing", BlendMode::AlphaMixing}}, 0, InvalidationLevel::InvalidResources) , shader_("background.frag", Shader::Build::No) { addPort(inport_); addPort(outport_); inport_.setOptional(true); addProperty(backgroundStyle_); bgColor1_.setSemantics(PropertySemantics::Color); addProperty(bgColor1_); bgColor2_.setSemantics(PropertySemantics::Color); addProperty(bgColor2_); addProperty(checkerBoardSize_); addProperty(switchColors_); addProperty(blendMode_); switchColors_.onChange([&]() { vec4 tmp = bgColor1_.get(); bgColor1_.set(bgColor2_.get()); bgColor2_.set(tmp); }); shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); } Background::~Background() = default; void Background::initializeResources() { auto fs = shader_.getFragmentShaderObject(); std::string_view bgStyleValue; switch (backgroundStyle_.get()) { default: case BackgroundStyle::LinearVertical: // linear gradient bgStyleValue = "linearGradientVertical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearHorizontal: // linear gradient bgStyleValue = "linearGradientHorizontal(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearSpherical: // linear spherical gradient bgStyleValue = "linearGradientSpherical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::Uniform: // uniform color bgStyleValue = "bgColor1"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::CheckerBoard: // checker board bgStyleValue = "checkerBoard(texCoord)"; checkerBoardSize_.setVisible(true); break; } fs->addShaderDefine("BACKGROUND_STYLE_FUNCTION", bgStyleValue); if (inport_.isReady()) { fs->addShaderDefine("SRC_COLOR", "texture(inportColor, texCoord)"); // set shader inputs to match number of available color layers updateShaderInputs(); fs->addShaderDefine("PICKING_LAYER"); fs->addShaderDefine("DEPTH_LAYER"); hadData_ = true; } else { fs->addShaderDefine("SRC_COLOR", "vec4(0)"); fs->removeShaderDefine("PICKING_LAYER"); fs->removeShaderDefine("DEPTH_LAYER"); hadData_ = false; } const std::string_view blendfunc = [&]() { switch (blendMode_.get()) { case BlendMode::BackToFront: return "blendBackToFront"; case BlendMode::AlphaMixing: [[fallthrough]]; default: return "blendAlphaCompositing"; } }(); fs->addShaderDefine("BLENDFUNC", blendfunc); shader_.build(); } void Background::process() { if (inport_.isReady() != hadData_) initializeResources(); if (inport_.isReady()) { // Check data format, make sure we always have 4 channels auto inDataFromat = inport_.getData()->getDataFormat(); auto format = DataFormatBase::get(inDataFromat->getNumericType(), 4, inDataFromat->getSize() * 8 / inDataFromat->getComponents()); if (outport_.getData()->getDataFormat() != format) { outport_.setData(std::make_shared<Image>(outport_.getDimensions(), format)); } } utilgl::activateTarget(outport_, ImageType::AllLayers); shader_.activate(); if (inport_.isReady()) { TextureUnitContainer textureUnits; auto image = inport_.getData(); utilgl::bindAndSetUniforms(shader_, textureUnits, inport_, ImageType::AllLayers); { // bind all additional color layers const auto numColorLayers = image->getNumberOfColorLayers(); auto imageGL = image->getRepresentation<ImageGL>(); for (size_t i = 1; i < numColorLayers; ++i) { TextureUnit texUnit; imageGL->getColorLayerGL(i)->bindTexture(texUnit.getEnum()); shader_.setUniform("color" + toString<size_t>(i), texUnit.getUnitNumber()); textureUnits.push_back(std::move(texUnit)); } } } utilgl::setUniforms(shader_, outport_, bgColor1_, bgColor2_, checkerBoardSize_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void Background::updateShaderInputs() { const auto numColorLayers = inport_.getData()->getNumberOfColorLayers(); auto fs = shader_.getFragmentShaderObject(); if (numColorLayers > 1) { fs->addShaderDefine("ADDITIONAL_COLOR_LAYERS"); // location 0 is reserved for FragData0, location 1 for PickingData size_t outputLocation = 2; StrBuffer buff; buff.append("\n"); for (size_t i = 1; i < numColorLayers; ++i) { buff.append("layout(location = {}) out vec4 FragData{};\n", outputLocation++, i); } for (size_t i = 1; i < numColorLayers; ++i) { buff.append("uniform sampler2D color{};\n", i); } fs->addShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS", buff); buff.clear(); for (size_t i = 1; i < numColorLayers - 1; ++i) { buff.append("FragData{0} = texture(color{0}, texCoord.xy); \\\n", i); } buff.append("FragData{0} = texture(color{0}, texCoord.xy); \n", numColorLayers - 1); fs->addShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE", buff); } else { fs->removeShaderDefine("ADDITIONAL_COLOR_LAYERS"); fs->removeShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS"); fs->removeShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE"); } } } // namespace inviwo <commit_msg>BaseGL: ordinal colors in Background processor<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2021 Inviwo 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/basegl/processors/background.h> #include <inviwo/core/util/stringconversion.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/image/imagegl.h> #include <modules/opengl/image/layergl.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/inviwoopengl.h> namespace inviwo { const ProcessorInfo Background::processorInfo_{ "org.inviwo.Background", // Class identifier "Background", // Display name "Image Operation", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo Background::getProcessorInfo() const { return processorInfo_; } Background::Background() : Processor() , inport_("inport") , outport_("outport") , backgroundStyle_("backgroundStyle", "Style", {{"linearGradientVertical", "Linear gradient (Vertical)", BackgroundStyle::LinearVertical}, {"linearGradientHorizontal", "Linear gradient (Horizontal)", BackgroundStyle::LinearHorizontal}, {"linearGradientSpherical", "Linear gradient (Spherical)", BackgroundStyle::LinearSpherical}, {"uniformColor", "Uniform color", BackgroundStyle::Uniform}, {"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}}, 0, InvalidationLevel::InvalidResources) , bgColor1_("bgColor1", "Color 1", util::ordinalColor(0.0f, 0.0f, 0.0f, 1.0f)) , bgColor2_("bgColor2", "Color 2", util::ordinalColor(1.0f, 1.0f, 1.0f, 1.0f)) , checkerBoardSize_("checkerBoardSize", "Checker Board Size", ivec2(10, 10), ivec2(1, 1), ivec2(256, 256)) , switchColors_("switchColors", "Switch Colors", InvalidationLevel::Valid) , blendMode_("blendMode", "Blend mode", {{"backtofront", "Back To Front (Pre-multiplied)", BlendMode::BackToFront}, {"alphamixing", "Alpha Mixing", BlendMode::AlphaMixing}}, 0, InvalidationLevel::InvalidResources) , shader_("background.frag", Shader::Build::No) { addPort(inport_); addPort(outport_); inport_.setOptional(true); addProperty(backgroundStyle_); addProperty(bgColor1_); addProperty(bgColor2_); addProperty(checkerBoardSize_); addProperty(switchColors_); addProperty(blendMode_); switchColors_.onChange([&]() { vec4 tmp = bgColor1_.get(); bgColor1_.set(bgColor2_.get()); bgColor2_.set(tmp); }); shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); } Background::~Background() = default; void Background::initializeResources() { auto fs = shader_.getFragmentShaderObject(); std::string_view bgStyleValue; switch (backgroundStyle_.get()) { default: case BackgroundStyle::LinearVertical: // linear gradient bgStyleValue = "linearGradientVertical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearHorizontal: // linear gradient bgStyleValue = "linearGradientHorizontal(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearSpherical: // linear spherical gradient bgStyleValue = "linearGradientSpherical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::Uniform: // uniform color bgStyleValue = "bgColor1"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::CheckerBoard: // checker board bgStyleValue = "checkerBoard(texCoord)"; checkerBoardSize_.setVisible(true); break; } fs->addShaderDefine("BACKGROUND_STYLE_FUNCTION", bgStyleValue); if (inport_.isReady()) { fs->addShaderDefine("SRC_COLOR", "texture(inportColor, texCoord)"); // set shader inputs to match number of available color layers updateShaderInputs(); fs->addShaderDefine("PICKING_LAYER"); fs->addShaderDefine("DEPTH_LAYER"); hadData_ = true; } else { fs->addShaderDefine("SRC_COLOR", "vec4(0)"); fs->removeShaderDefine("PICKING_LAYER"); fs->removeShaderDefine("DEPTH_LAYER"); hadData_ = false; } const std::string_view blendfunc = [&]() { switch (blendMode_.get()) { case BlendMode::BackToFront: return "blendBackToFront"; case BlendMode::AlphaMixing: [[fallthrough]]; default: return "blendAlphaCompositing"; } }(); fs->addShaderDefine("BLENDFUNC", blendfunc); shader_.build(); } void Background::process() { if (inport_.isReady() != hadData_) initializeResources(); if (inport_.isReady()) { // Check data format, make sure we always have 4 channels auto inDataFromat = inport_.getData()->getDataFormat(); auto format = DataFormatBase::get(inDataFromat->getNumericType(), 4, inDataFromat->getSize() * 8 / inDataFromat->getComponents()); if (outport_.getData()->getDataFormat() != format) { outport_.setData(std::make_shared<Image>(outport_.getDimensions(), format)); } } utilgl::activateTarget(outport_, ImageType::AllLayers); shader_.activate(); if (inport_.isReady()) { TextureUnitContainer textureUnits; auto image = inport_.getData(); utilgl::bindAndSetUniforms(shader_, textureUnits, inport_, ImageType::AllLayers); { // bind all additional color layers const auto numColorLayers = image->getNumberOfColorLayers(); auto imageGL = image->getRepresentation<ImageGL>(); for (size_t i = 1; i < numColorLayers; ++i) { TextureUnit texUnit; imageGL->getColorLayerGL(i)->bindTexture(texUnit.getEnum()); shader_.setUniform("color" + toString<size_t>(i), texUnit.getUnitNumber()); textureUnits.push_back(std::move(texUnit)); } } } utilgl::setUniforms(shader_, outport_, bgColor1_, bgColor2_, checkerBoardSize_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void Background::updateShaderInputs() { const auto numColorLayers = inport_.getData()->getNumberOfColorLayers(); auto fs = shader_.getFragmentShaderObject(); if (numColorLayers > 1) { fs->addShaderDefine("ADDITIONAL_COLOR_LAYERS"); // location 0 is reserved for FragData0, location 1 for PickingData size_t outputLocation = 2; StrBuffer buff; buff.append("\n"); for (size_t i = 1; i < numColorLayers; ++i) { buff.append("layout(location = {}) out vec4 FragData{};\n", outputLocation++, i); } for (size_t i = 1; i < numColorLayers; ++i) { buff.append("uniform sampler2D color{};\n", i); } fs->addShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS", buff); buff.clear(); for (size_t i = 1; i < numColorLayers - 1; ++i) { buff.append("FragData{0} = texture(color{0}, texCoord.xy); \\\n", i); } buff.append("FragData{0} = texture(color{0}, texCoord.xy); \n", numColorLayers - 1); fs->addShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE", buff); } else { fs->removeShaderDefine("ADDITIONAL_COLOR_LAYERS"); fs->removeShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS"); fs->removeShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE"); } } } // namespace inviwo <|endoftext|>
<commit_before>//Rubisks trying to wrap leveldb-mcpe #include <leveldb/cache.h> #include <leveldb/comparator.h> #include <leveldb/db.h> #include <leveldb/env.h> #include <leveldb/filter_policy.h> #include <leveldb/write_batch.h> #define BOOST_PYTHON_STATIC_LIB #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/python/object.hpp> #include <boost/python/str.hpp> #include <boost/python/extract.hpp> #include <boost/system/config.hpp> #include <boost/python.hpp> #include <stdint.h> #include <stdio.h> namespace bp = boost::python; //Exception class LevelDBException { public: LevelDBException(const std::string msg) : message(msg) {} std::string getMessage() const { return message; } private: std::string message; }; static void ExceptionTranslator(const LevelDBException &err) { PyErr_SetString(PyExc_RuntimeError, err.getMessage().c_str()); }; struct IteratorWrapper{ leveldb::Iterator* _it; IteratorWrapper(leveldb::Iterator* it){ this->_it = it; } bool Valid() { return this->_it->Valid(); } void SeekToFirst() { this->_it->SeekToFirst(); } void SeekToLast() { this->_it->SeekToLast(); } void Seek(PyObject* _target) { const std::string target = bp::extract<const std::string>(_target); return this->_it->Seek(target); } void Next() { this->_it->Next(); } void Prev() { this->_it->Prev(); } std::string key() { return this->_it->key().ToString(); } std::string value() { return this->_it->value().ToString(); } void status() { leveldb::Status s = this->_it->status(); if (!s.ok()){ throw LevelDBException(s.ToString()); } } }; //write_batch.h struct WriteBatchWrapper { leveldb::WriteBatch* _wb; WriteBatchWrapper(){ _wb = new leveldb::WriteBatch(); }; ~WriteBatchWrapper(){ delete _wb; }; void Put(PyObject* _key, PyObject* _value) { const std::string key = bp::extract<const std::string>(_key); const std::string value = bp::extract<const std::string>(_value); this->_wb->Put(key, value); } void Delete(PyObject* _key) { const std::string key = bp::extract<const std::string>(_key); this->_wb->Delete(key); } }; //leveldb::DB wrapper class DBWrap { public: leveldb::DB * _db; DBWrap(PyObject* _options, PyObject* _name) //Open(options, name, db) { const leveldb::Options options = bp::extract<const leveldb::Options&>(_options); std::string name = bp::extract<std::string>(_name); leveldb::Status s = leveldb::DB::Open(options, name, &_db); if(!s.ok()) { throw LevelDBException(s.ToString()); } } void Put(PyObject* _options, PyObject* _key, PyObject* _value) //Put(options, key, value) { const leveldb::WriteOptions& options = bp::extract<const leveldb::WriteOptions&>(_options); const std::string key = bp::extract<const std::string>(_key); const std::string value = bp::extract<const std::string>(_value); leveldb::Status s = this->_db->Put(options, key, value); if (!s.ok()){ throw LevelDBException(s.ToString()); } } void Delete(PyObject* _options, PyObject* _key) //Delete(options, key) { const leveldb::WriteOptions& options = bp::extract<const leveldb::WriteOptions&>(_options); const std::string key = bp::extract<const std::string>(_key); leveldb::Status s = this->_db->Delete(options, key); if (!s.ok()){ throw LevelDBException(s.ToString()); } } std::string Get(PyObject* _options, PyObject* _key) //Delete(options, key) { const leveldb::ReadOptions& options = bp::extract<const leveldb::ReadOptions&>(_options); const std::string key = bp::extract<const std::string>(_key); std::string value; leveldb::Status s = this->_db->Get(options, key, &value); if (!s.ok()){ throw LevelDBException(s.ToString()); } return value; } void Write(PyObject* _options, PyObject* _updates) { const leveldb::WriteOptions& options = bp::extract<const leveldb::WriteOptions&>(_options); WriteBatchWrapper& __updates = bp::extract<WriteBatchWrapper&>(_updates); leveldb::Status s = this->_db->Write(options, __updates._wb); if (!s.ok()){ throw LevelDBException(s.ToString()); } } IteratorWrapper NewIterator(const leveldb::ReadOptions& options) { leveldb::Iterator* it = this->_db->NewIterator(options); return IteratorWrapper(it); } const leveldb::Snapshot* GetSnapshot() { return this->_db->GetSnapshot(); } void GetApproximateSizes(const leveldb::Range* range, int n, uint64_t* sizes) { this->_db->GetApproximateSizes(range, n, sizes); } void ReleaseSnapshot(const leveldb::Snapshot* snapshot) { this->_db->ReleaseSnapshot(snapshot); } bool GetProperty(const leveldb::Slice& property, std::string* value) { return this->_db->GetProperty(property, value); } void CompactRange(const leveldb::Slice* begin, const leveldb::Slice* end) { this->_db->CompactRange(begin, end); } }; BOOST_PYTHON_MODULE(leveldb_mcpe) { //Exceptions bp::register_exception_translator<LevelDBException>(&ExceptionTranslator); //leveldb/db.h bp::class_<DBWrap, boost::noncopyable>("DB", bp::init<PyObject*, PyObject*>()) .def("Put", &DBWrap::Put) .def("Delete", &DBWrap::Delete) .def("Write", &DBWrap::Write) .def("Get", &DBWrap::Get) .def("NewIterator", &DBWrap::NewIterator) .def("GetSnapshot", &DBWrap::GetSnapshot, bp::return_value_policy<bp::reference_existing_object>()) .def("ReleaseSnapshot", &DBWrap::ReleaseSnapshot) .def("GetProperty", &DBWrap::GetProperty) .def("GetApproximateSizes", &DBWrap::GetApproximateSizes) .def("CompactRange", &DBWrap::CompactRange); //leveldb/options.h bp::class_<leveldb::Options>("Options", bp::init<>()) .def_readonly("comparator", &leveldb::Options::comparator) //Pointer, maybe needs better wrapper? Untested .def_readwrite("create_if_missing", &leveldb::Options::create_if_missing) .def_readwrite("error_if_exists", &leveldb::Options::error_if_exists) .def_readwrite("env", &leveldb::Options::env) //Pointer, maybe needs better wrapper? Untested .def_readwrite("info_log", &leveldb::Options::info_log) //Pointer, maybe needs better wrapper? Untested .def_readwrite("write_buffer_size", &leveldb::Options::write_buffer_size) .def_readwrite("max_open_files", &leveldb::Options::max_open_files) .def_readwrite("block_cache", &leveldb::Options::block_cache) //Pointer, maybe needs better wrapper? Untested .def_readwrite("block_size", &leveldb::Options::block_size) .def_readwrite("block_restart_interval", &leveldb::Options::block_restart_interval) //TODO setup a way to include compressor array //Pointer, maybe needs better wrapper? Untested .def_readonly("filter_policy", &leveldb::Options::filter_policy); //Pointer, maybe needs better wrapper? Untested ; bp::class_<leveldb::ReadOptions>("ReadOptions", bp::init<>()) .def_readwrite("verify_checksums", &leveldb::ReadOptions::verify_checksums) .def_readwrite("fill_cache", &leveldb::ReadOptions::fill_cache) .def_readwrite("snapshot", &leveldb::ReadOptions::snapshot) //Pointer, maybe needs better wrapper? Untested ; bp::class_<leveldb::WriteOptions>("WriteOptions", bp::init<>()) .def_readwrite("sync", &leveldb::WriteOptions::sync) ; //leveldb/iterator.h bp::class_<IteratorWrapper>("Iterator", bp::no_init) .def("Valid", &IteratorWrapper::Valid) .def("SeekToFirst", &IteratorWrapper::SeekToFirst) .def("SeekToLast", &IteratorWrapper::SeekToLast) .def("Seek", &IteratorWrapper::Seek) .def("Next", &IteratorWrapper::Next) .def("Prev", &IteratorWrapper::Prev) .def("key", &IteratorWrapper::key) .def("value", &IteratorWrapper::value) .def("status", &IteratorWrapper::status) ; //leveldb/write_batch.h bp::class_<WriteBatchWrapper>("WriteBatch", bp::init<>()) .def("Put", &WriteBatchWrapper::Put) .def("Delete", &WriteBatchWrapper::Delete) ; } <commit_msg>Added destructors for IteratorWrapper and DBWrap<commit_after>//Rubisks trying to wrap leveldb-mcpe #include <leveldb/cache.h> #include <leveldb/comparator.h> #include <leveldb/db.h> #include <leveldb/env.h> #include <leveldb/filter_policy.h> #include <leveldb/write_batch.h> #define BOOST_PYTHON_STATIC_LIB #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/python/object.hpp> #include <boost/python/str.hpp> #include <boost/python/extract.hpp> #include <boost/system/config.hpp> #include <boost/python.hpp> #include <stdint.h> #include <stdio.h> namespace bp = boost::python; //Exception class LevelDBException { public: LevelDBException(const std::string msg) : message(msg) {} std::string getMessage() const { return message; } private: std::string message; }; static void ExceptionTranslator(const LevelDBException &err) { PyErr_SetString(PyExc_RuntimeError, err.getMessage().c_str()); }; struct IteratorWrapper{ leveldb::Iterator* _it; IteratorWrapper(leveldb::Iterator* it){ this->_it = it; } ~IteratorWrapper{ delete _it; } bool Valid() { return this->_it->Valid(); } void SeekToFirst() { this->_it->SeekToFirst(); } void SeekToLast() { this->_it->SeekToLast(); } void Seek(PyObject* _target) { const std::string target = bp::extract<const std::string>(_target); return this->_it->Seek(target); } void Next() { this->_it->Next(); } void Prev() { this->_it->Prev(); } std::string key() { return this->_it->key().ToString(); } std::string value() { return this->_it->value().ToString(); } void status() { leveldb::Status s = this->_it->status(); if (!s.ok()){ throw LevelDBException(s.ToString()); } } }; //write_batch.h struct WriteBatchWrapper { leveldb::WriteBatch* _wb; WriteBatchWrapper(){ _wb = new leveldb::WriteBatch(); }; ~WriteBatchWrapper(){ delete _wb; } void Put(PyObject* _key, PyObject* _value) { const std::string key = bp::extract<const std::string>(_key); const std::string value = bp::extract<const std::string>(_value); this->_wb->Put(key, value); } void Delete(PyObject* _key) { const std::string key = bp::extract<const std::string>(_key); this->_wb->Delete(key); } }; //leveldb::DB wrapper class DBWrap { public: leveldb::DB * _db; ~DBWrap(){ delete _db; }; DBWrap(PyObject* _options, PyObject* _name) //Open(options, name, db) { const leveldb::Options options = bp::extract<const leveldb::Options&>(_options); std::string name = bp::extract<std::string>(_name); leveldb::Status s = leveldb::DB::Open(options, name, &_db); if(!s.ok()) { throw LevelDBException(s.ToString()); } } void Put(PyObject* _options, PyObject* _key, PyObject* _value) //Put(options, key, value) { const leveldb::WriteOptions& options = bp::extract<const leveldb::WriteOptions&>(_options); const std::string key = bp::extract<const std::string>(_key); const std::string value = bp::extract<const std::string>(_value); leveldb::Status s = this->_db->Put(options, key, value); if (!s.ok()){ throw LevelDBException(s.ToString()); } } void Delete(PyObject* _options, PyObject* _key) //Delete(options, key) { const leveldb::WriteOptions& options = bp::extract<const leveldb::WriteOptions&>(_options); const std::string key = bp::extract<const std::string>(_key); leveldb::Status s = this->_db->Delete(options, key); if (!s.ok()){ throw LevelDBException(s.ToString()); } } std::string Get(PyObject* _options, PyObject* _key) //Delete(options, key) { const leveldb::ReadOptions& options = bp::extract<const leveldb::ReadOptions&>(_options); const std::string key = bp::extract<const std::string>(_key); std::string value; leveldb::Status s = this->_db->Get(options, key, &value); if (!s.ok()){ throw LevelDBException(s.ToString()); } return value; } void Write(PyObject* _options, PyObject* _updates) { const leveldb::WriteOptions& options = bp::extract<const leveldb::WriteOptions&>(_options); WriteBatchWrapper& __updates = bp::extract<WriteBatchWrapper&>(_updates); leveldb::Status s = this->_db->Write(options, __updates._wb); if (!s.ok()){ throw LevelDBException(s.ToString()); } } IteratorWrapper NewIterator(const leveldb::ReadOptions& options) { leveldb::Iterator* it = this->_db->NewIterator(options); return IteratorWrapper(it); } const leveldb::Snapshot* GetSnapshot() { return this->_db->GetSnapshot(); } void GetApproximateSizes(const leveldb::Range* range, int n, uint64_t* sizes) { this->_db->GetApproximateSizes(range, n, sizes); } void ReleaseSnapshot(const leveldb::Snapshot* snapshot) { this->_db->ReleaseSnapshot(snapshot); } bool GetProperty(const leveldb::Slice& property, std::string* value) { return this->_db->GetProperty(property, value); } void CompactRange(const leveldb::Slice* begin, const leveldb::Slice* end) { this->_db->CompactRange(begin, end); } }; BOOST_PYTHON_MODULE(leveldb_mcpe) { //Exceptions bp::register_exception_translator<LevelDBException>(&ExceptionTranslator); //leveldb/db.h bp::class_<DBWrap, boost::noncopyable>("DB", bp::init<PyObject*, PyObject*>()) .def("Put", &DBWrap::Put) .def("Delete", &DBWrap::Delete) .def("Write", &DBWrap::Write) .def("Get", &DBWrap::Get) .def("NewIterator", &DBWrap::NewIterator) .def("GetSnapshot", &DBWrap::GetSnapshot, bp::return_value_policy<bp::reference_existing_object>()) .def("ReleaseSnapshot", &DBWrap::ReleaseSnapshot) .def("GetProperty", &DBWrap::GetProperty) .def("GetApproximateSizes", &DBWrap::GetApproximateSizes) .def("CompactRange", &DBWrap::CompactRange); //leveldb/options.h bp::class_<leveldb::Options>("Options", bp::init<>()) .def_readonly("comparator", &leveldb::Options::comparator) //Pointer, maybe needs better wrapper? Untested .def_readwrite("create_if_missing", &leveldb::Options::create_if_missing) .def_readwrite("error_if_exists", &leveldb::Options::error_if_exists) .def_readwrite("env", &leveldb::Options::env) //Pointer, maybe needs better wrapper? Untested .def_readwrite("info_log", &leveldb::Options::info_log) //Pointer, maybe needs better wrapper? Untested .def_readwrite("write_buffer_size", &leveldb::Options::write_buffer_size) .def_readwrite("max_open_files", &leveldb::Options::max_open_files) .def_readwrite("block_cache", &leveldb::Options::block_cache) //Pointer, maybe needs better wrapper? Untested .def_readwrite("block_size", &leveldb::Options::block_size) .def_readwrite("block_restart_interval", &leveldb::Options::block_restart_interval) //TODO setup a way to include compressor array //Pointer, maybe needs better wrapper? Untested .def_readonly("filter_policy", &leveldb::Options::filter_policy); //Pointer, maybe needs better wrapper? Untested ; bp::class_<leveldb::ReadOptions>("ReadOptions", bp::init<>()) .def_readwrite("verify_checksums", &leveldb::ReadOptions::verify_checksums) .def_readwrite("fill_cache", &leveldb::ReadOptions::fill_cache) .def_readwrite("snapshot", &leveldb::ReadOptions::snapshot) //Pointer, maybe needs better wrapper? Untested ; bp::class_<leveldb::WriteOptions>("WriteOptions", bp::init<>()) .def_readwrite("sync", &leveldb::WriteOptions::sync) ; //leveldb/iterator.h bp::class_<IteratorWrapper>("Iterator", bp::no_init) .def("Valid", &IteratorWrapper::Valid) .def("SeekToFirst", &IteratorWrapper::SeekToFirst) .def("SeekToLast", &IteratorWrapper::SeekToLast) .def("Seek", &IteratorWrapper::Seek) .def("Next", &IteratorWrapper::Next) .def("Prev", &IteratorWrapper::Prev) .def("key", &IteratorWrapper::key) .def("value", &IteratorWrapper::value) .def("status", &IteratorWrapper::status) ; //leveldb/write_batch.h bp::class_<WriteBatchWrapper>("WriteBatch", bp::init<>()) .def("Put", &WriteBatchWrapper::Put) .def("Delete", &WriteBatchWrapper::Delete) ; } <|endoftext|>
<commit_before>// @(#)root/editline:$Id$ // Author: Mary-Louise Gill, 2009 /************************************************************************* * Copyright (C) 1995-2011, 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 "Getline_color.h" #include <stack> #include <string> #include "TClass.h" #include "TClassTable.h" #include "TInterpreter.h" #include "TROOT.h" #include "textinput/Range.h" #include "textinput/Text.h" using namespace std; using namespace textinput; namespace { Color ColorFromName(const char* name) { // Convert a color name to a Color. Color ret; std::string lowname(name); size_t lenname = strlen(name); for (size_t i = 0; i < lenname; ++i) lowname[i] = tolower(lowname[i]); if (lowname.find("bold") != std::string::npos || lowname.find("light") != std::string::npos) ret.fModifiers |= Color::kModBold; if (lowname.find("under") != std::string::npos) ret.fModifiers |= Color::kModUnderline; size_t poshash = lowname.find('#'); size_t lenrgb = 0; if (poshash != std::string::npos) { int endrgb = poshash + 1; while ((lowname[endrgb] >= '0' && lowname[endrgb] <= '9') || (lowname[endrgb] >= 'a' && lowname[endrgb] <= 'f')) { ++endrgb; } lenrgb = endrgb - poshash - 1; } int rgb[3] = {0}; if (lenrgb == 3) { for (int i = 0; i < 3; ++i) { rgb[i] = lowname[poshash + 1 + i] - '0'; if (rgb[i] > 9) { rgb[i] = rgb[i] + '0' - 'a' + 10; } rgb[i] *= 16; // only upper 4 bits are set. } return ret; } else if (lenrgb == 6) { for (int i = 0; i < 6; ++i) { int v = lowname[poshash + 1 + i] - '0'; if (v > 9) { v = v + '0' - 'a' + 10; } if (i % 2 == 0) { v *= 16; } rgb[i / 2] += v; } ret.fR = rgb[0]; ret.fG = rgb[1]; ret.fB = rgb[2]; return ret; } else { if (lowname.find("default") != std::string::npos) { return ret; } static const char* colornames[] = { "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", 0 }; static const unsigned char colorrgb[][3] = { {0,0,0}, {127,0,0}, {0,127,0}, {127,127,0}, {0,0,127}, {127,0,127}, {0,127,127}, {127,127,127}, {0} }; for (int i = 0; colornames[i]; ++i) { if (lowname.find(colornames[i]) != std::string::npos) { int boldify = 0; if (ret.fModifiers & Color::kModBold) boldify = 64; ret.fR = colorrgb[i][0] + boldify; ret.fG = colorrgb[i][1] + boldify; ret.fB = colorrgb[i][2] + boldify; return ret; } } } fprintf(stderr, "Getline_color/ColorFromName: cannot parse color %s!\n", name); return Color(); } // ColorFromName() bool IsAlnum_(char c) { return c == '_' || isalnum(c); } bool IsAlpha_(char c) { return c == '_' || isalpha(c); } } // unnamed namespace ROOT::TextInputColorizer::TextInputColorizer(): fColorIsDefault(), fPrevBracketColor(kColorNone) { // Set the default colors. // fColors[kColorNone] stays default initialized. fColors[kColorType] = ColorFromName("blue"); fColors[kColorTabComp] = ColorFromName("magenta"); fColors[kColorBracket] = ColorFromName("green"); fColors[kColorBadBracket] = ColorFromName("red"); fColors[kColorPrompt] = ColorFromName("default"); fColorIsDefault[kColorPrompt] = true; } ROOT::TextInputColorizer::~TextInputColorizer() { // pin vtable } void ROOT::TextInputColorizer::ExtendRangeAndSetColor(Text& input, size_t idx, char col, Range& disp) { // Utility function that updates the display modification range if the // color at index idx is different from what it was before. if (fColorIsDefault[(int)col]) { // Never mind the color: use use default. col = 0; } if (input.GetColor(idx) != col) { input.SetColor(idx, col); disp.Extend(idx); } } bool ROOT::TextInputColorizer::GetColor(char type, Color& col) { // Set the Color corresponding to an entry in EColorTypes. // Returns false if the type index is out of range. if (type < (int)kNumColors) { col = fColors[(size_t)type]; return true; } col = Color(); return false; } void ROOT::TextInputColorizer::SetColors(const char* colorType, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { // Set the colors of the different items as either // #RGB // #RRGGBB or // color name, optionally prepended by "underline" or "bold" fColors[kColorType] = ColorFromName(colorType); fColorIsDefault[kColorType] = (fColors[kColorType] == Color()); fColors[kColorTabComp] = ColorFromName(colorTabComp); fColorIsDefault[kColorTabComp] = (fColors[kColorTabComp] == Color()); fColors[kColorBracket] = ColorFromName(colorBracket); fColorIsDefault[kColorBracket] = (fColors[kColorBracket] == Color()); fColors[kColorBadBracket] = ColorFromName(colorBadBracket); fColorIsDefault[kColorBadBracket] = (fColors[kColorBadBracket] == Color()); fColors[kColorPrompt] = ColorFromName(colorPrompt); fColorIsDefault[kColorPrompt] = (fColors[kColorPrompt] == Color()); } void ROOT::TextInputColorizer::ProcessTextChange(EditorRange& Modification, Text& input) { // The text has changed; look for word that are types. const std::string& text = input.GetText(); size_t modStart = Modification.fEdit.fStart; size_t inputLength = input.length(); // Find end of modified word: size_t modEnd = Modification.fEdit.fLength; if (modEnd == (size_t) -1) { modEnd = inputLength; } else { modEnd += modStart; if (modEnd > inputLength) { modEnd = inputLength; } else { while (modEnd < inputLength && IsAlnum_(text[modEnd])) ++modEnd; } } // Find beginning of modified word. Don't treat // "12ull" specially, it will fall out below. while (modStart && IsAlnum_(text[modStart])) --modStart; // Ignore spaces while (modStart < modEnd && isspace(text[modStart])) ++modStart; while (modEnd > modStart && isspace(text[modEnd])) --modStart; for (size_t i = modStart; i < modEnd;) { // i points to beginning of word here. if (isdigit(text[i])) { // "12", or "12ull". Default color. ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; while (i < modEnd && IsAlnum_(text[i])) { ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; } } else if (IsAlpha_(text[i])) { // identifier, but is it a type? size_t wordLen = 1; while (i + wordLen < modEnd && IsAlnum_(text[i + wordLen])) { ++wordLen; } std::string word = text.substr(i, wordLen); char color = kColorNone; if (gROOT->GetListOfTypes()->FindObject(word.c_str()) || gClassTable->GetDict(word.c_str()) || gInterpreter->GetClassSharedLibs(word.c_str()) || TClass::GetClass(word.c_str(), kFALSE)) { color = kColorType; } for (size_t ic = i; ic < i + wordLen; ++ic) { ExtendRangeAndSetColor(input, ic, color, Modification.fDisplay); } i += wordLen; } else { size_t wordLen = 1; while (i + wordLen < modEnd && !IsAlnum_(text[i + wordLen])) ++wordLen; for (size_t ic = i; ic < i + wordLen; ++ic) { // protect colored parens char oldColor = input.GetColor(ic); if (oldColor != kColorBracket && oldColor != kColorBadBracket) { ExtendRangeAndSetColor(input, ic, kColorNone, Modification.fDisplay); } } i += wordLen; } // skip trailing whitespace. while (i < modEnd && isspace(text[i])) { ExtendRangeAndSetColor(input, i, kColorNone, Modification.fDisplay); ++i; } } } void ROOT::TextInputColorizer::ProcessPromptChange(Text& prompt) { int idx = kColorPrompt; if (fColorIsDefault[kColorPrompt]) { idx = 0; } prompt.SetColor(Range::AllText(), idx); } void ROOT::TextInputColorizer::ProcessCursorChange(size_t Cursor, Text& input, Range& DisplayR) { // Check each char to see if it is an opening bracket, // if so, check for its closing one and color them green. static const int numBrackets = 3; static const char bTypes[numBrackets][3] = {"()", "{}", "[]"}; if (input.empty()) return; if (fPrevBracketColor != kColorNone) { // Remove previous bracket coloring. const char* colors = &input.GetColors()[0]; const char* prevBracket = (const char*) memchr(colors, fPrevBracketColor, input.length()); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); if (fPrevBracketColor == kColorBracket) { // There will be two. prevBracket = (const char*) memchr(prevBracket, fPrevBracketColor, input.length() - (prevBracket - colors)); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); } } } } // locations of brackets stack<size_t> locBrackets; int foundParenIdx = -1; int parenType = 0; const std::string& text = input.GetText(); if (Cursor < input.length()) { // check against each bracket type for (; parenType < numBrackets; parenType++) { // if current char is equal to opening bracket, push onto stack if (text[Cursor] == bTypes[parenType][0]) { locBrackets.push(Cursor); foundParenIdx = 0; break; } else if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } } // current cursor char is not an open bracket, and there is a previous char // to check if (foundParenIdx == -1 && Cursor > 0) { // check previously typed char for being a closing bracket --Cursor; // check against each bracket type parenType = 0; for (; parenType < numBrackets; parenType++) { // if current char is equal to closing bracket, push onto stack if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } } // no bracket found on either current or previous char, return. if (foundParenIdx == -1) { return; } // terate through remaining letters until find a matching closing bracket // if another open bracket of the same type is found, push onto stack // and pop on next closing bracket match int direction = 1; if (foundParenIdx == 1) { direction = -1; } size_t lenLine = input.length(); // direction == -1: Cursor - 1 to front. size_t scanBegin = (Cursor > 0) ? Cursor - 1 : 0; size_t scanLast = 0; if (direction == 1) { // direction == 1: Cursor + 1 to end. scanBegin = Cursor + 1; scanLast = lenLine - 1; if (scanBegin > scanLast) return; } for (size_t i = scanBegin; true /*avoid "unsigned >= 0" condition*/; i += direction) { // if current char is equal to another opening bracket, push onto stack if (text[i] == bTypes[parenType][foundParenIdx]) { // push index of bracket locBrackets.push(i); } // if current char is equal to closing bracket else if (text[i] == bTypes[parenType][1 - foundParenIdx]) { // pop previous opening bracket off stack locBrackets.pop(); // if previous opening was the last entry and we are at the cursor, then highlight match if (locBrackets.empty()) { ExtendRangeAndSetColor(input, i, kColorBracket, DisplayR); ExtendRangeAndSetColor(input, Cursor, kColorBracket, DisplayR); fPrevBracketColor = kColorBracket; break; } } // loop termination check before possible underflow ("--0") if (i == scanLast) break; } if (!locBrackets.empty()) { ExtendRangeAndSetColor(input, Cursor, kColorBadBracket, DisplayR); fPrevBracketColor = kColorBadBracket; } } // matchParentheses <commit_msg>Don't use TClass::GetClass() but TInterpreter::CheckClassInfo() with disabled autoloading to see whether a class is known to the interpreter.<commit_after>// @(#)root/editline:$Id$ // Author: Mary-Louise Gill, 2009 /************************************************************************* * Copyright (C) 1995-2011, 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 "Getline_color.h" #include <stack> #include <string> #include "TClass.h" #include "TClassTable.h" #include "TInterpreter.h" #include "TROOT.h" #include "textinput/Range.h" #include "textinput/Text.h" using namespace std; using namespace textinput; namespace { Color ColorFromName(const char* name) { // Convert a color name to a Color. Color ret; std::string lowname(name); size_t lenname = strlen(name); for (size_t i = 0; i < lenname; ++i) lowname[i] = tolower(lowname[i]); if (lowname.find("bold") != std::string::npos || lowname.find("light") != std::string::npos) ret.fModifiers |= Color::kModBold; if (lowname.find("under") != std::string::npos) ret.fModifiers |= Color::kModUnderline; size_t poshash = lowname.find('#'); size_t lenrgb = 0; if (poshash != std::string::npos) { int endrgb = poshash + 1; while ((lowname[endrgb] >= '0' && lowname[endrgb] <= '9') || (lowname[endrgb] >= 'a' && lowname[endrgb] <= 'f')) { ++endrgb; } lenrgb = endrgb - poshash - 1; } int rgb[3] = {0}; if (lenrgb == 3) { for (int i = 0; i < 3; ++i) { rgb[i] = lowname[poshash + 1 + i] - '0'; if (rgb[i] > 9) { rgb[i] = rgb[i] + '0' - 'a' + 10; } rgb[i] *= 16; // only upper 4 bits are set. } return ret; } else if (lenrgb == 6) { for (int i = 0; i < 6; ++i) { int v = lowname[poshash + 1 + i] - '0'; if (v > 9) { v = v + '0' - 'a' + 10; } if (i % 2 == 0) { v *= 16; } rgb[i / 2] += v; } ret.fR = rgb[0]; ret.fG = rgb[1]; ret.fB = rgb[2]; return ret; } else { if (lowname.find("default") != std::string::npos) { return ret; } static const char* colornames[] = { "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", 0 }; static const unsigned char colorrgb[][3] = { {0,0,0}, {127,0,0}, {0,127,0}, {127,127,0}, {0,0,127}, {127,0,127}, {0,127,127}, {127,127,127}, {0} }; for (int i = 0; colornames[i]; ++i) { if (lowname.find(colornames[i]) != std::string::npos) { int boldify = 0; if (ret.fModifiers & Color::kModBold) boldify = 64; ret.fR = colorrgb[i][0] + boldify; ret.fG = colorrgb[i][1] + boldify; ret.fB = colorrgb[i][2] + boldify; return ret; } } } fprintf(stderr, "Getline_color/ColorFromName: cannot parse color %s!\n", name); return Color(); } // ColorFromName() bool IsAlnum_(char c) { return c == '_' || isalnum(c); } bool IsAlpha_(char c) { return c == '_' || isalpha(c); } } // unnamed namespace ROOT::TextInputColorizer::TextInputColorizer(): fColorIsDefault(), fPrevBracketColor(kColorNone) { // Set the default colors. // fColors[kColorNone] stays default initialized. fColors[kColorType] = ColorFromName("blue"); fColors[kColorTabComp] = ColorFromName("magenta"); fColors[kColorBracket] = ColorFromName("green"); fColors[kColorBadBracket] = ColorFromName("red"); fColors[kColorPrompt] = ColorFromName("default"); fColorIsDefault[kColorPrompt] = true; } ROOT::TextInputColorizer::~TextInputColorizer() { // pin vtable } void ROOT::TextInputColorizer::ExtendRangeAndSetColor(Text& input, size_t idx, char col, Range& disp) { // Utility function that updates the display modification range if the // color at index idx is different from what it was before. if (fColorIsDefault[(int)col]) { // Never mind the color: use use default. col = 0; } if (input.GetColor(idx) != col) { input.SetColor(idx, col); disp.Extend(idx); } } bool ROOT::TextInputColorizer::GetColor(char type, Color& col) { // Set the Color corresponding to an entry in EColorTypes. // Returns false if the type index is out of range. if (type < (int)kNumColors) { col = fColors[(size_t)type]; return true; } col = Color(); return false; } void ROOT::TextInputColorizer::SetColors(const char* colorType, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { // Set the colors of the different items as either // #RGB // #RRGGBB or // color name, optionally prepended by "underline" or "bold" fColors[kColorType] = ColorFromName(colorType); fColorIsDefault[kColorType] = (fColors[kColorType] == Color()); fColors[kColorTabComp] = ColorFromName(colorTabComp); fColorIsDefault[kColorTabComp] = (fColors[kColorTabComp] == Color()); fColors[kColorBracket] = ColorFromName(colorBracket); fColorIsDefault[kColorBracket] = (fColors[kColorBracket] == Color()); fColors[kColorBadBracket] = ColorFromName(colorBadBracket); fColorIsDefault[kColorBadBracket] = (fColors[kColorBadBracket] == Color()); fColors[kColorPrompt] = ColorFromName(colorPrompt); fColorIsDefault[kColorPrompt] = (fColors[kColorPrompt] == Color()); } void ROOT::TextInputColorizer::ProcessTextChange(EditorRange& Modification, Text& input) { // The text has changed; look for word that are types. const std::string& text = input.GetText(); size_t modStart = Modification.fEdit.fStart; size_t inputLength = input.length(); // Find end of modified word: size_t modEnd = Modification.fEdit.fLength; if (modEnd == (size_t) -1) { modEnd = inputLength; } else { modEnd += modStart; if (modEnd > inputLength) { modEnd = inputLength; } else { while (modEnd < inputLength && IsAlnum_(text[modEnd])) ++modEnd; } } // Find beginning of modified word. Don't treat // "12ull" specially, it will fall out below. while (modStart && IsAlnum_(text[modStart])) --modStart; // Ignore spaces while (modStart < modEnd && isspace(text[modStart])) ++modStart; while (modEnd > modStart && isspace(text[modEnd])) --modStart; for (size_t i = modStart; i < modEnd;) { // i points to beginning of word here. if (isdigit(text[i])) { // "12", or "12ull". Default color. ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; while (i < modEnd && IsAlnum_(text[i])) { ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; } } else if (IsAlpha_(text[i])) { // identifier, but is it a type? size_t wordLen = 1; while (i + wordLen < modEnd && IsAlnum_(text[i + wordLen])) { ++wordLen; } std::string word = text.substr(i, wordLen); char color = kColorNone; if (gROOT->GetListOfTypes()->FindObject(word.c_str()) || gClassTable->GetDict(word.c_str()) || gInterpreter->GetClassSharedLibs(word.c_str()) || gInterpreter->CheckClassInfo(word.c_str(), false /*autoload*/)) { color = kColorType; } for (size_t ic = i; ic < i + wordLen; ++ic) { ExtendRangeAndSetColor(input, ic, color, Modification.fDisplay); } i += wordLen; } else { size_t wordLen = 1; while (i + wordLen < modEnd && !IsAlnum_(text[i + wordLen])) ++wordLen; for (size_t ic = i; ic < i + wordLen; ++ic) { // protect colored parens char oldColor = input.GetColor(ic); if (oldColor != kColorBracket && oldColor != kColorBadBracket) { ExtendRangeAndSetColor(input, ic, kColorNone, Modification.fDisplay); } } i += wordLen; } // skip trailing whitespace. while (i < modEnd && isspace(text[i])) { ExtendRangeAndSetColor(input, i, kColorNone, Modification.fDisplay); ++i; } } } void ROOT::TextInputColorizer::ProcessPromptChange(Text& prompt) { int idx = kColorPrompt; if (fColorIsDefault[kColorPrompt]) { idx = 0; } prompt.SetColor(Range::AllText(), idx); } void ROOT::TextInputColorizer::ProcessCursorChange(size_t Cursor, Text& input, Range& DisplayR) { // Check each char to see if it is an opening bracket, // if so, check for its closing one and color them green. static const int numBrackets = 3; static const char bTypes[numBrackets][3] = {"()", "{}", "[]"}; if (input.empty()) return; if (fPrevBracketColor != kColorNone) { // Remove previous bracket coloring. const char* colors = &input.GetColors()[0]; const char* prevBracket = (const char*) memchr(colors, fPrevBracketColor, input.length()); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); if (fPrevBracketColor == kColorBracket) { // There will be two. prevBracket = (const char*) memchr(prevBracket, fPrevBracketColor, input.length() - (prevBracket - colors)); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); } } } } // locations of brackets stack<size_t> locBrackets; int foundParenIdx = -1; int parenType = 0; const std::string& text = input.GetText(); if (Cursor < input.length()) { // check against each bracket type for (; parenType < numBrackets; parenType++) { // if current char is equal to opening bracket, push onto stack if (text[Cursor] == bTypes[parenType][0]) { locBrackets.push(Cursor); foundParenIdx = 0; break; } else if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } } // current cursor char is not an open bracket, and there is a previous char // to check if (foundParenIdx == -1 && Cursor > 0) { // check previously typed char for being a closing bracket --Cursor; // check against each bracket type parenType = 0; for (; parenType < numBrackets; parenType++) { // if current char is equal to closing bracket, push onto stack if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } } // no bracket found on either current or previous char, return. if (foundParenIdx == -1) { return; } // terate through remaining letters until find a matching closing bracket // if another open bracket of the same type is found, push onto stack // and pop on next closing bracket match int direction = 1; if (foundParenIdx == 1) { direction = -1; } size_t lenLine = input.length(); // direction == -1: Cursor - 1 to front. size_t scanBegin = (Cursor > 0) ? Cursor - 1 : 0; size_t scanLast = 0; if (direction == 1) { // direction == 1: Cursor + 1 to end. scanBegin = Cursor + 1; scanLast = lenLine - 1; if (scanBegin > scanLast) return; } for (size_t i = scanBegin; true /*avoid "unsigned >= 0" condition*/; i += direction) { // if current char is equal to another opening bracket, push onto stack if (text[i] == bTypes[parenType][foundParenIdx]) { // push index of bracket locBrackets.push(i); } // if current char is equal to closing bracket else if (text[i] == bTypes[parenType][1 - foundParenIdx]) { // pop previous opening bracket off stack locBrackets.pop(); // if previous opening was the last entry and we are at the cursor, then highlight match if (locBrackets.empty()) { ExtendRangeAndSetColor(input, i, kColorBracket, DisplayR); ExtendRangeAndSetColor(input, Cursor, kColorBracket, DisplayR); fPrevBracketColor = kColorBracket; break; } } // loop termination check before possible underflow ("--0") if (i == scanLast) break; } if (!locBrackets.empty()) { ExtendRangeAndSetColor(input, Cursor, kColorBadBracket, DisplayR); fPrevBracketColor = kColorBadBracket; } } // matchParentheses <|endoftext|>
<commit_before>// @(#)root/editline:$Id$ // Author: Mary-Louise Gill, 2009 /************************************************************************* * Copyright (C) 1995-2011, 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 "Getline_color.h" #include <stack> #include <string> #include "TROOT.h" #include "TInterpreter.h" #include "textinput/Range.h" #include "textinput/Text.h" using namespace std; using namespace textinput; namespace { Color ColorFromName(const char* name) { // Convert a color name to a Color. Color ret; std::string lowname(name); size_t lenname = strlen(name); for (size_t i = 0; i < lenname; ++i) lowname[i] = tolower(lowname[i]); if (lowname.find("bold") != std::string::npos || lowname.find("light") != std::string::npos) ret.fModifiers |= Color::kModBold; if (lowname.find("under") != std::string::npos) ret.fModifiers |= Color::kModUnderline; size_t poshash = lowname.find('#'); size_t lenrgb = 0; if (poshash != std::string::npos) { int endrgb = poshash + 1; while ((lowname[endrgb] >= '0' && lowname[endrgb] <= '9') || (lowname[endrgb] >= 'a' && lowname[endrgb] <= 'f')) { ++endrgb; } lenrgb = endrgb - poshash - 1; } int rgb[3] = {0}; if (lenrgb == 3) { for (int i = 0; i < 3; ++i) { rgb[i] = lowname[poshash + 1 + i] - '0'; if (rgb[i] > 9) { rgb[i] = rgb[i] + '0' - 'a' + 10; } rgb[i] *= 16; // only upper 4 bits are set. } return ret; } else if (lenrgb == 6) { for (int i = 0; i < 6; ++i) { int v = lowname[poshash + 1 + i] - '0'; if (v > 9) { v = v + '0' - 'a' + 10; } if (i % 2 == 0) { v *= 16; } rgb[i / 2] += v; } ret.fR = rgb[0]; ret.fG = rgb[1]; ret.fB = rgb[2]; return ret; } else { if (lowname.find("default") != std::string::npos) { return ret; } static const char* colornames[] = { "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", 0 }; static const unsigned char colorrgb[][3] = { {0,0,0}, {127,0,0}, {0,127,0}, {127,127,0}, {0,0,127}, {127,0,127}, {0,127,127}, {127,127,127}, {0} }; for (int i = 0; colornames[i]; ++i) { if (lowname.find(colornames[i]) != std::string::npos) { int boldify = 0; if (ret.fModifiers & Color::kModBold) boldify = 64; ret.fR = colorrgb[i][0] + boldify; ret.fG = colorrgb[i][1] + boldify; ret.fB = colorrgb[i][2] + boldify; return ret; } } } fprintf(stderr, "Getline_color/ColorFromName: cannot parse color %s!\n", name); return Color(); } // ColorFromName() bool IsAlnum_(char c) { return c == '_' || isalnum(c); } bool IsAlpha_(char c) { return c == '_' || isalpha(c); } void ExtendRangeAndSetColor(Text& input, size_t idx, char col, Range& disp) { // Utility function that updates the display modification range if the // color at index idx is different from what it was before. if (input.GetColor(idx) != col) { input.SetColor(idx, col); disp.Extend(idx); } } } // unnamed namespace ROOT::TextInputColorizer::TextInputColorizer(): fPrevBracketColor(kColorNone) { // Set the default colors. // fColors[kColorNone] stays default initialized. fColors[kColorType] = ColorFromName("blue"); fColors[kColorTabComp] = ColorFromName("magenta"); fColors[kColorBracket] = ColorFromName("green"); fColors[kColorBadBracket] = ColorFromName("red"); fColors[kColorPrompt] = ColorFromName("cyan"); } ROOT::TextInputColorizer::~TextInputColorizer() { // pin vtable } bool ROOT::TextInputColorizer::GetColor(char type, Color& col) { // Set the Color corresponding to an entry in EColorTypes. // Returns false if the type index is out of range. if (type < (int)kNumColors) { col = fColors[(size_t)type]; return true; } col = Color(); return false; } void ROOT::TextInputColorizer::SetColors(const char* colorType, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { // Set the colors of the different items as either // #RGB // #RRGGBB or // color name, optionally prepended by "underline" or "bold" fColors[kColorType] = ColorFromName(colorType); fColors[kColorTabComp] = ColorFromName(colorTabComp); fColors[kColorBracket] = ColorFromName(colorBracket); fColors[kColorBadBracket] = ColorFromName(colorBadBracket); fColors[kColorPrompt] = ColorFromName(colorPrompt); } void ROOT::TextInputColorizer::ProcessTextChange(EditorRange& Modification, Text& input) { // The text has changed; look for word that are types. const std::string& text = input.GetText(); size_t modStart = Modification.fEdit.fStart; size_t inputLength = input.length(); // Find end of modified word: size_t modEnd = Modification.fEdit.fLength; if (modEnd == (size_t) -1) { modEnd = inputLength; } else { modEnd += modStart; if (modEnd > inputLength) { modEnd = inputLength; } else { while (modEnd < inputLength && IsAlnum_(text[modEnd])) ++modEnd; } } // Find beginning of modified word. Don't treat // "12ull" specially, it will fall out below. while (modStart && IsAlnum_(text[modStart])) --modStart; // Ignore spaces while (modStart < modEnd && isspace(text[modStart])) ++modStart; while (modEnd > modStart && isspace(text[modEnd])) --modStart; for (size_t i = modStart; i < modEnd;) { // i points to beginning of word here. if (isdigit(text[i])) { // "12", or "12ull". Default color. ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; while (i < modEnd && IsAlnum_(text[i])) { ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; } } else if (IsAlpha_(text[i])) { // identifier, but is it a type? size_t wordLen = 1; while (i + wordLen < modEnd && IsAlnum_(text[i + wordLen])) { ++wordLen; } std::string word = text.substr(i, wordLen); char color = kColorNone; if (gROOT->GetListOfTypes()->FindObject(word.c_str()) || gInterpreter->CheckClassInfo(word.c_str(), kFALSE)) { color = kColorType; } for (size_t ic = i; ic < i + wordLen; ++ic) { ExtendRangeAndSetColor(input, ic, color, Modification.fDisplay); } i += wordLen; } else { size_t wordLen = 1; while (i + wordLen < modEnd && !IsAlnum_(text[i + wordLen])) ++wordLen; for (size_t ic = i; ic < i + wordLen; ++ic) { // protect colored parens char oldColor = input.GetColor(ic); if (oldColor != kColorBracket && oldColor != kColorBadBracket) { ExtendRangeAndSetColor(input, ic, kColorNone, Modification.fDisplay); } } i += wordLen; } // skip trailing whitespace. while (i < modEnd && isspace(text[i])) { ExtendRangeAndSetColor(input, i, kColorNone, Modification.fDisplay); ++i; } } } void ROOT::TextInputColorizer::ProcessPromptChange(Text& prompt) { prompt.SetColor(Range::AllText(), kColorPrompt); } void ROOT::TextInputColorizer::ProcessCursorChange(size_t Cursor, Text& input, Range& DisplayR) { // Check each char to see if it is an opening bracket, // if so, check for its closing one and color them green. static const int numBrackets = 3; static const char bTypes[numBrackets][3] = {"()", "{}", "[]"}; if (input.empty()) return; if (fPrevBracketColor != kColorNone) { // Remove previous bracket coloring. const char* colors = &input.GetColors()[0]; const char* prevBracket = (const char*) memchr(colors, fPrevBracketColor, input.length()); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); if (fPrevBracketColor == kColorBracket) { // There will be two. prevBracket = (const char*) memchr(prevBracket, fPrevBracketColor, input.length() - (prevBracket - colors)); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); } } } } // locations of brackets stack<size_t> locBrackets; int foundParenIdx = -1; int parenType = 0; const std::string& text = input.GetText(); if (Cursor < input.length()) { // check against each bracket type for (; parenType < numBrackets; parenType++) { // if current char is equal to opening bracket, push onto stack if (text[Cursor] == bTypes[parenType][0]) { locBrackets.push(Cursor); foundParenIdx = 0; break; } else if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } } // current cursor char is not an open bracket, and there is a previous char // to check if (foundParenIdx == -1 && Cursor > 0) { // check previously typed char for being a closing bracket --Cursor; // check against each bracket type parenType = 0; for (; parenType < numBrackets; parenType++) { // if current char is equal to closing bracket, push onto stack if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } // no bracket found on either current or previous char, return. if (foundParenIdx == -1) { return; } } // terate through remaining letters until find a matching closing bracket // if another open bracket of the same type is found, push onto stack // and pop on next closing bracket match int direction = 1; if (foundParenIdx == 1) { direction = -1; } size_t lenLine = input.length(); // direction == -1: Cursor - 1 to front. size_t scanBegin = Cursor - 1; size_t scanLast = 0; if (direction == 1) { // direction == 1: Cursor + 1 to end. scanBegin = Cursor + 1; scanLast = lenLine - 1; } for (size_t i = scanBegin; true /*avoid "unsigned >= 0" condition*/; i += direction) { // if current char is equal to another opening bracket, push onto stack if (text[i] == bTypes[parenType][foundParenIdx]) { // push index of bracket locBrackets.push(i); } // if current char is equal to closing bracket else if (text[i] == bTypes[parenType][1 - foundParenIdx]) { // pop previous opening bracket off stack locBrackets.pop(); // if previous opening was the last entry and we are at the cursor, then highlight match if (locBrackets.empty()) { ExtendRangeAndSetColor(input, i, kColorBracket, DisplayR); ExtendRangeAndSetColor(input, Cursor, kColorBracket, DisplayR); fPrevBracketColor = kColorBracket; break; } } // loop termination check before possible underflow ("--0") if (i == scanLast) break; } if (!locBrackets.empty()) { ExtendRangeAndSetColor(input, Cursor, kColorBadBracket, DisplayR); fPrevBracketColor = kColorBadBracket; } } // matchParentheses <commit_msg>Default prompt has default color.<commit_after>// @(#)root/editline:$Id$ // Author: Mary-Louise Gill, 2009 /************************************************************************* * Copyright (C) 1995-2011, 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 "Getline_color.h" #include <stack> #include <string> #include "TROOT.h" #include "TInterpreter.h" #include "textinput/Range.h" #include "textinput/Text.h" using namespace std; using namespace textinput; namespace { Color ColorFromName(const char* name) { // Convert a color name to a Color. Color ret; std::string lowname(name); size_t lenname = strlen(name); for (size_t i = 0; i < lenname; ++i) lowname[i] = tolower(lowname[i]); if (lowname.find("bold") != std::string::npos || lowname.find("light") != std::string::npos) ret.fModifiers |= Color::kModBold; if (lowname.find("under") != std::string::npos) ret.fModifiers |= Color::kModUnderline; size_t poshash = lowname.find('#'); size_t lenrgb = 0; if (poshash != std::string::npos) { int endrgb = poshash + 1; while ((lowname[endrgb] >= '0' && lowname[endrgb] <= '9') || (lowname[endrgb] >= 'a' && lowname[endrgb] <= 'f')) { ++endrgb; } lenrgb = endrgb - poshash - 1; } int rgb[3] = {0}; if (lenrgb == 3) { for (int i = 0; i < 3; ++i) { rgb[i] = lowname[poshash + 1 + i] - '0'; if (rgb[i] > 9) { rgb[i] = rgb[i] + '0' - 'a' + 10; } rgb[i] *= 16; // only upper 4 bits are set. } return ret; } else if (lenrgb == 6) { for (int i = 0; i < 6; ++i) { int v = lowname[poshash + 1 + i] - '0'; if (v > 9) { v = v + '0' - 'a' + 10; } if (i % 2 == 0) { v *= 16; } rgb[i / 2] += v; } ret.fR = rgb[0]; ret.fG = rgb[1]; ret.fB = rgb[2]; return ret; } else { if (lowname.find("default") != std::string::npos) { return ret; } static const char* colornames[] = { "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", 0 }; static const unsigned char colorrgb[][3] = { {0,0,0}, {127,0,0}, {0,127,0}, {127,127,0}, {0,0,127}, {127,0,127}, {0,127,127}, {127,127,127}, {0} }; for (int i = 0; colornames[i]; ++i) { if (lowname.find(colornames[i]) != std::string::npos) { int boldify = 0; if (ret.fModifiers & Color::kModBold) boldify = 64; ret.fR = colorrgb[i][0] + boldify; ret.fG = colorrgb[i][1] + boldify; ret.fB = colorrgb[i][2] + boldify; return ret; } } } fprintf(stderr, "Getline_color/ColorFromName: cannot parse color %s!\n", name); return Color(); } // ColorFromName() bool IsAlnum_(char c) { return c == '_' || isalnum(c); } bool IsAlpha_(char c) { return c == '_' || isalpha(c); } void ExtendRangeAndSetColor(Text& input, size_t idx, char col, Range& disp) { // Utility function that updates the display modification range if the // color at index idx is different from what it was before. if (input.GetColor(idx) != col) { input.SetColor(idx, col); disp.Extend(idx); } } } // unnamed namespace ROOT::TextInputColorizer::TextInputColorizer(): fPrevBracketColor(kColorNone) { // Set the default colors. // fColors[kColorNone] stays default initialized. fColors[kColorType] = ColorFromName("blue"); fColors[kColorTabComp] = ColorFromName("magenta"); fColors[kColorBracket] = ColorFromName("green"); fColors[kColorBadBracket] = ColorFromName("red"); fColors[kColorPrompt] = ColorFromName("default"); } ROOT::TextInputColorizer::~TextInputColorizer() { // pin vtable } bool ROOT::TextInputColorizer::GetColor(char type, Color& col) { // Set the Color corresponding to an entry in EColorTypes. // Returns false if the type index is out of range. if (type < (int)kNumColors) { col = fColors[(size_t)type]; return true; } col = Color(); return false; } void ROOT::TextInputColorizer::SetColors(const char* colorType, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { // Set the colors of the different items as either // #RGB // #RRGGBB or // color name, optionally prepended by "underline" or "bold" fColors[kColorType] = ColorFromName(colorType); fColors[kColorTabComp] = ColorFromName(colorTabComp); fColors[kColorBracket] = ColorFromName(colorBracket); fColors[kColorBadBracket] = ColorFromName(colorBadBracket); fColors[kColorPrompt] = ColorFromName(colorPrompt); } void ROOT::TextInputColorizer::ProcessTextChange(EditorRange& Modification, Text& input) { // The text has changed; look for word that are types. const std::string& text = input.GetText(); size_t modStart = Modification.fEdit.fStart; size_t inputLength = input.length(); // Find end of modified word: size_t modEnd = Modification.fEdit.fLength; if (modEnd == (size_t) -1) { modEnd = inputLength; } else { modEnd += modStart; if (modEnd > inputLength) { modEnd = inputLength; } else { while (modEnd < inputLength && IsAlnum_(text[modEnd])) ++modEnd; } } // Find beginning of modified word. Don't treat // "12ull" specially, it will fall out below. while (modStart && IsAlnum_(text[modStart])) --modStart; // Ignore spaces while (modStart < modEnd && isspace(text[modStart])) ++modStart; while (modEnd > modStart && isspace(text[modEnd])) --modStart; for (size_t i = modStart; i < modEnd;) { // i points to beginning of word here. if (isdigit(text[i])) { // "12", or "12ull". Default color. ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; while (i < modEnd && IsAlnum_(text[i])) { ExtendRangeAndSetColor(input, i, 0, Modification.fDisplay); ++i; } } else if (IsAlpha_(text[i])) { // identifier, but is it a type? size_t wordLen = 1; while (i + wordLen < modEnd && IsAlnum_(text[i + wordLen])) { ++wordLen; } std::string word = text.substr(i, wordLen); char color = kColorNone; if (gROOT->GetListOfTypes()->FindObject(word.c_str()) || gInterpreter->CheckClassInfo(word.c_str(), kFALSE)) { color = kColorType; } for (size_t ic = i; ic < i + wordLen; ++ic) { ExtendRangeAndSetColor(input, ic, color, Modification.fDisplay); } i += wordLen; } else { size_t wordLen = 1; while (i + wordLen < modEnd && !IsAlnum_(text[i + wordLen])) ++wordLen; for (size_t ic = i; ic < i + wordLen; ++ic) { // protect colored parens char oldColor = input.GetColor(ic); if (oldColor != kColorBracket && oldColor != kColorBadBracket) { ExtendRangeAndSetColor(input, ic, kColorNone, Modification.fDisplay); } } i += wordLen; } // skip trailing whitespace. while (i < modEnd && isspace(text[i])) { ExtendRangeAndSetColor(input, i, kColorNone, Modification.fDisplay); ++i; } } } void ROOT::TextInputColorizer::ProcessPromptChange(Text& prompt) { prompt.SetColor(Range::AllText(), kColorPrompt); } void ROOT::TextInputColorizer::ProcessCursorChange(size_t Cursor, Text& input, Range& DisplayR) { // Check each char to see if it is an opening bracket, // if so, check for its closing one and color them green. static const int numBrackets = 3; static const char bTypes[numBrackets][3] = {"()", "{}", "[]"}; if (input.empty()) return; if (fPrevBracketColor != kColorNone) { // Remove previous bracket coloring. const char* colors = &input.GetColors()[0]; const char* prevBracket = (const char*) memchr(colors, fPrevBracketColor, input.length()); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); if (fPrevBracketColor == kColorBracket) { // There will be two. prevBracket = (const char*) memchr(prevBracket, fPrevBracketColor, input.length() - (prevBracket - colors)); if (prevBracket) { ExtendRangeAndSetColor(input, prevBracket - colors, kColorNone, DisplayR); } } } } // locations of brackets stack<size_t> locBrackets; int foundParenIdx = -1; int parenType = 0; const std::string& text = input.GetText(); if (Cursor < input.length()) { // check against each bracket type for (; parenType < numBrackets; parenType++) { // if current char is equal to opening bracket, push onto stack if (text[Cursor] == bTypes[parenType][0]) { locBrackets.push(Cursor); foundParenIdx = 0; break; } else if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } } // current cursor char is not an open bracket, and there is a previous char // to check if (foundParenIdx == -1 && Cursor > 0) { // check previously typed char for being a closing bracket --Cursor; // check against each bracket type parenType = 0; for (; parenType < numBrackets; parenType++) { // if current char is equal to closing bracket, push onto stack if (text[Cursor] == bTypes[parenType][1]) { locBrackets.push(Cursor); foundParenIdx = 1; break; } } // no bracket found on either current or previous char, return. if (foundParenIdx == -1) { return; } } // terate through remaining letters until find a matching closing bracket // if another open bracket of the same type is found, push onto stack // and pop on next closing bracket match int direction = 1; if (foundParenIdx == 1) { direction = -1; } size_t lenLine = input.length(); // direction == -1: Cursor - 1 to front. size_t scanBegin = Cursor - 1; size_t scanLast = 0; if (direction == 1) { // direction == 1: Cursor + 1 to end. scanBegin = Cursor + 1; scanLast = lenLine - 1; } for (size_t i = scanBegin; true /*avoid "unsigned >= 0" condition*/; i += direction) { // if current char is equal to another opening bracket, push onto stack if (text[i] == bTypes[parenType][foundParenIdx]) { // push index of bracket locBrackets.push(i); } // if current char is equal to closing bracket else if (text[i] == bTypes[parenType][1 - foundParenIdx]) { // pop previous opening bracket off stack locBrackets.pop(); // if previous opening was the last entry and we are at the cursor, then highlight match if (locBrackets.empty()) { ExtendRangeAndSetColor(input, i, kColorBracket, DisplayR); ExtendRangeAndSetColor(input, Cursor, kColorBracket, DisplayR); fPrevBracketColor = kColorBracket; break; } } // loop termination check before possible underflow ("--0") if (i == scanLast) break; } if (!locBrackets.empty()) { ExtendRangeAndSetColor(input, Cursor, kColorBadBracket, DisplayR); fPrevBracketColor = kColorBadBracket; } } // matchParentheses <|endoftext|>
<commit_before>#include "dreal/solver/icp_seq.h" #include <tuple> #include <utility> #include "dreal/solver/branch.h" #include "dreal/solver/icp_stat.h" #include "dreal/util/interrupt.h" #include "dreal/util/logging.h" using std::pair; using std::tie; using std::vector; namespace dreal { IcpSeq::IcpSeq(const Config& config) : Icp{config} {} bool IcpSeq::CheckSat(const Contractor& contractor, const vector<FormulaEvaluator>& formula_evaluators, ContractorStatus* const cs) { // Use the stacking policy set by the configuration. stack_left_box_first_ = config().stack_left_box_first(); static IcpStat stat{DREAL_LOG_INFO_ENABLED}; DREAL_LOG_DEBUG("IcpSeq::CheckSat()"); // Stack of Box x BranchingPoint. vector<pair<Box, int>> stack; stack.emplace_back( cs->box(), // -1 indicates that the very first box does not come from a branching. -1); // `current_box` always points to the box in the contractor status // as a mutable reference. Box& current_box{cs->mutable_box()}; // `current_branching_point` always points to the branching_point in // the contractor status as a mutable reference. int& current_branching_point{cs->mutable_branching_point()}; TimerGuard prune_timer_guard(&stat.timer_prune_, stat.enabled(), false /* start_timer */); TimerGuard eval_timer_guard(&stat.timer_eval_, stat.enabled(), false /* start_timer */); TimerGuard branch_timer_guard(&stat.timer_branch_, stat.enabled(), false /* start_timer */); while (!stack.empty()) { DREAL_LOG_DEBUG("IcpSeq::CheckSat() Loop Head"); // Note that 'DREAL_CHECK_INTERRUPT' is only defined in setup.py, // when we build dReal python package. #ifdef DREAL_CHECK_INTERRUPT if (g_interrupted) { DREAL_LOG_DEBUG("KeyboardInterrupt(SIGINT) Detected."); throw std::runtime_error("KeyboardInterrupt(SIGINT) Detected."); } #endif // 1. Pop the current box from the stack tie(current_box, current_branching_point) = stack.back(); stack.pop_back(); // 2. Prune the current box. DREAL_LOG_TRACE("IcpSeq::CheckSat() Current Box:\n{}", current_box); prune_timer_guard.resume(); contractor.Prune(cs); prune_timer_guard.pause(); stat.num_prune_++; DREAL_LOG_TRACE("IcpSeq::CheckSat() After pruning, the current box =\n{}", current_box); if (current_box.empty()) { // 3.1. The box is empty after pruning. DREAL_LOG_DEBUG("IcpSeq::CheckSat() Box is empty after pruning"); continue; } // 3.2. The box is non-empty. Check if the box is still feasible // under evaluation and it's small enough. eval_timer_guard.resume(); const optional<ibex::BitSet> evaluation_result{ EvaluateBox(formula_evaluators, current_box, config().precision(), cs)}; if (!evaluation_result) { // 3.2.1. We detect that the current box is not a feasible solution. DREAL_LOG_DEBUG( "IcpSeq::CheckSat() Detect that the current box is not feasible by " "evaluation:\n{}", current_box); continue; } if (evaluation_result->empty()) { // 3.2.2. delta-SAT : We find a box which is smaller enough. DREAL_LOG_DEBUG("IcpSeq::CheckSat() Found a delta-box:\n{}", current_box); return true; } eval_timer_guard.pause(); // 3.2.3. This box is bigger than delta. Need branching. branch_timer_guard.resume(); if (!Branch(current_box, *evaluation_result, stack_left_box_first_, &stack)) { DREAL_LOG_DEBUG( "IcpSeq::CheckSat() Found that the current box is not satisfying " "delta-condition but it's not bisectable.:\n{}", current_box); return true; } branch_timer_guard.pause(); // We alternate between adding-the-left-box-first policy and // adding-the-right-box-first policy. stack_left_box_first_ = !stack_left_box_first_; stat.num_branch_++; } DREAL_LOG_DEBUG("IcpSeq::CheckSat() No solution"); return false; } } // namespace dreal <commit_msg>fix(solver/icp_seq.cc): Fix eval timer<commit_after>#include "dreal/solver/icp_seq.h" #include <tuple> #include <utility> #include "dreal/solver/branch.h" #include "dreal/solver/icp_stat.h" #include "dreal/util/interrupt.h" #include "dreal/util/logging.h" using std::pair; using std::tie; using std::vector; namespace dreal { IcpSeq::IcpSeq(const Config& config) : Icp{config} {} bool IcpSeq::CheckSat(const Contractor& contractor, const vector<FormulaEvaluator>& formula_evaluators, ContractorStatus* const cs) { // Use the stacking policy set by the configuration. stack_left_box_first_ = config().stack_left_box_first(); static IcpStat stat{DREAL_LOG_INFO_ENABLED}; DREAL_LOG_DEBUG("IcpSeq::CheckSat()"); // Stack of Box x BranchingPoint. vector<pair<Box, int>> stack; stack.emplace_back( cs->box(), // -1 indicates that the very first box does not come from a branching. -1); // `current_box` always points to the box in the contractor status // as a mutable reference. Box& current_box{cs->mutable_box()}; // `current_branching_point` always points to the branching_point in // the contractor status as a mutable reference. int& current_branching_point{cs->mutable_branching_point()}; TimerGuard prune_timer_guard(&stat.timer_prune_, stat.enabled(), false /* start_timer */); TimerGuard eval_timer_guard(&stat.timer_eval_, stat.enabled(), false /* start_timer */); TimerGuard branch_timer_guard(&stat.timer_branch_, stat.enabled(), false /* start_timer */); while (!stack.empty()) { DREAL_LOG_DEBUG("IcpSeq::CheckSat() Loop Head"); // Note that 'DREAL_CHECK_INTERRUPT' is only defined in setup.py, // when we build dReal python package. #ifdef DREAL_CHECK_INTERRUPT if (g_interrupted) { DREAL_LOG_DEBUG("KeyboardInterrupt(SIGINT) Detected."); throw std::runtime_error("KeyboardInterrupt(SIGINT) Detected."); } #endif // 1. Pop the current box from the stack tie(current_box, current_branching_point) = stack.back(); stack.pop_back(); // 2. Prune the current box. DREAL_LOG_TRACE("IcpSeq::CheckSat() Current Box:\n{}", current_box); prune_timer_guard.resume(); contractor.Prune(cs); prune_timer_guard.pause(); stat.num_prune_++; DREAL_LOG_TRACE("IcpSeq::CheckSat() After pruning, the current box =\n{}", current_box); if (current_box.empty()) { // 3.1. The box is empty after pruning. DREAL_LOG_DEBUG("IcpSeq::CheckSat() Box is empty after pruning"); continue; } // 3.2. The box is non-empty. Check if the box is still feasible // under evaluation and it's small enough. eval_timer_guard.resume(); const optional<ibex::BitSet> evaluation_result{ EvaluateBox(formula_evaluators, current_box, config().precision(), cs)}; if (!evaluation_result) { // 3.2.1. We detect that the current box is not a feasible solution. DREAL_LOG_DEBUG( "IcpSeq::CheckSat() Detect that the current box is not feasible by " "evaluation:\n{}", current_box); eval_timer_guard.pause(); continue; } if (evaluation_result->empty()) { // 3.2.2. delta-SAT : We find a box which is smaller enough. DREAL_LOG_DEBUG("IcpSeq::CheckSat() Found a delta-box:\n{}", current_box); return true; } eval_timer_guard.pause(); // 3.2.3. This box is bigger than delta. Need branching. branch_timer_guard.resume(); if (!Branch(current_box, *evaluation_result, stack_left_box_first_, &stack)) { DREAL_LOG_DEBUG( "IcpSeq::CheckSat() Found that the current box is not satisfying " "delta-condition but it's not bisectable.:\n{}", current_box); return true; } branch_timer_guard.pause(); // We alternate between adding-the-left-box-first policy and // adding-the-right-box-first policy. stack_left_box_first_ = !stack_left_box_first_; stat.num_branch_++; } DREAL_LOG_DEBUG("IcpSeq::CheckSat() No solution"); return false; } } // namespace dreal <|endoftext|>