text
stringlengths
54
60.6k
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 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 "CodeUnit.h" #include "Config.h" #include "visitors/DeclarationVisitor.h" #include "visitors/ExpressionVisitor.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "OOModel/src/expressions/MetaCallExpression.h" #include "OOModel/src/declarations/TypeAlias.h" namespace CppExport { CodeUnit::CodeUnit(QString name, Model::Node* node) : name_{name}, node_{node}, headerPart_{this}, sourcePart_{this} {} void CodeUnit::calculateSourceFragments() { if (auto classs = DCast<OOModel::Class>(node())) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visitTopLevelClass(classs)); sourcePart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visitTopLevelClass(classs)); } else if (auto module = DCast<OOModel::Module>(node())) { auto fragment = new Export::CompositeFragment(node()); for (auto metaDefinition : Model::Node::childrenOfType<OOModel::MetaDefinition>(module)) *fragment << DeclarationVisitor(HEADER_VISITOR).visit(metaDefinition); headerPart()->setSourceFragment(fragment); } else if (auto method = DCast<OOModel::Method>(node())) { if (method->typeArguments()->isEmpty() && !method->modifiers()->isSet(OOModel::Modifier::Inline)) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visit(method)); if (!method->modifiers()->isSet(OOModel::Modifier::Abstract) && !method->modifiers()->isSet(OOModel::Modifier::Deleted)) sourcePart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visit(method)); } else { headerPart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visit(method)); } } else if (auto method = DCast<OOModel::Field>(node())) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visit(method)); sourcePart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visit(method)); } else if (auto typeAlias = DCast<OOModel::TypeAlias>(node())) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visit(typeAlias)); } else if (auto metaCall = DCast<OOModel::MetaCallExpression>(node())) { auto ooReference = DCast<OOModel::ReferenceExpression>(metaCall->callee()); if (Config::instance().metaCallLocationMap().value(ooReference->name()) != "cpp") headerPart()->setSourceFragment(ExpressionVisitor(SOURCE_VISITOR).visit(metaCall)); else sourcePart()->setSourceFragment(ExpressionVisitor(SOURCE_VISITOR).visit(metaCall)); } else Q_ASSERT(false); } void CodeUnit::calculateDependencies(QList<CodeUnit*>& allUnits) { headerPart()->calculateDependencies(allUnits); sourcePart()->calculateDependencies(allUnits); } } <commit_msg>improve support for meta definition code units<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 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 "CodeUnit.h" #include "Config.h" #include "visitors/DeclarationVisitor.h" #include "visitors/ExpressionVisitor.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "OOModel/src/expressions/MetaCallExpression.h" #include "OOModel/src/declarations/TypeAlias.h" namespace CppExport { CodeUnit::CodeUnit(QString name, Model::Node* node) : name_{name}, node_{node}, headerPart_{this}, sourcePart_{this} {} void CodeUnit::calculateSourceFragments() { if (auto classs = DCast<OOModel::Class>(node())) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visitTopLevelClass(classs)); sourcePart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visitTopLevelClass(classs)); } else if (auto module = DCast<OOModel::Module>(node())) { auto fragment = new Export::CompositeFragment(node()); for (auto metaDefinition : Model::Node::childrenOfType<OOModel::MetaDefinition>(module)) *fragment << DeclarationVisitor(HEADER_VISITOR).visit(metaDefinition); headerPart()->setSourceFragment(fragment); } else if (auto method = DCast<OOModel::Method>(node())) { if (method->typeArguments()->isEmpty() && !method->modifiers()->isSet(OOModel::Modifier::Inline)) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visit(method)); if (!method->modifiers()->isSet(OOModel::Modifier::Abstract) && !method->modifiers()->isSet(OOModel::Modifier::Deleted)) sourcePart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visit(method)); } else { headerPart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visit(method)); } } else if (auto method = DCast<OOModel::Field>(node())) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visit(method)); sourcePart()->setSourceFragment(DeclarationVisitor(SOURCE_VISITOR).visit(method)); } else if (auto typeAlias = DCast<OOModel::TypeAlias>(node())) { headerPart()->setSourceFragment(DeclarationVisitor(HEADER_VISITOR).visit(typeAlias)); } else if (auto metaCall = DCast<OOModel::MetaCallExpression>(node())) { auto ooReference = DCast<OOModel::ReferenceExpression>(metaCall->callee()); if (Config::instance().metaCallLocationMap().value(ooReference->name()) != "cpp") headerPart()->setSourceFragment(ExpressionVisitor(SOURCE_VISITOR).visit(metaCall)); else sourcePart()->setSourceFragment(ExpressionVisitor(SOURCE_VISITOR).visit(metaCall)); } else if (auto metaDefinition = DCast<OOModel::MetaDefinition>(node())) { // TODO: add a similar map to the metaCallLocationMap (maybe even unify them?) headerPart()->setSourceFragment(DeclarationVisitor(MACRO_VISITOR).visit(metaDefinition)); } else Q_ASSERT(false); } void CodeUnit::calculateDependencies(QList<CodeUnit*>& allUnits) { headerPart()->calculateDependencies(allUnits); sourcePart()->calculateDependencies(allUnits); } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/fapi2_i2c_access.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file fapi2_i2c_access.H /// @brief Common file that defines the i2c access functions that /// platform code must implement. /// #ifndef _FAPI2_COMMON_I2C_ACCESS_H_ #define _FAPI2_COMMON_I2C_ACCESS_H_ #include <stdint.h> #include <vector> #include <return_code.H> #include <target.H> namespace fapi2 { /// @brief Reads data via i2c from the target /// /// Example use (seeprom read 8 bytes w/ 2-byte address: 0x01B0): /// std::vector<uint8_t> addr = {0x01, 0xB0}; /// std::vector<uint8_t> data; /// size_t len = 8; /// FAPI_TRY(getI2c(target, len, addr, data)); /// data should contain the 8 bytes starting at address 0x01B0 /// /// Example use (smbus read 5 bytes w/ 1-byte command: 0x02): /// std::vector<uint8_t> command = {0x02}; /// std::vector<uint8_t> data; /// size_t len = 5; /// FAPI_TRY(getI2c(target, len, command, data)); /// data should contain 5 bytes, first byte with the data length(4) /// remaining four bytes will be the data requested from the command /// /// @tparam K the type (Kind) of target, from i_target /// @tparam V the type of the target's Value, from i_target /// @param[in] i_target HW target to operate on. /// @param[in] i_get_size Size that getI2c will read from the HW target. /// @param[in] i_data Buffer that holds data to write to the HW target. /// May be empty if no address/command is required /// before the read. /// @param[out] o_data Buffer that holds data read from HW target. /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. template< TargetType K, typename V > inline ReturnCode getI2c(const Target<K, V>& i_target, const size_t i_get_size, const std::vector<uint8_t>& i_data, std::vector<uint8_t>& o_data); /// @brief Writes data via i2c to the target. /// /// Example use (seeprom write 4 bytes of zeros w/ 2-byte address: 0x0208): /// std::vector<uint8_t> addr_data = {0x02, 0x08, 0x00, 0x00, 0x00, 0x00}; /// FAPI_TRY(getI2c(target, addr_data)); /// /// Example use (smbus write 1 data length byte + 4 bytes of zeros w/ 1-byte command: 0x01): /// std::vector<uint8_t> command_data = {0x01, 0x04, 0x00, 0x00, 0x00, 0x00}; /// FAPI_TRY(getI2c(target, command_data)); /// /// @tparam K the type (Kind) of target, from i_target /// @tparam V the type of the target's Value, from i_target /// @param[in] i_target HW target to operate on. /// @param[in] i_data Buffer that holds data to write to the HW target. /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. template< TargetType K, typename V > inline ReturnCode putI2c(const Target<K, V>& i_target, const std::vector<uint8_t>& i_data); }; #endif // _FAPI2_COMMON_I2C_ACCESS_H_ <commit_msg>Fix i2c doxy and update i2c_access.H doxy to match fapi2_access_i2c.H<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/fapi2_i2c_access.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file fapi2_i2c_access.H /// @brief Common file that defines the i2c access functions that /// platform code must implement. /// #ifndef _FAPI2_COMMON_I2C_ACCESS_H_ #define _FAPI2_COMMON_I2C_ACCESS_H_ #include <stdint.h> #include <vector> #include <return_code.H> #include <target.H> namespace fapi2 { /// @brief Reads data via i2c from the target /// /// Example use (seeprom read 8 bytes w/ 2-byte address: 0x01B0): /// std::vector<uint8_t> addr = {0x01, 0xB0}; /// std::vector<uint8_t> data; /// size_t len = 8; /// FAPI_TRY(getI2c(target, len, addr, data)); /// data should contain the 8 bytes starting at address 0x01B0 /// /// Example use (smbus read 5 bytes w/ 1-byte command: 0x02): /// std::vector<uint8_t> command = {0x02}; /// std::vector<uint8_t> data; /// size_t len = 5; /// FAPI_TRY(getI2c(target, len, command, data)); /// data should contain 5 bytes, first byte with the data length(4) /// remaining four bytes will be the data requested from the command /// /// @tparam K the type (Kind) of target, from i_target /// @tparam V the type of the target's Value, from i_target /// @param[in] i_target HW target to operate on. /// @param[in] i_get_size Size that getI2c will read from the HW target. /// @param[in] i_data Buffer that holds data to write to the HW target. /// May be empty if no address/command is required /// before the read. /// @param[out] o_data Buffer that holds data read from HW target. /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. template< TargetType K, typename V > inline ReturnCode getI2c(const Target<K, V>& i_target, const size_t i_get_size, const std::vector<uint8_t>& i_data, std::vector<uint8_t>& o_data); /// @brief Writes data via i2c to the target. /// /// Example use (seeprom write 4 bytes of zeros w/ 2-byte address: 0x0208): /// std::vector<uint8_t> addr_data = {0x02, 0x08, 0x00, 0x00, 0x00, 0x00}; /// FAPI_TRY(putI2c(target, addr_data)); /// /// Example use (smbus write 1 data length byte + 4 bytes of zeros w/ 1-byte command: 0x01): /// std::vector<uint8_t> command_data = {0x01, 0x04, 0x00, 0x00, 0x00, 0x00}; /// FAPI_TRY(putI2c(target, command_data)); /// /// @tparam K the type (Kind) of target, from i_target /// @tparam V the type of the target's Value, from i_target /// @param[in] i_target HW target to operate on. /// @param[in] i_data Buffer that holds data to write to the HW target. /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. template< TargetType K, typename V > inline ReturnCode putI2c(const Target<K, V>& i_target, const std::vector<uint8_t>& i_data); }; #endif // _FAPI2_COMMON_I2C_ACCESS_H_ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #pragma once #include <cassert> #include <uavcan/stdint.hpp> #include <uavcan/transport/transfer_listener.hpp> #include <uavcan/transport/outgoing_transfer_registry.hpp> #include <uavcan/transport/can_io.hpp> #include <uavcan/linked_list.hpp> namespace uavcan { class Dispatcher; class LoopbackFrameListenerBase : public LinkedListNode<LoopbackFrameListenerBase>, Noncopyable { Dispatcher& dispatcher_; protected: LoopbackFrameListenerBase(Dispatcher& dispatcher) : dispatcher_(dispatcher) { } virtual ~LoopbackFrameListenerBase() { stopListening(); } void startListening(); void stopListening(); bool isListening() const; Dispatcher& getDispatcher() { return dispatcher_; } public: virtual void handleLoopbackFrame(const RxFrame& frame) = 0; }; class LoopbackFrameListenerRegistry : Noncopyable { LinkedListRoot<LoopbackFrameListenerBase> listeners_; public: void add(LoopbackFrameListenerBase* listener); void remove(LoopbackFrameListenerBase* listener); bool doesExist(const LoopbackFrameListenerBase* listener) const; unsigned int getNumListeners() const { return listeners_.getLength(); } void invokeListeners(RxFrame& frame); }; class Dispatcher : Noncopyable { CanIOManager canio_; ISystemClock& sysclock_; IOutgoingTransferRegistry& outgoing_transfer_reg_; class ListenerRegistry { LinkedListRoot<TransferListenerBase> list_; class DataTypeIDInsertionComparator { const DataTypeID id_; public: DataTypeIDInsertionComparator(DataTypeID id) : id_(id) { } bool operator()(const TransferListenerBase* listener) const { assert(listener); return id_ > listener->getDataTypeDescriptor().getID(); } }; public: enum Mode { UniqueListener, ManyListeners }; bool add(TransferListenerBase* listener, Mode mode); void remove(TransferListenerBase* listener); bool exists(DataTypeID dtid) const; void cleanup(MonotonicTime ts); void handleFrame(const RxFrame& frame); int getNumEntries() const { return list_.getLength(); } }; ListenerRegistry lmsg_; ListenerRegistry lsrv_req_; ListenerRegistry lsrv_resp_; LoopbackFrameListenerRegistry loopback_listeners_; NodeID self_node_id_; void handleFrame(const CanRxFrame& can_frame); void handleLoopbackFrame(const CanRxFrame& can_frame); public: Dispatcher(ICanDriver& driver, IAllocator& allocator, ISystemClock& sysclock, IOutgoingTransferRegistry& otr) : canio_(driver, allocator, sysclock) , sysclock_(sysclock) , outgoing_transfer_reg_(otr) { } int spin(MonotonicTime deadline); /** * Refer to CanIOManager::send() for the parameter description */ int send(const Frame& frame, MonotonicTime tx_deadline, MonotonicTime blocking_deadline, CanTxQueue::Qos qos, CanIOFlags flags, uint8_t iface_mask); void cleanup(MonotonicTime ts); bool registerMessageListener(TransferListenerBase* listener); bool registerServiceRequestListener(TransferListenerBase* listener); bool registerServiceResponseListener(TransferListenerBase* listener); void unregisterMessageListener(TransferListenerBase* listener); void unregisterServiceRequestListener(TransferListenerBase* listener); void unregisterServiceResponseListener(TransferListenerBase* listener); bool hasSubscriber(DataTypeID dtid) const; bool hasPublisher(DataTypeID dtid) const; bool hasServer(DataTypeID dtid) const; int getNumMessageListeners() const { return lmsg_.getNumEntries(); } int getNumServiceRequestListeners() const { return lsrv_req_.getNumEntries(); } int getNumServiceResponseListeners() const { return lsrv_resp_.getNumEntries(); } IOutgoingTransferRegistry& getOutgoingTransferRegistry() { return outgoing_transfer_reg_; } LoopbackFrameListenerRegistry& getLoopbackFrameListenerRegistry() { return loopback_listeners_; } NodeID getNodeID() const { return self_node_id_; } bool setNodeID(NodeID nid); const ISystemClock& getSystemClock() const { return sysclock_; } ISystemClock& getSystemClock() { return sysclock_; } }; } <commit_msg>Dispatcher::getCanIOManager()<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #pragma once #include <cassert> #include <uavcan/stdint.hpp> #include <uavcan/transport/transfer_listener.hpp> #include <uavcan/transport/outgoing_transfer_registry.hpp> #include <uavcan/transport/can_io.hpp> #include <uavcan/linked_list.hpp> namespace uavcan { class Dispatcher; class LoopbackFrameListenerBase : public LinkedListNode<LoopbackFrameListenerBase>, Noncopyable { Dispatcher& dispatcher_; protected: LoopbackFrameListenerBase(Dispatcher& dispatcher) : dispatcher_(dispatcher) { } virtual ~LoopbackFrameListenerBase() { stopListening(); } void startListening(); void stopListening(); bool isListening() const; Dispatcher& getDispatcher() { return dispatcher_; } public: virtual void handleLoopbackFrame(const RxFrame& frame) = 0; }; class LoopbackFrameListenerRegistry : Noncopyable { LinkedListRoot<LoopbackFrameListenerBase> listeners_; public: void add(LoopbackFrameListenerBase* listener); void remove(LoopbackFrameListenerBase* listener); bool doesExist(const LoopbackFrameListenerBase* listener) const; unsigned int getNumListeners() const { return listeners_.getLength(); } void invokeListeners(RxFrame& frame); }; class Dispatcher : Noncopyable { CanIOManager canio_; ISystemClock& sysclock_; IOutgoingTransferRegistry& outgoing_transfer_reg_; class ListenerRegistry { LinkedListRoot<TransferListenerBase> list_; class DataTypeIDInsertionComparator { const DataTypeID id_; public: DataTypeIDInsertionComparator(DataTypeID id) : id_(id) { } bool operator()(const TransferListenerBase* listener) const { assert(listener); return id_ > listener->getDataTypeDescriptor().getID(); } }; public: enum Mode { UniqueListener, ManyListeners }; bool add(TransferListenerBase* listener, Mode mode); void remove(TransferListenerBase* listener); bool exists(DataTypeID dtid) const; void cleanup(MonotonicTime ts); void handleFrame(const RxFrame& frame); int getNumEntries() const { return list_.getLength(); } }; ListenerRegistry lmsg_; ListenerRegistry lsrv_req_; ListenerRegistry lsrv_resp_; LoopbackFrameListenerRegistry loopback_listeners_; NodeID self_node_id_; void handleFrame(const CanRxFrame& can_frame); void handleLoopbackFrame(const CanRxFrame& can_frame); public: Dispatcher(ICanDriver& driver, IAllocator& allocator, ISystemClock& sysclock, IOutgoingTransferRegistry& otr) : canio_(driver, allocator, sysclock) , sysclock_(sysclock) , outgoing_transfer_reg_(otr) { } int spin(MonotonicTime deadline); /** * Refer to CanIOManager::send() for the parameter description */ int send(const Frame& frame, MonotonicTime tx_deadline, MonotonicTime blocking_deadline, CanTxQueue::Qos qos, CanIOFlags flags, uint8_t iface_mask); void cleanup(MonotonicTime ts); bool registerMessageListener(TransferListenerBase* listener); bool registerServiceRequestListener(TransferListenerBase* listener); bool registerServiceResponseListener(TransferListenerBase* listener); void unregisterMessageListener(TransferListenerBase* listener); void unregisterServiceRequestListener(TransferListenerBase* listener); void unregisterServiceResponseListener(TransferListenerBase* listener); bool hasSubscriber(DataTypeID dtid) const; bool hasPublisher(DataTypeID dtid) const; bool hasServer(DataTypeID dtid) const; int getNumMessageListeners() const { return lmsg_.getNumEntries(); } int getNumServiceRequestListeners() const { return lsrv_req_.getNumEntries(); } int getNumServiceResponseListeners() const { return lsrv_resp_.getNumEntries(); } IOutgoingTransferRegistry& getOutgoingTransferRegistry() { return outgoing_transfer_reg_; } LoopbackFrameListenerRegistry& getLoopbackFrameListenerRegistry() { return loopback_listeners_; } NodeID getNodeID() const { return self_node_id_; } bool setNodeID(NodeID nid); const ISystemClock& getSystemClock() const { return sysclock_; } ISystemClock& getSystemClock() { return sysclock_; } const CanIOManager& getCanIOManager() const { return canio_; } }; } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SkPDFGraphicState.h" #include "SkPDFUtils.h" #include "SkStream.h" #include "SkTypes.h" namespace { const char* blendModeFromXfermode(SkXfermode::Mode mode) { switch (mode) { case SkXfermode::kSrcOver_Mode: return "Normal"; case SkXfermode::kMultiply_Mode: return "Multiply"; case SkXfermode::kScreen_Mode: return "Screen"; case SkXfermode::kOverlay_Mode: return "Overlay"; case SkXfermode::kDarken_Mode: return "Darken"; case SkXfermode::kLighten_Mode: return "Lighten"; case SkXfermode::kColorDodge_Mode: return "ColorDodge"; case SkXfermode::kColorBurn_Mode: return "ColorBurn"; case SkXfermode::kHardLight_Mode: return "HardLight"; case SkXfermode::kSoftLight_Mode: return "SoftLight"; case SkXfermode::kDifference_Mode: return "Difference"; case SkXfermode::kExclusion_Mode: return "Exclusion"; // These are handled in SkPDFDevice::setUpContentEntry. case SkXfermode::kClear_Mode: case SkXfermode::kSrc_Mode: case SkXfermode::kDst_Mode: case SkXfermode::kDstOver_Mode: return "Normal"; // TODO(vandebo) Figure out if we can support more of these modes. case SkXfermode::kSrcIn_Mode: case SkXfermode::kDstIn_Mode: case SkXfermode::kSrcOut_Mode: case SkXfermode::kDstOut_Mode: case SkXfermode::kSrcATop_Mode: case SkXfermode::kDstATop_Mode: case SkXfermode::kXor_Mode: case SkXfermode::kPlus_Mode: return NULL; } return NULL; } } SkPDFGraphicState::~SkPDFGraphicState() { SkAutoMutexAcquire lock(canonicalPaintsMutex()); int index = find(fPaint); SkASSERT(index >= 0); canonicalPaints().removeShuffle(index); } void SkPDFGraphicState::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { populateDict(); SkPDFDict::emitObject(stream, catalog, indirect); } // static size_t SkPDFGraphicState::getOutputSize(SkPDFCatalog* catalog, bool indirect) { populateDict(); return SkPDFDict::getOutputSize(catalog, indirect); } // static SkTDArray<SkPDFGraphicState::GSCanonicalEntry>& SkPDFGraphicState::canonicalPaints() { // This initialization is only thread safe with gcc. static SkTDArray<SkPDFGraphicState::GSCanonicalEntry> gCanonicalPaints; return gCanonicalPaints; } // static SkMutex& SkPDFGraphicState::canonicalPaintsMutex() { // This initialization is only thread safe with gcc. static SkMutex gCanonicalPaintsMutex; return gCanonicalPaintsMutex; } // static SkPDFGraphicState* SkPDFGraphicState::getGraphicStateForPaint( const SkPaint& paint) { SkAutoMutexAcquire lock(canonicalPaintsMutex()); int index = find(paint); if (index >= 0) { canonicalPaints()[index].fGraphicState->ref(); return canonicalPaints()[index].fGraphicState; } GSCanonicalEntry newEntry(new SkPDFGraphicState(paint)); canonicalPaints().push(newEntry); return newEntry.fGraphicState; } // static int SkPDFGraphicState::find(const SkPaint& paint) { GSCanonicalEntry search(&paint); return canonicalPaints().find(search); } SkPDFGraphicState::SkPDFGraphicState(const SkPaint& paint) : fPaint(paint), fPopulated(false) { } // populateDict and operator== have to stay in sync with each other. void SkPDFGraphicState::populateDict() { if (!fPopulated) { fPopulated = true; insert("Type", new SkPDFName("ExtGState"))->unref(); SkRefPtr<SkPDFScalar> alpha = new SkPDFScalar(fPaint.getAlpha() * SkScalarInvert(0xFF)); alpha->unref(); // SkRefPtr and new both took a reference. insert("CA", alpha.get()); insert("ca", alpha.get()); SK_COMPILE_ASSERT(SkPaint::kButt_Cap == 0, paint_cap_mismatch); SK_COMPILE_ASSERT(SkPaint::kRound_Cap == 1, paint_cap_mismatch); SK_COMPILE_ASSERT(SkPaint::kSquare_Cap == 2, paint_cap_mismatch); SK_COMPILE_ASSERT(SkPaint::kCapCount == 3, paint_cap_mismatch); SkASSERT(fPaint.getStrokeCap() >= 0 && fPaint.getStrokeCap() <= 2); insert("LC", new SkPDFInt(fPaint.getStrokeCap()))->unref(); SK_COMPILE_ASSERT(SkPaint::kMiter_Join == 0, paint_join_mismatch); SK_COMPILE_ASSERT(SkPaint::kRound_Join == 1, paint_join_mismatch); SK_COMPILE_ASSERT(SkPaint::kBevel_Join == 2, paint_join_mismatch); SK_COMPILE_ASSERT(SkPaint::kJoinCount == 3, paint_join_mismatch); SkASSERT(fPaint.getStrokeJoin() >= 0 && fPaint.getStrokeJoin() <= 2); insert("LJ", new SkPDFInt(fPaint.getStrokeJoin()))->unref(); insert("LW", new SkPDFScalar(fPaint.getStrokeWidth()))->unref(); insert("ML", new SkPDFScalar(fPaint.getStrokeMiter()))->unref(); insert("SA", new SkPDFBool(true))->unref(); // Auto stroke adjustment. SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode; // If asMode fails, default to kSrcOver_Mode. if (fPaint.getXfermode()) fPaint.getXfermode()->asMode(&xfermode); // If we don't support the mode, just use kSrcOver_Mode. if (xfermode < 0 || xfermode > SkXfermode::kLastMode || blendModeFromXfermode(xfermode) == NULL) { xfermode = SkXfermode::kSrcOver_Mode; NOT_IMPLEMENTED("unsupported xfermode", false); } insert("BM", new SkPDFName(blendModeFromXfermode(xfermode)))->unref(); } } // We're only interested in some fields of the SkPaint, so we have a custom // operator== function. bool SkPDFGraphicState::GSCanonicalEntry::operator==( const SkPDFGraphicState::GSCanonicalEntry& gs) const { const SkPaint* a = fPaint; const SkPaint* b = gs.fPaint; SkASSERT(a != NULL); SkASSERT(b != NULL); if (SkColorGetA(a->getColor()) != SkColorGetA(b->getColor()) || a->getStrokeCap() != b->getStrokeCap() || a->getStrokeJoin() != b->getStrokeJoin() || a->getStrokeWidth() != b->getStrokeWidth() || a->getStrokeMiter() != b->getStrokeMiter()) { return false; } SkXfermode* aXfermode = a->getXfermode(); SkXfermode::Mode aXfermodeName = SkXfermode::kSrcOver_Mode; bool aXfermodeKnown = true; if (aXfermode) aXfermodeKnown = aXfermode->asMode(&aXfermodeName); SkXfermode* bXfermode = b->getXfermode(); SkXfermode::Mode bXfermodeName = SkXfermode::kSrcOver_Mode; bool bXfermodeKnown = true; if (bXfermode) bXfermodeKnown = bXfermode->asMode(&bXfermodeName); if (aXfermodeKnown != bXfermodeKnown) return false; if (!aXfermodeKnown) return aXfermode == bXfermode; return aXfermodeName == bXfermodeName; } <commit_msg>[PDF] Fix bug in graphic state comparison.<commit_after>/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SkPDFGraphicState.h" #include "SkPDFUtils.h" #include "SkStream.h" #include "SkTypes.h" namespace { const char* blendModeFromXfermode(SkXfermode::Mode mode) { switch (mode) { case SkXfermode::kSrcOver_Mode: return "Normal"; case SkXfermode::kMultiply_Mode: return "Multiply"; case SkXfermode::kScreen_Mode: return "Screen"; case SkXfermode::kOverlay_Mode: return "Overlay"; case SkXfermode::kDarken_Mode: return "Darken"; case SkXfermode::kLighten_Mode: return "Lighten"; case SkXfermode::kColorDodge_Mode: return "ColorDodge"; case SkXfermode::kColorBurn_Mode: return "ColorBurn"; case SkXfermode::kHardLight_Mode: return "HardLight"; case SkXfermode::kSoftLight_Mode: return "SoftLight"; case SkXfermode::kDifference_Mode: return "Difference"; case SkXfermode::kExclusion_Mode: return "Exclusion"; // These are handled in SkPDFDevice::setUpContentEntry. case SkXfermode::kClear_Mode: case SkXfermode::kSrc_Mode: case SkXfermode::kDst_Mode: case SkXfermode::kDstOver_Mode: return "Normal"; // TODO(vandebo) Figure out if we can support more of these modes. case SkXfermode::kSrcIn_Mode: case SkXfermode::kDstIn_Mode: case SkXfermode::kSrcOut_Mode: case SkXfermode::kDstOut_Mode: case SkXfermode::kSrcATop_Mode: case SkXfermode::kDstATop_Mode: case SkXfermode::kXor_Mode: case SkXfermode::kPlus_Mode: return NULL; } return NULL; } } SkPDFGraphicState::~SkPDFGraphicState() { SkAutoMutexAcquire lock(canonicalPaintsMutex()); int index = find(fPaint); SkASSERT(index >= 0); canonicalPaints().removeShuffle(index); } void SkPDFGraphicState::emitObject(SkWStream* stream, SkPDFCatalog* catalog, bool indirect) { populateDict(); SkPDFDict::emitObject(stream, catalog, indirect); } // static size_t SkPDFGraphicState::getOutputSize(SkPDFCatalog* catalog, bool indirect) { populateDict(); return SkPDFDict::getOutputSize(catalog, indirect); } // static SkTDArray<SkPDFGraphicState::GSCanonicalEntry>& SkPDFGraphicState::canonicalPaints() { // This initialization is only thread safe with gcc. static SkTDArray<SkPDFGraphicState::GSCanonicalEntry> gCanonicalPaints; return gCanonicalPaints; } // static SkMutex& SkPDFGraphicState::canonicalPaintsMutex() { // This initialization is only thread safe with gcc. static SkMutex gCanonicalPaintsMutex; return gCanonicalPaintsMutex; } // static SkPDFGraphicState* SkPDFGraphicState::getGraphicStateForPaint( const SkPaint& paint) { SkAutoMutexAcquire lock(canonicalPaintsMutex()); int index = find(paint); if (index >= 0) { canonicalPaints()[index].fGraphicState->ref(); return canonicalPaints()[index].fGraphicState; } GSCanonicalEntry newEntry(new SkPDFGraphicState(paint)); canonicalPaints().push(newEntry); return newEntry.fGraphicState; } // static int SkPDFGraphicState::find(const SkPaint& paint) { GSCanonicalEntry search(&paint); return canonicalPaints().find(search); } SkPDFGraphicState::SkPDFGraphicState(const SkPaint& paint) : fPaint(paint), fPopulated(false) { } // populateDict and operator== have to stay in sync with each other. void SkPDFGraphicState::populateDict() { if (!fPopulated) { fPopulated = true; insert("Type", new SkPDFName("ExtGState"))->unref(); SkRefPtr<SkPDFScalar> alpha = new SkPDFScalar(fPaint.getAlpha() * SkScalarInvert(0xFF)); alpha->unref(); // SkRefPtr and new both took a reference. insert("CA", alpha.get()); insert("ca", alpha.get()); SK_COMPILE_ASSERT(SkPaint::kButt_Cap == 0, paint_cap_mismatch); SK_COMPILE_ASSERT(SkPaint::kRound_Cap == 1, paint_cap_mismatch); SK_COMPILE_ASSERT(SkPaint::kSquare_Cap == 2, paint_cap_mismatch); SK_COMPILE_ASSERT(SkPaint::kCapCount == 3, paint_cap_mismatch); SkASSERT(fPaint.getStrokeCap() >= 0 && fPaint.getStrokeCap() <= 2); insert("LC", new SkPDFInt(fPaint.getStrokeCap()))->unref(); SK_COMPILE_ASSERT(SkPaint::kMiter_Join == 0, paint_join_mismatch); SK_COMPILE_ASSERT(SkPaint::kRound_Join == 1, paint_join_mismatch); SK_COMPILE_ASSERT(SkPaint::kBevel_Join == 2, paint_join_mismatch); SK_COMPILE_ASSERT(SkPaint::kJoinCount == 3, paint_join_mismatch); SkASSERT(fPaint.getStrokeJoin() >= 0 && fPaint.getStrokeJoin() <= 2); insert("LJ", new SkPDFInt(fPaint.getStrokeJoin()))->unref(); insert("LW", new SkPDFScalar(fPaint.getStrokeWidth()))->unref(); insert("ML", new SkPDFScalar(fPaint.getStrokeMiter()))->unref(); insert("SA", new SkPDFBool(true))->unref(); // Auto stroke adjustment. SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode; // If asMode fails, default to kSrcOver_Mode. if (fPaint.getXfermode()) fPaint.getXfermode()->asMode(&xfermode); // If we don't support the mode, just use kSrcOver_Mode. if (xfermode < 0 || xfermode > SkXfermode::kLastMode || blendModeFromXfermode(xfermode) == NULL) { xfermode = SkXfermode::kSrcOver_Mode; NOT_IMPLEMENTED("unsupported xfermode", false); } insert("BM", new SkPDFName(blendModeFromXfermode(xfermode)))->unref(); } } // We're only interested in some fields of the SkPaint, so we have a custom // operator== function. bool SkPDFGraphicState::GSCanonicalEntry::operator==( const SkPDFGraphicState::GSCanonicalEntry& gs) const { const SkPaint* a = fPaint; const SkPaint* b = gs.fPaint; SkASSERT(a != NULL); SkASSERT(b != NULL); if (SkColorGetA(a->getColor()) != SkColorGetA(b->getColor()) || a->getStrokeCap() != b->getStrokeCap() || a->getStrokeJoin() != b->getStrokeJoin() || a->getStrokeWidth() != b->getStrokeWidth() || a->getStrokeMiter() != b->getStrokeMiter()) { return false; } SkXfermode::Mode aXfermodeName = SkXfermode::kSrcOver_Mode; SkXfermode* aXfermode = a->getXfermode(); if (aXfermode) { aXfermode->asMode(&aXfermodeName); } if (aXfermodeName < 0 || aXfermodeName > SkXfermode::kLastMode || blendModeFromXfermode(aXfermodeName) == NULL) { aXfermodeName = SkXfermode::kSrcOver_Mode; } const char* aXfermodeString = blendModeFromXfermode(aXfermodeName); SkASSERT(aXfermodeString != NULL); SkXfermode::Mode bXfermodeName = SkXfermode::kSrcOver_Mode; SkXfermode* bXfermode = b->getXfermode(); if (bXfermode) { bXfermode->asMode(&bXfermodeName); } if (bXfermodeName < 0 || bXfermodeName > SkXfermode::kLastMode || blendModeFromXfermode(bXfermodeName) == NULL) { bXfermodeName = SkXfermode::kSrcOver_Mode; } const char* bXfermodeString = blendModeFromXfermode(bXfermodeName); SkASSERT(bXfermodeString != NULL); return strcmp(aXfermodeString, bXfermodeString) == 0; } <|endoftext|>
<commit_before><commit_msg>capsule tunneling through terrain - fixes #881<commit_after><|endoftext|>
<commit_before>#include <plasp/sas/Description.h> #include <iostream> #include <boost/filesystem.hpp> #include <plasp/sas/ParserException.h> namespace plasp { namespace sas { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Description // //////////////////////////////////////////////////////////////////////////////////////////////////// Description::Description() : m_usesActionCosts{false} { } //////////////////////////////////////////////////////////////////////////////////////////////////// Description Description::fromFile(const boost::filesystem::path &path) { Description description; setlocale(LC_NUMERIC, "C"); if (!boost::filesystem::is_regular_file(path)) { std::cerr << "Error: File does not exist: " << path.string() << std::endl; return description; } std::ifstream fileStream(path.string(), std::ios::in); fileStream.exceptions(std::ifstream::failbit | std::ifstream::badbit); description.parseVersionSection(fileStream); description.parseMetricSection(fileStream); description.parseVariablesSection(fileStream); description.parseMutexSection(fileStream); description.parseInitialStateSection(fileStream); description.parseGoalSection(fileStream); description.parseOperatorSection(fileStream); description.parseAxiomSection(fileStream); return description; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::print(std::ostream &ostream) const { // Metric section ostream << "uses action costs: " << (m_usesActionCosts ? "yes" : "no") << std::endl; // Variable section ostream << "variables: " << m_variables.size() << std::endl; std::for_each(m_variables.cbegin(), m_variables.cend(), [&](const auto &variable) { ostream << "\t" << variable.name << ":" << std::endl; ostream << "\t\tvalues: " << variable.values.size() << std::endl; std::for_each(variable.values.cbegin(), variable.values.cend(), [&](const auto &value) { ostream << "\t\t\t" << value.name << std::endl; }); ostream << "\t\taxiom layer: " << variable.axiomLayer << std::endl; }); // Mutex section ostream << "mutex groups: " << m_mutexGroups.size() << std::endl; std::for_each(m_mutexGroups.cbegin(), m_mutexGroups.cend(), [&](const auto &mutexGroup) { ostream << "\tmutex group:" << std::endl; std::for_each(mutexGroup.facts.cbegin(), mutexGroup.facts.cend(), [&](const auto &fact) { ostream << "\t\t" << fact.variable.name << " = " << fact.value.name << std::endl; }); }); // Initial state section ostream << "initial state:" << std::endl; std::for_each(m_initialStateFacts.cbegin(), m_initialStateFacts.cend(), [&](const auto &initialStateFact) { ostream << "\t" << initialStateFact.variable.name << " = " << initialStateFact.value.name << std::endl; }); // Goal section ostream << "goal:" << std::endl; std::for_each(m_goalFacts.cbegin(), m_goalFacts.cend(), [&](const auto &goalFact) { ostream << "\t" << goalFact.variable.name << " = " << goalFact.value.name << std::endl; }); // Operator section ostream << "operators: " << m_operators.size() << std::endl; std::for_each(m_operators.cbegin(), m_operators.cend(), [&](const auto &operator_) { ostream << "\t" << operator_.name << ":" << std::endl; ostream << "\t\tpreconditions: " << operator_.preconditions.size() << std::endl; std::for_each(operator_.preconditions.cbegin(), operator_.preconditions.cend(), [&](const auto &precondition) { std::cout << "\t\t\t" << precondition.variable.name << " = " << precondition.value.name << std::endl; }); ostream << "\t\teffects: " << operator_.effects.size() << std::endl; std::for_each(operator_.effects.cbegin(), operator_.effects.cend(), [&](const auto &effect) { ostream << "\t\t\teffect:" << std::endl; ostream << "\t\t\t\tconditions: " << effect.conditions.size() << std::endl; std::for_each(effect.conditions.cbegin(), effect.conditions.cend(), [&](const auto &condition) { ostream << "\t\t\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl; }); ostream << "\t\t\t\tpostcondition:" << std::endl; ostream << "\t\t\t\t\t" << effect.postcondition.variable.name << " = " << effect.postcondition.value.name << std::endl; }); ostream << "\t\tcosts: " << operator_.costs << std::endl; }); // Axiom section ostream << "axiom rules: " << m_axiomRules.size() << std::endl; std::for_each(m_axiomRules.cbegin(), m_axiomRules.cend(), [&](const auto &axiomRule) { ostream << "\taxiom rule:" << std::endl; ostream << "\t\tconditions: " << axiomRule.conditions.size() << std::endl; std::for_each(axiomRule.conditions.cbegin(), axiomRule.conditions.cend(), [&](const auto &condition) { ostream << "\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl; }); ostream << "\t\tpostcondition:" << std::endl; ostream << "\t\t\t" << axiomRule.postcondition.variable.name << " = " << axiomRule.postcondition.value.name << std::endl; }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseSectionIdentifier(std::istream &istream, const std::string &expectedSectionIdentifier) const { const auto sectionIdentifier = parse<std::string>(istream); if (sectionIdentifier != expectedSectionIdentifier) throw ParserException("Invalid format, expected " + expectedSectionIdentifier + ", got " + sectionIdentifier); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T> T Description::parse(std::istream &istream) const { T value; try { istream >> value; } catch (const std::exception &e) { throw ParserException(std::string("Could not parse value of type ") + typeid(T).name() + " (" + e.what() + ")"); } return value; } //////////////////////////////////////////////////////////////////////////////////////////////////// const Variable &Description::parseVariable(std::istream &istream) const { const auto variableID = parse<size_t>(istream); if (variableID >= m_variables.size()) throw ParserException("Variable index out of range (index " + std::to_string(variableID) + ")"); return m_variables[variableID]; } //////////////////////////////////////////////////////////////////////////////////////////////////// const Value &Description::parseValue(std::istream &istream, const Variable &variable) const { const auto valueID = parse<int>(istream); if (valueID == -1) return Value::Any; if (valueID < 0 || static_cast<size_t>(valueID) >= variable.values.size()) throw ParserException("Value index out of range (variable " + variable.name + ", index " + std::to_string(valueID) + ")"); return variable.values[valueID]; } //////////////////////////////////////////////////////////////////////////////////////////////////// AssignedVariable Description::parseAssignedVariable(std::istream &istream) const { const auto &variable = parseVariable(istream); const auto &value = parseValue(istream, variable); return {variable, value}; } //////////////////////////////////////////////////////////////////////////////////////////////////// VariableTransition Description::parseVariableTransition(std::istream &istream) const { const auto &variable = parseVariable(istream); const auto &valueBefore = parseValue(istream, variable); const auto &valueAfter = parseValue(istream, variable); return {variable, valueBefore, valueAfter}; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseVersionSection(std::istream &istream) const { // Version section parseSectionIdentifier(istream, "begin_version"); const auto formatVersion = parse<size_t>(istream); if (formatVersion != 3) throw ParserException("Unsupported SAS format version (" + std::to_string(formatVersion) + ")"); std::cout << "SAS format version: " << formatVersion << std::endl; parseSectionIdentifier(istream, "end_version"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseMetricSection(std::istream &istream) { parseSectionIdentifier(istream, "begin_metric"); m_usesActionCosts = parse<bool>(istream); parseSectionIdentifier(istream, "end_metric"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseVariablesSection(std::istream &istream) { const auto numberOfVariables = parse<size_t>(istream); m_variables.resize(numberOfVariables); for (size_t i = 0; i < numberOfVariables; i++) { auto &variable = m_variables[i]; parseSectionIdentifier(istream, "begin_variable"); variable.name = parse<std::string>(istream); variable.axiomLayer = parse<int>(istream); const auto numberOfValues = parse<size_t>(istream); variable.values.resize(numberOfValues); try { istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); for (size_t j = 0; j < numberOfValues; j++) { auto &value = variable.values[j]; std::getline(istream, value.name); } } catch (const std::exception &e) { throw ParserException("Could not parse variable " + variable.name + " (" + e.what() + ")"); } parseSectionIdentifier(istream, "end_variable"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseMutexSection(std::istream &istream) { const auto numberOfMutexGroups = parse<size_t>(istream); m_mutexGroups.resize(numberOfMutexGroups); for (size_t i = 0; i < numberOfMutexGroups; i++) { parseSectionIdentifier(istream, "begin_mutex_group"); auto &mutexGroup = m_mutexGroups[i]; const auto numberOfFacts = parse<size_t>(istream); mutexGroup.facts.reserve(numberOfFacts); for (size_t j = 0; j < numberOfFacts; j++) { const auto fact = parseAssignedVariable(istream); mutexGroup.facts.push_back(std::move(fact)); } parseSectionIdentifier(istream, "end_mutex_group"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseInitialStateSection(std::istream &istream) { parseSectionIdentifier(istream, "begin_state"); m_initialStateFacts.reserve(m_variables.size()); for (size_t i = 0; i < m_variables.size(); i++) { const auto &variable = m_variables[i]; const auto &value = parseValue(istream, variable); m_initialStateFacts.push_back({variable, value}); } parseSectionIdentifier(istream, "end_state"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseGoalSection(std::istream &istream) { parseSectionIdentifier(istream, "begin_goal"); const auto numberOfGoalFacts = parse<size_t>(istream); m_goalFacts.reserve(numberOfGoalFacts); for (size_t i = 0; i < numberOfGoalFacts; i++) { const auto goalFact = parseAssignedVariable(istream); m_goalFacts.push_back(std::move(goalFact)); } parseSectionIdentifier(istream, "end_goal"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseOperatorSection(std::istream &istream) { const auto numberOfOperators = parse<size_t>(istream); m_operators.resize(numberOfOperators); for (size_t i = 0; i < numberOfOperators; i++) { parseSectionIdentifier(istream, "begin_operator"); istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); auto &operator_ = m_operators[i]; std::getline(istream, operator_.name); const auto numberOfPrevailConditions = parse<size_t>(istream); operator_.preconditions.reserve(numberOfPrevailConditions); for (size_t j = 0; j < numberOfPrevailConditions; j++) { const auto precondition = parseAssignedVariable(istream); operator_.preconditions.push_back(std::move(precondition)); } const auto numberOfEffects = parse<size_t>(istream); operator_.effects.reserve(numberOfEffects); for (size_t j = 0; j < numberOfEffects; j++) { Effect::Conditions conditions; const auto numberOfEffectConditions = parse<size_t>(istream); conditions.reserve(numberOfEffectConditions); for (size_t k = 0; k < numberOfEffectConditions; k++) { const auto condition = parseAssignedVariable(istream); conditions.push_back(std::move(condition)); } const auto variableTransition = parseVariableTransition(istream); if (&variableTransition.valueBefore != &Value::Any) operator_.preconditions.push_back({variableTransition.variable, variableTransition.valueBefore}); const Effect::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter}; const Effect effect = {std::move(conditions), std::move(postcondition)}; operator_.effects.push_back(std::move(effect)); } operator_.costs = parse<size_t>(istream); parseSectionIdentifier(istream, "end_operator"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseAxiomSection(std::istream &istream) { const auto numberOfAxiomRules = parse<size_t>(istream); m_axiomRules.reserve(numberOfAxiomRules); std::cout << "Axiom rules: " << numberOfAxiomRules << std::endl; for (size_t i = 0; i < numberOfAxiomRules; i++) { parseSectionIdentifier(istream, "begin_rule"); const auto numberOfConditions = parse<size_t>(istream); AxiomRule::Conditions conditions; conditions.reserve(numberOfConditions); for (size_t j = 0; j < numberOfConditions; j++) { const auto condition = parseAssignedVariable(istream); conditions.push_back(std::move(condition)); } const auto variableTransition = parseVariableTransition(istream); if (&variableTransition.valueBefore != &Value::Any) conditions.push_back({variableTransition.variable, variableTransition.valueBefore}); const AxiomRule::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter}; const AxiomRule axiomRule = {std::move(conditions), std::move(postcondition)}; m_axiomRules.push_back(std::move(axiomRule)); parseSectionIdentifier(istream, "end_rule"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <commit_msg>Removed unintended debug output.<commit_after>#include <plasp/sas/Description.h> #include <iostream> #include <boost/filesystem.hpp> #include <plasp/sas/ParserException.h> namespace plasp { namespace sas { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Description // //////////////////////////////////////////////////////////////////////////////////////////////////// Description::Description() : m_usesActionCosts{false} { } //////////////////////////////////////////////////////////////////////////////////////////////////// Description Description::fromFile(const boost::filesystem::path &path) { Description description; setlocale(LC_NUMERIC, "C"); if (!boost::filesystem::is_regular_file(path)) { std::cerr << "Error: File does not exist: " << path.string() << std::endl; return description; } std::ifstream fileStream(path.string(), std::ios::in); fileStream.exceptions(std::ifstream::failbit | std::ifstream::badbit); description.parseVersionSection(fileStream); description.parseMetricSection(fileStream); description.parseVariablesSection(fileStream); description.parseMutexSection(fileStream); description.parseInitialStateSection(fileStream); description.parseGoalSection(fileStream); description.parseOperatorSection(fileStream); description.parseAxiomSection(fileStream); return description; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::print(std::ostream &ostream) const { // Metric section ostream << "uses action costs: " << (m_usesActionCosts ? "yes" : "no") << std::endl; // Variable section ostream << "variables: " << m_variables.size() << std::endl; std::for_each(m_variables.cbegin(), m_variables.cend(), [&](const auto &variable) { ostream << "\t" << variable.name << ":" << std::endl; ostream << "\t\tvalues: " << variable.values.size() << std::endl; std::for_each(variable.values.cbegin(), variable.values.cend(), [&](const auto &value) { ostream << "\t\t\t" << value.name << std::endl; }); ostream << "\t\taxiom layer: " << variable.axiomLayer << std::endl; }); // Mutex section ostream << "mutex groups: " << m_mutexGroups.size() << std::endl; std::for_each(m_mutexGroups.cbegin(), m_mutexGroups.cend(), [&](const auto &mutexGroup) { ostream << "\tmutex group:" << std::endl; std::for_each(mutexGroup.facts.cbegin(), mutexGroup.facts.cend(), [&](const auto &fact) { ostream << "\t\t" << fact.variable.name << " = " << fact.value.name << std::endl; }); }); // Initial state section ostream << "initial state:" << std::endl; std::for_each(m_initialStateFacts.cbegin(), m_initialStateFacts.cend(), [&](const auto &initialStateFact) { ostream << "\t" << initialStateFact.variable.name << " = " << initialStateFact.value.name << std::endl; }); // Goal section ostream << "goal:" << std::endl; std::for_each(m_goalFacts.cbegin(), m_goalFacts.cend(), [&](const auto &goalFact) { ostream << "\t" << goalFact.variable.name << " = " << goalFact.value.name << std::endl; }); // Operator section ostream << "operators: " << m_operators.size() << std::endl; std::for_each(m_operators.cbegin(), m_operators.cend(), [&](const auto &operator_) { ostream << "\t" << operator_.name << ":" << std::endl; ostream << "\t\tpreconditions: " << operator_.preconditions.size() << std::endl; std::for_each(operator_.preconditions.cbegin(), operator_.preconditions.cend(), [&](const auto &precondition) { std::cout << "\t\t\t" << precondition.variable.name << " = " << precondition.value.name << std::endl; }); ostream << "\t\teffects: " << operator_.effects.size() << std::endl; std::for_each(operator_.effects.cbegin(), operator_.effects.cend(), [&](const auto &effect) { ostream << "\t\t\teffect:" << std::endl; ostream << "\t\t\t\tconditions: " << effect.conditions.size() << std::endl; std::for_each(effect.conditions.cbegin(), effect.conditions.cend(), [&](const auto &condition) { ostream << "\t\t\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl; }); ostream << "\t\t\t\tpostcondition:" << std::endl; ostream << "\t\t\t\t\t" << effect.postcondition.variable.name << " = " << effect.postcondition.value.name << std::endl; }); ostream << "\t\tcosts: " << operator_.costs << std::endl; }); // Axiom section ostream << "axiom rules: " << m_axiomRules.size() << std::endl; std::for_each(m_axiomRules.cbegin(), m_axiomRules.cend(), [&](const auto &axiomRule) { ostream << "\taxiom rule:" << std::endl; ostream << "\t\tconditions: " << axiomRule.conditions.size() << std::endl; std::for_each(axiomRule.conditions.cbegin(), axiomRule.conditions.cend(), [&](const auto &condition) { ostream << "\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl; }); ostream << "\t\tpostcondition:" << std::endl; ostream << "\t\t\t" << axiomRule.postcondition.variable.name << " = " << axiomRule.postcondition.value.name << std::endl; }); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseSectionIdentifier(std::istream &istream, const std::string &expectedSectionIdentifier) const { const auto sectionIdentifier = parse<std::string>(istream); if (sectionIdentifier != expectedSectionIdentifier) throw ParserException("Invalid format, expected " + expectedSectionIdentifier + ", got " + sectionIdentifier); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T> T Description::parse(std::istream &istream) const { T value; try { istream >> value; } catch (const std::exception &e) { throw ParserException(std::string("Could not parse value of type ") + typeid(T).name() + " (" + e.what() + ")"); } return value; } //////////////////////////////////////////////////////////////////////////////////////////////////// const Variable &Description::parseVariable(std::istream &istream) const { const auto variableID = parse<size_t>(istream); if (variableID >= m_variables.size()) throw ParserException("Variable index out of range (index " + std::to_string(variableID) + ")"); return m_variables[variableID]; } //////////////////////////////////////////////////////////////////////////////////////////////////// const Value &Description::parseValue(std::istream &istream, const Variable &variable) const { const auto valueID = parse<int>(istream); if (valueID == -1) return Value::Any; if (valueID < 0 || static_cast<size_t>(valueID) >= variable.values.size()) throw ParserException("Value index out of range (variable " + variable.name + ", index " + std::to_string(valueID) + ")"); return variable.values[valueID]; } //////////////////////////////////////////////////////////////////////////////////////////////////// AssignedVariable Description::parseAssignedVariable(std::istream &istream) const { const auto &variable = parseVariable(istream); const auto &value = parseValue(istream, variable); return {variable, value}; } //////////////////////////////////////////////////////////////////////////////////////////////////// VariableTransition Description::parseVariableTransition(std::istream &istream) const { const auto &variable = parseVariable(istream); const auto &valueBefore = parseValue(istream, variable); const auto &valueAfter = parseValue(istream, variable); return {variable, valueBefore, valueAfter}; } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseVersionSection(std::istream &istream) const { // Version section parseSectionIdentifier(istream, "begin_version"); const auto formatVersion = parse<size_t>(istream); if (formatVersion != 3) throw ParserException("Unsupported SAS format version (" + std::to_string(formatVersion) + ")"); parseSectionIdentifier(istream, "end_version"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseMetricSection(std::istream &istream) { parseSectionIdentifier(istream, "begin_metric"); m_usesActionCosts = parse<bool>(istream); parseSectionIdentifier(istream, "end_metric"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseVariablesSection(std::istream &istream) { const auto numberOfVariables = parse<size_t>(istream); m_variables.resize(numberOfVariables); for (size_t i = 0; i < numberOfVariables; i++) { auto &variable = m_variables[i]; parseSectionIdentifier(istream, "begin_variable"); variable.name = parse<std::string>(istream); variable.axiomLayer = parse<int>(istream); const auto numberOfValues = parse<size_t>(istream); variable.values.resize(numberOfValues); try { istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); for (size_t j = 0; j < numberOfValues; j++) { auto &value = variable.values[j]; std::getline(istream, value.name); } } catch (const std::exception &e) { throw ParserException("Could not parse variable " + variable.name + " (" + e.what() + ")"); } parseSectionIdentifier(istream, "end_variable"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseMutexSection(std::istream &istream) { const auto numberOfMutexGroups = parse<size_t>(istream); m_mutexGroups.resize(numberOfMutexGroups); for (size_t i = 0; i < numberOfMutexGroups; i++) { parseSectionIdentifier(istream, "begin_mutex_group"); auto &mutexGroup = m_mutexGroups[i]; const auto numberOfFacts = parse<size_t>(istream); mutexGroup.facts.reserve(numberOfFacts); for (size_t j = 0; j < numberOfFacts; j++) { const auto fact = parseAssignedVariable(istream); mutexGroup.facts.push_back(std::move(fact)); } parseSectionIdentifier(istream, "end_mutex_group"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseInitialStateSection(std::istream &istream) { parseSectionIdentifier(istream, "begin_state"); m_initialStateFacts.reserve(m_variables.size()); for (size_t i = 0; i < m_variables.size(); i++) { const auto &variable = m_variables[i]; const auto &value = parseValue(istream, variable); m_initialStateFacts.push_back({variable, value}); } parseSectionIdentifier(istream, "end_state"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseGoalSection(std::istream &istream) { parseSectionIdentifier(istream, "begin_goal"); const auto numberOfGoalFacts = parse<size_t>(istream); m_goalFacts.reserve(numberOfGoalFacts); for (size_t i = 0; i < numberOfGoalFacts; i++) { const auto goalFact = parseAssignedVariable(istream); m_goalFacts.push_back(std::move(goalFact)); } parseSectionIdentifier(istream, "end_goal"); } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseOperatorSection(std::istream &istream) { const auto numberOfOperators = parse<size_t>(istream); m_operators.resize(numberOfOperators); for (size_t i = 0; i < numberOfOperators; i++) { parseSectionIdentifier(istream, "begin_operator"); istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); auto &operator_ = m_operators[i]; std::getline(istream, operator_.name); const auto numberOfPrevailConditions = parse<size_t>(istream); operator_.preconditions.reserve(numberOfPrevailConditions); for (size_t j = 0; j < numberOfPrevailConditions; j++) { const auto precondition = parseAssignedVariable(istream); operator_.preconditions.push_back(std::move(precondition)); } const auto numberOfEffects = parse<size_t>(istream); operator_.effects.reserve(numberOfEffects); for (size_t j = 0; j < numberOfEffects; j++) { Effect::Conditions conditions; const auto numberOfEffectConditions = parse<size_t>(istream); conditions.reserve(numberOfEffectConditions); for (size_t k = 0; k < numberOfEffectConditions; k++) { const auto condition = parseAssignedVariable(istream); conditions.push_back(std::move(condition)); } const auto variableTransition = parseVariableTransition(istream); if (&variableTransition.valueBefore != &Value::Any) operator_.preconditions.push_back({variableTransition.variable, variableTransition.valueBefore}); const Effect::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter}; const Effect effect = {std::move(conditions), std::move(postcondition)}; operator_.effects.push_back(std::move(effect)); } operator_.costs = parse<size_t>(istream); parseSectionIdentifier(istream, "end_operator"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void Description::parseAxiomSection(std::istream &istream) { const auto numberOfAxiomRules = parse<size_t>(istream); m_axiomRules.reserve(numberOfAxiomRules); for (size_t i = 0; i < numberOfAxiomRules; i++) { parseSectionIdentifier(istream, "begin_rule"); const auto numberOfConditions = parse<size_t>(istream); AxiomRule::Conditions conditions; conditions.reserve(numberOfConditions); for (size_t j = 0; j < numberOfConditions; j++) { const auto condition = parseAssignedVariable(istream); conditions.push_back(std::move(condition)); } const auto variableTransition = parseVariableTransition(istream); if (&variableTransition.valueBefore != &Value::Any) conditions.push_back({variableTransition.variable, variableTransition.valueBefore}); const AxiomRule::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter}; const AxiomRule axiomRule = {std::move(conditions), std::move(postcondition)}; m_axiomRules.push_back(std::move(axiomRule)); parseSectionIdentifier(istream, "end_rule"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// } } <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_EVENTLOOP_HPP_ #define _QI_EVENTLOOP_HPP_ #ifdef _MSC_VER # pragma warning( disable: 4503 ) // decorated name length #endif #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <qi/types.hpp> #include <qi/api.hpp> #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4251 ) #endif namespace boost { namespace asio { class io_service; }} namespace qi { template<typename T> class Future; class EventLoopPrivate; class QI_API EventLoop { public: /** Create a new eventLoop. * You must then call either start(), run() or startThreadPool() to start event processing. */ EventLoop(); ~EventLoop(); /// Return true if current thread is the event loop thread. bool isInEventLoopThread(); /// Start in threaded mode void start(int nthreads = 0); /// Start in thread-pool mode: each asyncCall() will be run in parallel void startThreadPool(int minWorkers=-1, int maxWorkers=-1, int minIdleWorkers=-1, int maxIdleWorkers=-1); /// Wait for run thread to terminate void join(); /// Ask main loop to terminate void stop(); /// Run main loop in current thread. void run(); // Internal function void *nativeHandle(); /// @{ /** Call given function once after given delay in microseconds. * @return a canceleable future */ template<typename R> Future<R> async(boost::function<R()> callback, uint64_t usDelay=0); Future<void> async(boost::function<void ()> callback, uint64_t usDelay=0); /// @} /// Similar to async() but without cancelation or notification void post(const boost::function<void ()>& callback, uint64_t usDelay=0); /** Monitor event loop to detect deadlocks. @param helper an other event loop used for monitoring @param maxUsDelay maximum expected delay between an async() and its execution @return a canceleable future. Invoke cancel() to terminate monitoring. In case an async() call does not execute in time, the future's error will be set. */ Future<void> monitorEventLoop(EventLoop* helper, uint64_t maxUsDelay); EventLoopPrivate *_p; }; /// Return the global eventloop, created on demand on first call. QI_API EventLoop* getEventLoop(); /// Return the io_service used by the global event loop boost::asio::io_service& getIoService(); /// Return a default event loop for network operations. QI_API QI_API_DEPRECATED EventLoop* getDefaultNetworkEventLoop(); /// Return a default context for other uses. QI_API QI_API_DEPRECATED EventLoop* getDefaultObjectEventLoop(); /// Return a default thread pool context QI_API QI_API_DEPRECATED EventLoop* getDefaultThreadPoolEventLoop(); } #ifdef _MSC_VER # pragma warning( pop ) #endif #include <qi/details/eventloop.hxx> #endif // _QI_EVENTLOOP_HPP_ <commit_msg>Export getIoService<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_EVENTLOOP_HPP_ #define _QI_EVENTLOOP_HPP_ #ifdef _MSC_VER # pragma warning( disable: 4503 ) // decorated name length #endif #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <qi/types.hpp> #include <qi/api.hpp> #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4251 ) #endif namespace boost { namespace asio { class io_service; }} namespace qi { template<typename T> class Future; class EventLoopPrivate; class QI_API EventLoop { public: /** Create a new eventLoop. * You must then call either start(), run() or startThreadPool() to start event processing. */ EventLoop(); ~EventLoop(); /// Return true if current thread is the event loop thread. bool isInEventLoopThread(); /// Start in threaded mode void start(int nthreads = 0); /// Start in thread-pool mode: each asyncCall() will be run in parallel void startThreadPool(int minWorkers=-1, int maxWorkers=-1, int minIdleWorkers=-1, int maxIdleWorkers=-1); /// Wait for run thread to terminate void join(); /// Ask main loop to terminate void stop(); /// Run main loop in current thread. void run(); // Internal function void *nativeHandle(); /// @{ /** Call given function once after given delay in microseconds. * @return a canceleable future */ template<typename R> Future<R> async(boost::function<R()> callback, uint64_t usDelay=0); Future<void> async(boost::function<void ()> callback, uint64_t usDelay=0); /// @} /// Similar to async() but without cancelation or notification void post(const boost::function<void ()>& callback, uint64_t usDelay=0); /** Monitor event loop to detect deadlocks. @param helper an other event loop used for monitoring @param maxUsDelay maximum expected delay between an async() and its execution @return a canceleable future. Invoke cancel() to terminate monitoring. In case an async() call does not execute in time, the future's error will be set. */ Future<void> monitorEventLoop(EventLoop* helper, uint64_t maxUsDelay); EventLoopPrivate *_p; }; /// Return the global eventloop, created on demand on first call. QI_API EventLoop* getEventLoop(); /// Return the io_service used by the global event loop QI_API boost::asio::io_service& getIoService(); /// Compat /// Return a default event loop for network operations. QI_API QI_API_DEPRECATED EventLoop* getDefaultNetworkEventLoop(); /// Return a default context for other uses. QI_API QI_API_DEPRECATED EventLoop* getDefaultObjectEventLoop(); /// Return a default thread pool context QI_API QI_API_DEPRECATED EventLoop* getDefaultThreadPoolEventLoop(); } #ifdef _MSC_VER # pragma warning( pop ) #endif #include <qi/details/eventloop.hxx> #endif // _QI_EVENTLOOP_HPP_ <|endoftext|>
<commit_before>/** * @file * * @brief Write key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "write.hpp" #include "log.hpp" #include "yaml-cpp/yaml.h" #include <kdbassert.h> #include <kdbease.h> #include <kdblogger.h> #include <kdbplugin.h> #include <fstream> using namespace std; using namespace kdb; namespace { using KeySetPair = pair<KeySet, KeySet>; /** * @brief This function returns all array parents for a given key set. * * @param keys This parameter contains the key set this function searches for array parents. * * @return A key sets that contains all array parents stored in `keys` */ KeySet splitArrayParents (KeySet const & keys) { KeySet arrayParents; for (auto const & key : keys) { if (key.hasMeta ("array")) arrayParents.append (key); } #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Array parents:"); logKeySet (arrayParents); #endif return arrayParents; } /** * @brief This function splits `keys` into two key sets, one for array parents and elements, and the other one for all other keys. * * @param arrayParents This key set contains a (copy) of all array parents of `keys`. * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all array parents and elements, * and the second key set contains all other keys */ KeySetPair splitArrayOther (KeySet const & arrayParents, KeySet const & keys) { KeySet others = keys.dup (); KeySet arrays; for (auto const & parent : arrayParents) { arrays.append (others.cut (parent)); } return make_pair (arrays, others); } /** * @brief This function determines all keys “missing” from the given keyset. * * The term “missing” refers to keys that are not part of the hierarchy. For example in a key set with the parent key * * - `user/parent` * * that contains the keys * * - `user/parent/level1/level2`, and * - `user/parent/level1/level2/level3/level4` * * , the keys * * - `user/parent/level1`, and * - `user/parent/level1/level2/level3` * * are missing. * * @param keys This parameter contains the key set for which this function determines missing keys. * @param parent This value stores the parent key of `keys`. * * @return A key set that contains all keys missing from `keys` */ KeySet missingKeys (KeySet const & keys, Key const & parent) { KeySet missing; keys.rewind (); Key previous{ parent.getName (), KEY_BINARY, KEY_END }; for (; keys.next (); previous = keys.current ()) { if (keys.current ().isDirectBelow (previous) || !keys.current ().isBelow (previous)) continue; Key current{ keys.current ().getName (), KEY_BINARY, KEY_END }; while (!current.isDirectBelow (previous)) { ckdb::keySetBaseName (*current, NULL); missing.append (current); current = current.dup (); } } return missing; } /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre The parameter `key` must be a child of `parent`. * * @param key This is the key for which this function returns a relative iterator. * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (Key const & key, Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } /** * @brief This function checks if a key name specifies an array key. * * If the key name contains a valid array index that is smaller than `unsigned long long`, then the function will also return this index. * * @param nameIterator This iterator specifies the name of the key. * * @retval (true, arrayIndex) if `name` specifies an array key, where `arrayIndex` specifies the index stored in the array key. * @retval (false, 0) otherwise */ std::pair<bool, unsigned long long> isArrayIndex (NameIterator const & nameIterator) { string const name = *nameIterator; auto const offsetIndex = ckdb::elektraArrayValidateBaseNameString (name.c_str ()); auto const isArrayElement = offsetIndex >= 1; return { isArrayElement, isArrayElement ? stoull (name.substr (static_cast<size_t> (offsetIndex))) : 0 }; } /** * @brief This function creates a YAML node representing a key value. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 plugin before you use YAML CPP. * * @returns A new YAML node containing the data specified in `key` */ YAML::Node createMetaDataNode (Key const & key) { if (key.hasMeta ("array")) { return YAML::Node (YAML::NodeType::Sequence); } if (key.getBinarySize () == 0) { return YAML::Node (YAML::NodeType::Null); } if (key.isBinary ()) { return YAML::Node ("Unsupported binary value!"); } auto value = key.get<string> (); if (value == "0" || value == "1") { return YAML::Node (key.get<bool> ()); } return YAML::Node (value); } /** * @brief This function creates a YAML Node containing a key value and optionally metadata. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP. * * @returns A new YAML node containing the data and metadata specified in `key` */ YAML::Node createLeafNode (Key & key) { YAML::Node metaNode{ YAML::Node (YAML::NodeType::Map) }; YAML::Node dataNode = createMetaDataNode (key); key.rewindMeta (); while (Key meta = key.nextMeta ()) { if (meta.getName () == "array" || meta.getName () == "binary") continue; if (meta.getName () == "type" && meta.getString () == "binary") { dataNode.SetTag ("tag:yaml.org,2002:binary"); continue; } metaNode[meta.getName ()] = meta.getString (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", meta.getName ().c_str (), meta.getString ().c_str ()); } if (metaNode.size () <= 0) { ELEKTRA_LOG_DEBUG ("Return leaf node with value “%s”", dataNode.IsNull () ? "~" : dataNode.IsSequence () ? "[]" : dataNode.as<string> ().c_str ()); return dataNode; } YAML::Node node{ YAML::Node (YAML::NodeType::Sequence) }; node.SetTag ("!elektra/meta"); node.push_back (dataNode); node.push_back (metaNode); #ifdef HAVE_LOGGER ostringstream data; data << node; ELEKTRA_LOG_DEBUG ("Return meta leaf node with value “%s”", data.str ().c_str ()); #endif return node; } /** * @brief This function adds `null` elements to the given YAML collection. * * @param sequence This node stores the collection to which this function adds `numberOfElements` empty elements. * @param numberOfElements This parameter specifies the number of empty element this function adds to `sequence`. */ void addEmptyArrayElements (YAML::Node & sequence, unsigned long long const numberOfElements) { ELEKTRA_LOG_DEBUG ("Add %lld empty array elements", numberOfElements); for (auto missingFields = numberOfElements; missingFields > 0; missingFields--) { sequence.push_back ({}); } } /** * @brief This function adds a key that is not part of any array to a YAML node. * * @param data This node stores the data specified via `keyIterator`. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. */ void addKeyNoArray (YAML::Node & data, NameIterator & keyIterator, Key & key) { if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined); #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Add key part “%s”", (*keyIterator).c_str ()); #endif if (keyIterator == key.end ()) { ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ()); data = createLeafNode (key); return; } if (keyIterator == --key.end ()) { data[*keyIterator] = createLeafNode (key); return; } YAML::Node node; node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node (); data[*keyIterator] = node; addKeyNoArray (node, ++keyIterator, key); } /** * @brief This function adds a key that is either, element of an array, or an array parent to a YAML node. * * @param data This node stores the data specified via `keyIterator`. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. */ void addKeyArray (YAML::Node & data, NameIterator & keyIterator, Key & key) { auto const isArrayAndIndex = isArrayIndex (keyIterator); auto const isArrayElement = isArrayAndIndex.first; auto const arrayIndex = isArrayAndIndex.second; if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined); #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Add key part “%s”", (*keyIterator).c_str ()); #endif if (keyIterator == key.end ()) { ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ()); data = createLeafNode (key); return; } if (keyIterator == --key.end ()) { if (isArrayElement) { addEmptyArrayElements (data, arrayIndex - data.size ()); data.push_back (createLeafNode (key)); } else { data[*keyIterator] = createLeafNode (key); } return; } YAML::Node node; if (isArrayElement) { node = (data[arrayIndex] && !data[arrayIndex].IsScalar ()) ? data[arrayIndex] : YAML::Node (); data[arrayIndex] = node; } else { node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node (); data[*keyIterator] = node; } addKeyArray (node, ++keyIterator, key); } /** * @brief This function adds a key set to a YAML node. * * @param data This node stores the data specified via `mappings`. * @param mappings This keyset specifies all keys and values this function adds to `data`. * @param parent This key is the root of all keys stored in `mappings`. * @param isArray This value specifies if the keys inside `keys` are all part of an array (either element or parent), or if none of them is * part of an array. */ void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent, bool const isArray = false) { for (auto key : mappings) { ELEKTRA_LOG_DEBUG ("Convert key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); NameIterator keyIterator = relativeKeyIterator (key, parent); if (isArray) { addKeyArray (data, keyIterator, key); } else { addKeyNoArray (data, keyIterator, key); } #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Converted Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (output.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif } } } // end namespace /** * @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`. * * @param mappings This key set stores the mappings that should be saved as YAML data. * @param parent This key specifies the path to the YAML data file that should be written. */ void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent) { KeySet keys = mappings; auto missing = missingKeys (keys, parent); keys.append (missing); KeySet arrayParents; KeySet arrays; KeySet nonArrays; arrayParents = splitArrayParents (keys); tie (arrays, nonArrays) = splitArrayOther (arrayParents, keys); auto data = YAML::Node (); addKeys (data, nonArrays, parent); addKeys (data, arrays, parent, true); #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Write Data:"); ELEKTRA_LOG_DEBUG ("——————————"); ostringstream outputString; outputString << data; istringstream stream (outputString.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif ofstream output (parent.getString ()); output << data << endl; } <commit_msg>YAML CPP: Fix minor spelling mistake in comment<commit_after>/** * @file * * @brief Write key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "write.hpp" #include "log.hpp" #include "yaml-cpp/yaml.h" #include <kdbassert.h> #include <kdbease.h> #include <kdblogger.h> #include <kdbplugin.h> #include <fstream> using namespace std; using namespace kdb; namespace { using KeySetPair = pair<KeySet, KeySet>; /** * @brief This function returns all array parents for a given key set. * * @param keys This parameter contains the key set this function searches for array parents. * * @return A key set that contains all array parents stored in `keys` */ KeySet splitArrayParents (KeySet const & keys) { KeySet arrayParents; for (auto const & key : keys) { if (key.hasMeta ("array")) arrayParents.append (key); } #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Array parents:"); logKeySet (arrayParents); #endif return arrayParents; } /** * @brief This function splits `keys` into two key sets, one for array parents and elements, and the other one for all other keys. * * @param arrayParents This key set contains a (copy) of all array parents of `keys`. * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all array parents and elements, * and the second key set contains all other keys */ KeySetPair splitArrayOther (KeySet const & arrayParents, KeySet const & keys) { KeySet others = keys.dup (); KeySet arrays; for (auto const & parent : arrayParents) { arrays.append (others.cut (parent)); } return make_pair (arrays, others); } /** * @brief This function determines all keys “missing” from the given keyset. * * The term “missing” refers to keys that are not part of the hierarchy. For example in a key set with the parent key * * - `user/parent` * * that contains the keys * * - `user/parent/level1/level2`, and * - `user/parent/level1/level2/level3/level4` * * , the keys * * - `user/parent/level1`, and * - `user/parent/level1/level2/level3` * * are missing. * * @param keys This parameter contains the key set for which this function determines missing keys. * @param parent This value stores the parent key of `keys`. * * @return A key set that contains all keys missing from `keys` */ KeySet missingKeys (KeySet const & keys, Key const & parent) { KeySet missing; keys.rewind (); Key previous{ parent.getName (), KEY_BINARY, KEY_END }; for (; keys.next (); previous = keys.current ()) { if (keys.current ().isDirectBelow (previous) || !keys.current ().isBelow (previous)) continue; Key current{ keys.current ().getName (), KEY_BINARY, KEY_END }; while (!current.isDirectBelow (previous)) { ckdb::keySetBaseName (*current, NULL); missing.append (current); current = current.dup (); } } return missing; } /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre The parameter `key` must be a child of `parent`. * * @param key This is the key for which this function returns a relative iterator. * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (Key const & key, Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } /** * @brief This function checks if a key name specifies an array key. * * If the key name contains a valid array index that is smaller than `unsigned long long`, then the function will also return this index. * * @param nameIterator This iterator specifies the name of the key. * * @retval (true, arrayIndex) if `name` specifies an array key, where `arrayIndex` specifies the index stored in the array key. * @retval (false, 0) otherwise */ std::pair<bool, unsigned long long> isArrayIndex (NameIterator const & nameIterator) { string const name = *nameIterator; auto const offsetIndex = ckdb::elektraArrayValidateBaseNameString (name.c_str ()); auto const isArrayElement = offsetIndex >= 1; return { isArrayElement, isArrayElement ? stoull (name.substr (static_cast<size_t> (offsetIndex))) : 0 }; } /** * @brief This function creates a YAML node representing a key value. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 plugin before you use YAML CPP. * * @returns A new YAML node containing the data specified in `key` */ YAML::Node createMetaDataNode (Key const & key) { if (key.hasMeta ("array")) { return YAML::Node (YAML::NodeType::Sequence); } if (key.getBinarySize () == 0) { return YAML::Node (YAML::NodeType::Null); } if (key.isBinary ()) { return YAML::Node ("Unsupported binary value!"); } auto value = key.get<string> (); if (value == "0" || value == "1") { return YAML::Node (key.get<bool> ()); } return YAML::Node (value); } /** * @brief This function creates a YAML Node containing a key value and optionally metadata. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP. * * @returns A new YAML node containing the data and metadata specified in `key` */ YAML::Node createLeafNode (Key & key) { YAML::Node metaNode{ YAML::Node (YAML::NodeType::Map) }; YAML::Node dataNode = createMetaDataNode (key); key.rewindMeta (); while (Key meta = key.nextMeta ()) { if (meta.getName () == "array" || meta.getName () == "binary") continue; if (meta.getName () == "type" && meta.getString () == "binary") { dataNode.SetTag ("tag:yaml.org,2002:binary"); continue; } metaNode[meta.getName ()] = meta.getString (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", meta.getName ().c_str (), meta.getString ().c_str ()); } if (metaNode.size () <= 0) { ELEKTRA_LOG_DEBUG ("Return leaf node with value “%s”", dataNode.IsNull () ? "~" : dataNode.IsSequence () ? "[]" : dataNode.as<string> ().c_str ()); return dataNode; } YAML::Node node{ YAML::Node (YAML::NodeType::Sequence) }; node.SetTag ("!elektra/meta"); node.push_back (dataNode); node.push_back (metaNode); #ifdef HAVE_LOGGER ostringstream data; data << node; ELEKTRA_LOG_DEBUG ("Return meta leaf node with value “%s”", data.str ().c_str ()); #endif return node; } /** * @brief This function adds `null` elements to the given YAML collection. * * @param sequence This node stores the collection to which this function adds `numberOfElements` empty elements. * @param numberOfElements This parameter specifies the number of empty element this function adds to `sequence`. */ void addEmptyArrayElements (YAML::Node & sequence, unsigned long long const numberOfElements) { ELEKTRA_LOG_DEBUG ("Add %lld empty array elements", numberOfElements); for (auto missingFields = numberOfElements; missingFields > 0; missingFields--) { sequence.push_back ({}); } } /** * @brief This function adds a key that is not part of any array to a YAML node. * * @param data This node stores the data specified via `keyIterator`. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. */ void addKeyNoArray (YAML::Node & data, NameIterator & keyIterator, Key & key) { if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined); #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Add key part “%s”", (*keyIterator).c_str ()); #endif if (keyIterator == key.end ()) { ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ()); data = createLeafNode (key); return; } if (keyIterator == --key.end ()) { data[*keyIterator] = createLeafNode (key); return; } YAML::Node node; node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node (); data[*keyIterator] = node; addKeyNoArray (node, ++keyIterator, key); } /** * @brief This function adds a key that is either, element of an array, or an array parent to a YAML node. * * @param data This node stores the data specified via `keyIterator`. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. */ void addKeyArray (YAML::Node & data, NameIterator & keyIterator, Key & key) { auto const isArrayAndIndex = isArrayIndex (keyIterator); auto const isArrayElement = isArrayAndIndex.first; auto const arrayIndex = isArrayAndIndex.second; if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined); #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Add key part “%s”", (*keyIterator).c_str ()); #endif if (keyIterator == key.end ()) { ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ()); data = createLeafNode (key); return; } if (keyIterator == --key.end ()) { if (isArrayElement) { addEmptyArrayElements (data, arrayIndex - data.size ()); data.push_back (createLeafNode (key)); } else { data[*keyIterator] = createLeafNode (key); } return; } YAML::Node node; if (isArrayElement) { node = (data[arrayIndex] && !data[arrayIndex].IsScalar ()) ? data[arrayIndex] : YAML::Node (); data[arrayIndex] = node; } else { node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node (); data[*keyIterator] = node; } addKeyArray (node, ++keyIterator, key); } /** * @brief This function adds a key set to a YAML node. * * @param data This node stores the data specified via `mappings`. * @param mappings This keyset specifies all keys and values this function adds to `data`. * @param parent This key is the root of all keys stored in `mappings`. * @param isArray This value specifies if the keys inside `keys` are all part of an array (either element or parent), or if none of them is * part of an array. */ void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent, bool const isArray = false) { for (auto key : mappings) { ELEKTRA_LOG_DEBUG ("Convert key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); NameIterator keyIterator = relativeKeyIterator (key, parent); if (isArray) { addKeyArray (data, keyIterator, key); } else { addKeyNoArray (data, keyIterator, key); } #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Converted Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (output.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif } } } // end namespace /** * @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`. * * @param mappings This key set stores the mappings that should be saved as YAML data. * @param parent This key specifies the path to the YAML data file that should be written. */ void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent) { KeySet keys = mappings; auto missing = missingKeys (keys, parent); keys.append (missing); KeySet arrayParents; KeySet arrays; KeySet nonArrays; arrayParents = splitArrayParents (keys); tie (arrays, nonArrays) = splitArrayOther (arrayParents, keys); auto data = YAML::Node (); addKeys (data, nonArrays, parent); addKeys (data, arrays, parent, true); #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Write Data:"); ELEKTRA_LOG_DEBUG ("——————————"); ostringstream outputString; outputString << data; istringstream stream (outputString.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif ofstream output (parent.getString ()); output << data << endl; } <|endoftext|>
<commit_before>#include <znc/User.h> #include <znc/znc.h> using std::map; using std::vector; class CUserIPMod : public CModule { private: typedef map<CString, CUser*> MUsers; void ShowCommand(const CString& sLine) { if (!GetUser()->IsAdmin()) { PutModule("Access denied"); return; } } public: MODCONSTRUCTOR(CUserIPMod) {} ~CUserIPMod() override {} // Web stuff: bool WebRequiresAdmin() override { return true; } CString GetWebMenuTitle() override { return "User IPs"; } bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { if (sPageName == "index") { CModules& GModules = CZNC::Get().GetModules(); Tmpl["WebAdminLoaded"] = CString(GModules.FindModule("webadmin") != nullptr); const MUsers& mUsers = CZNC::Get().GetUserMap(); for (MUsers::const_iterator it = mUsers.begin(); it != mUsers.end(); ++it) { CUser* pUser = it->second; CTemplate& Row = Tmpl.AddRow("UserLoop"); Row["User"] = pUser->GetUserName(); const std::vector<CClient*>& vClients = pUser->GetAllClients(); CString cli = ""; for (client:vClients) { cli.append(client->GetRemoteIP()); cli.append(" "); } Row["IP"] = cli; } return true; } return false; } }; template <> void TModInfo<CUserIPMod>(CModInfo& Info) {} GLOBALMODULEDEFS(CUserIPMod, "Shows connected IPs for users.") <commit_msg>Require GCC 4.7+<commit_after>/* Requires GCC 4.7+ */ #include <znc/User.h> #include <znc/znc.h> using std::map; using std::vector; class CUserIPMod : public CModule { private: typedef map<CString, CUser*> MUsers; void ShowCommand(const CString& sLine) { if (!GetUser()->IsAdmin()) { PutModule("Access denied"); return; } } public: MODCONSTRUCTOR(CUserIPMod) {} ~CUserIPMod() override {} // Web stuff: bool WebRequiresAdmin() override { return true; } CString GetWebMenuTitle() override { return "User IPs"; } bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { if (sPageName == "index") { CModules& GModules = CZNC::Get().GetModules(); Tmpl["WebAdminLoaded"] = CString(GModules.FindModule("webadmin") != nullptr); const MUsers& mUsers = CZNC::Get().GetUserMap(); for (MUsers::const_iterator it = mUsers.begin(); it != mUsers.end(); ++it) { CUser* pUser = it->second; CTemplate& Row = Tmpl.AddRow("UserLoop"); Row["User"] = pUser->GetUserName(); const std::vector<CClient*>& vClients = pUser->GetAllClients(); CString cli = ""; for (client:vClients) { cli.append(client->GetRemoteIP()); cli.append(" "); } Row["IP"] = cli; } return true; } return false; } }; template <> void TModInfo<CUserIPMod>(CModInfo& Info) {} GLOBALMODULEDEFS(CUserIPMod, "Shows connected IPs for users.") <|endoftext|>
<commit_before>#include "opencv2/objdetect.hpp" //#include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> #include <stdio.h> using namespace std; using namespace cv; int imageHeight; int numPos = 100; // number of positive images int numNeg = 100; // number of negatives images void showImageFromVector(Mat image, int height) { Mat temp = image.clone(); imshow("Image", temp.reshape(0, height)); char c = (char)waitKey(200); } void showImageFromVectorRow(Mat images, int rowIndex, int height) { Mat temp = images.row(rowIndex).clone(); imshow("Image" + to_string(rowIndex), temp.reshape(0, height)); char c = (char)waitKey(200); } double isBee() { } double runTest(Mat reduced_images, Mat Eigencolumns, Mat multi) { double accuracy = 0; int numTested = 0; int correct = 0; Mat test_image; //filename = "images/pos/pos-img258.jpg"; String posTest = "images/test/neg/test-neg-img0.jpg"; String negTest = "images/test/pos/test-pos-img3.jpg"; // loop through each pos test for (int i = 0; i < numPos; i++) { sdfsfsdfsd }s // get the test image Mat mat = imread(posTest, IMREAD_GRAYSCALE); if (mat.empty()) { cout << "empty image" << endl; cout << posTest; } else { test_image.push_back(mat.reshape(0, 1)); } // subtract mean from test image Mat subtracted_test; Mat outMat; subtract(test_image.row(0), reduced_images, outMat); subtracted_test.push_back(outMat); // multiple subtracted test data with eigen vector Mat normalizedTest; subtracted_test.convertTo(normalizedTest, CV_32FC1); Mat Test = normalizedTest * Eigencolumns; // get Euclidean distance of test image and data float min = -1; int position = -1; float current_value = 0; // double dist = norm(a, b, NORM_L2); for (int i = 0; i < multi.rows; i++) { current_value = norm(multi.row(i), Test.row(0)); //abs(multi.at<float>(i,0) - Test.at<float>(0, 0)); if (min == -1) { min = current_value; position = i; } else if (current_value < min) { min = current_value; position = i; } } // results for image cout << "min: " << min << endl; cout << "position: " << position << endl; /* positioon < numPos | positive position >= numPos | negative */ if (position < numPos) { //temp = subtracted_matrix.row(position).clone(); //imshow("positive", temp.reshape(0, imageHeight)); cout << "positive" << endl; } else { //temp = subtracted_matrix.row(position).clone(); //imshow("negative", temp.reshape(0, imageHeight)); cout << "negative" << endl; } imshow("test image", mat); char c = (char)waitKey(0); if (c == 27) {} return accuracy; } int main(void) { Mat images; string pos_name = "images/pos/vertical-pos-img"; string neg_name = "images/neg/neg-img"; Mat mat; // used as temp storage when reading images Mat temp; string filename; char c; int counter = 0; ///store the images into a matrix for (; counter < numPos; counter++) { filename = pos_name + to_string(counter) + ".jpg"; mat = imread(filename, IMREAD_GRAYSCALE); if (mat.empty()) { cout << "empty image" << endl; cout << filename; } else { images.push_back(mat.reshape(0, 1)); } //showImageFromVectorRow(images, counter, mat.rows); } imageHeight = mat.rows; //imshow("Image_test", images.row(1).clone().reshape(0, mat.rows)); ///get the mean of the matrix in reduced form Mat reduced_images; reduce(images, reduced_images, 0, CV_REDUCE_AVG, -1); //showImageFromVector(reduced_images, mat.rows); ///subtracted mean from matrix and store in new matrix Mat subtracted_matrix; Mat temp2; for (int i = 0; i < counter; i++) { subtract(images.row(i), reduced_images, temp2); subtracted_matrix.push_back(temp2); //showImageFromVectorRow(subtracted_matrix, i, imageHeight); } cout << "finished subtracting" << endl; ///Using PCA to get eigenvalues and vectors PCA pca(images, Mat(), PCA::DATA_AS_ROW); //cout << "values" << endl; cout << pca.eigenvalues << endl; //cout << "vector" << endl; cout << pca.eigenvectors << endl; double eigensum = 0; Mat eigen = pca.eigenvalues; double eigsum = cv::sum(pca.eigenvalues)[0]; Mat eigenVec = pca.eigenvectors; Mat eigenVecTrans = eigenVec.t(); int length = eigen.rows; float thresh = 0; float sum = 0; int k95 = 0; //cout << eigsum << endl; //cout << length << endl; ///getting how many columns to use for (int i = 0; i < length; i++) { sum = sum + eigen.at<float>(i, 0); //cout << sum << endl; thresh = sum / eigsum; //cout << thresh << endl; if (thresh > 0.95) { k95 = i; break; } } cout << "Threshold 95: vectors: " << k95 << endl; ///multiplying the subtracted matrix with eigenvectors //Mat Eigencolumns = eigenVecTrans.col(0); Mat Eigenrows; Mat Eigencolumns; // push k95 rows into the eigenvectors for (int i = 0; i <= k95; i++) { Eigenrows.push_back(eigenVec.row(i)); } // transform to cols (to multiply) Eigencolumns = Eigenrows.t(); Mat normalizedSub; // push the negative images into the subtracted matrix for (counter = 0; counter < numNeg; counter++) { // read neg image filename = neg_name + to_string(counter) + ".jpg"; mat = imread(filename, IMREAD_GRAYSCALE); if (mat.empty()) { cout << "empty image" << endl; cout << filename; } else { // subtract the mean from the negative image before adding subtract(mat.reshape(0, 1), reduced_images, temp2); subtracted_matrix.push_back(temp2); } //temp = images.row(counter).clone(); //imshow("Image" + to_string(counter), temp.reshape(0, mat.rows)); //c = (char)waitKey(200); //if (c == 27) { break; } } //normalize(subtracted_matrix, normalizedSub, 0, 255, NORM_MINMAX, CV_32FC1); // change format from CV_8U to CV_32FC1 subtracted_matrix.convertTo(normalizedSub, CV_32FC1); // reduced features received from finding the product Mat multi = normalizedSub * Eigencolumns; double result = runTest(reduced_images, Eigencolumns, multi); cout << result << endl; return 0; }<commit_msg>Add testing method including the isBee<commit_after>#include "opencv2/objdetect.hpp" //#include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> #include <stdio.h> using namespace std; using namespace cv; int imageHeight; int numPos = 100; // number of positive images int numNeg = 100; // number of negatives images String posTestName = "images/test/pos/test-pos-img"; String negTestName = "images/test/neg/test-neg-img"; void showImageFromVector(Mat image, int height) { Mat temp = image.clone(); imshow("Image", temp.reshape(0, height)); char c = (char)waitKey(200); } void showImageFromVectorRow(Mat images, int rowIndex, int height) { Mat temp = images.row(rowIndex).clone(); imshow("Image" + to_string(rowIndex), temp.reshape(0, height)); char c = (char)waitKey(200); } bool isBee(Mat test_image, Mat reduced_images, Mat Eigencolumns, Mat multi) { // subtract mean from test image Mat outMat; Mat subtracted_test; subtract(test_image.row(0), reduced_images, outMat); subtracted_test.push_back(outMat); // multiply subtracted test data with eigen vector Mat normalizedTest; Mat Test; subtracted_test.convertTo(normalizedTest, CV_32FC1); Test = normalizedTest * Eigencolumns; // get Euclidean distance of test image and data float min = -1; int position = -1; float current_value = 0; // double dist = norm(a, b, NORM_L2); for (int i = 0; i < multi.rows; i++) { current_value = norm(multi.row(i), Test.row(0)); //abs(multi.at<float>(i,0) - Test.at<float>(0, 0)); if (min == -1) { min = current_value; position = i; } else if (current_value < min) { min = current_value; position = i; } } // results for image cout << "min: " << min << endl; cout << "position: " << position << endl; /* positioon < numPos | positive position >= numPos | negative */ if (position < numPos) { //temp = subtracted_matrix.row(position).clone(); //imshow("positive", temp.reshape(0, imageHeight)); cout << "positive" << endl; return true; } else { //temp = subtracted_matrix.row(position).clone(); //imshow("negative", temp.reshape(0, imageHeight)); cout << "negative" << endl; return false; } return false; } double runTest(Mat reduced_images, Mat Eigencolumns, Mat multi) { Mat mat; Mat test_image; String filename; int posTestNum = 280; // 0-279 int negTestNum = 63; // 0-62 int numTested = posTestNum + negTestNum; int correct = 0; double accuracy = 0; // loop through each pos test (0->posNum-1) for (int i = 0; i < posTestNum; i++) { filename = posTestName + to_string(i) + ".jpg"; cout << "reading file: " << filename << endl; // get the test image Mat mat = imread(filename, IMREAD_GRAYSCALE); // check for empty image if (mat.empty()) { cout << "empty image" << endl; } else { test_image = mat.reshape(0, 1); if (isBee(test_image, reduced_images, Eigencolumns, multi)) { correct++; } } } for (int i = 0; i < negTestNum; i++) { filename = negTestName + to_string(i) + ".jpg"; cout << "reading file: " << filename << endl; // get the test image Mat mat = imread(filename, IMREAD_GRAYSCALE); // check for empty image if (mat.empty()) { cout << "empty image" << endl; } else { test_image = mat.reshape(0, 1); // negatives are not bees if (!isBee(test_image, reduced_images, Eigencolumns, multi)) { correct++; } } /* show test image imshow("test image", mat); char c = (char)waitKey(0); if (c == 27) {} */ } accuracy = correct / numTested; cout << " correct: " << correct << endl; cout << " accuracy: " << accuracy << endl; return accuracy; } int main(void) { Mat images; string pos_name = "images/pos/vertical-pos-img"; string neg_name = "images/neg/neg-img"; Mat mat; // used as temp storage when reading images Mat temp; string filename; char c; int counter = 0; ///store the images into a matrix for (; counter < numPos; counter++) { filename = pos_name + to_string(counter) + ".jpg"; mat = imread(filename, IMREAD_GRAYSCALE); if (mat.empty()) { cout << "empty image" << endl; cout << filename; } else { images.push_back(mat.reshape(0, 1)); } //showImageFromVectorRow(images, counter, mat.rows); } imageHeight = mat.rows; //imshow("Image_test", images.row(1).clone().reshape(0, mat.rows)); ///get the mean of the matrix in reduced form Mat reduced_images; reduce(images, reduced_images, 0, CV_REDUCE_AVG, -1); //showImageFromVector(reduced_images, mat.rows); ///subtracted mean from matrix and store in new matrix Mat subtracted_matrix; Mat temp2; for (int i = 0; i < counter; i++) { subtract(images.row(i), reduced_images, temp2); subtracted_matrix.push_back(temp2); //showImageFromVectorRow(subtracted_matrix, i, imageHeight); } cout << "finished subtracting" << endl; ///Using PCA to get eigenvalues and vectors PCA pca(images, Mat(), PCA::DATA_AS_ROW); //cout << "values" << endl; cout << pca.eigenvalues << endl; //cout << "vector" << endl; cout << pca.eigenvectors << endl; double eigensum = 0; Mat eigen = pca.eigenvalues; double eigsum = cv::sum(pca.eigenvalues)[0]; Mat eigenVec = pca.eigenvectors; Mat eigenVecTrans = eigenVec.t(); int length = eigen.rows; float thresh = 0; float sum = 0; int k95 = 0; //cout << eigsum << endl; //cout << length << endl; ///getting how many columns to use for (int i = 0; i < length; i++) { sum = sum + eigen.at<float>(i, 0); //cout << sum << endl; thresh = sum / eigsum; //cout << thresh << endl; if (thresh > 0.95) { k95 = i; break; } } cout << "Threshold 95: vectors: " << k95 << endl; ///multiplying the subtracted matrix with eigenvectors //Mat Eigencolumns = eigenVecTrans.col(0); Mat Eigenrows; Mat Eigencolumns; // push k95 rows into the eigenvectors for (int i = 0; i <= k95; i++) { Eigenrows.push_back(eigenVec.row(i)); } // transform to cols (to multiply) Eigencolumns = Eigenrows.t(); Mat normalizedSub; // push the negative images into the subtracted matrix for (counter = 0; counter < numNeg; counter++) { // read neg image filename = neg_name + to_string(counter) + ".jpg"; mat = imread(filename, IMREAD_GRAYSCALE); if (mat.empty()) { cout << "empty image" << endl; cout << filename; } else { // subtract the mean from the negative image before adding subtract(mat.reshape(0, 1), reduced_images, temp2); subtracted_matrix.push_back(temp2); } //temp = images.row(counter).clone(); //imshow("Image" + to_string(counter), temp.reshape(0, mat.rows)); //c = (char)waitKey(200); //if (c == 27) { break; } } //normalize(subtracted_matrix, normalizedSub, 0, 255, NORM_MINMAX, CV_32FC1); // change format from CV_8U to CV_32FC1 subtracted_matrix.convertTo(normalizedSub, CV_32FC1); // reduced features received from finding the product Mat multi = normalizedSub * Eigencolumns; double result = runTest(reduced_images, Eigencolumns, multi); cin >> result; return 0; }<|endoftext|>
<commit_before>// // Created by Sam on 11/18/2017. // #include "../../../build/catch-src/include/catch.hpp" #include "../../../include/Game/Python/Factory.h" TEST_CASE("Create factory") { SECTION("Verify minimum python version") { auto* factory = new Factory(); std::string minimumVersion = "2.7"; bool versionCheck = Version(minimumVersion) < factory->version; REQUIRE(versionCheck); delete factory; } SECTION("Verify expected python version") { auto* factory = new Factory(); std::string expectedVersion = "3.6.3"; bool versionCheck = Version(expectedVersion) == factory->version; if (!versionCheck) { FAIL_CHECK("Unexpected python version, expected " + expectedVersion + " but factory's interpreter is running " + factory->version.toString()); } delete factory; } }<commit_msg>Tried using a shared ptr to handle the memory management, might be running into a catch2 issue with embedding the interpreter in tests<commit_after>// // Created by Sam on 11/18/2017. // #include "../../../build/catch-src/include/catch.hpp" #include "../../../include/Game/Python/Factory.h" TEST_CASE("Create factory") { std::shared_ptr<Factory> factory = std::make_shared<Factory>(); SECTION("Verify creation") { REQUIRE_FALSE(factory == nullptr); } SECTION("Verify minimum python version") { std::string minimumVersion = "2.7"; bool versionCheck = Version(minimumVersion) < factory->version; REQUIRE(versionCheck); } SECTION("Verify expected python version") { std::string expectedVersion = "3.6.3"; bool versionCheck = Version(expectedVersion) == factory->version; if (!versionCheck) { FAIL_CHECK("Unexpected python version, expected " + expectedVersion + " but factory's interpreter is running " + factory->version.toString()); } } }<|endoftext|>
<commit_before>#pragma once #include "../range.hpp" namespace frea { namespace random { template <class T, class RD> Range<T> GenRange(RD&& rd) { T rmin = rd(), rmax = rd(); if(rmin > rmax) std::swap(rmin, rmax); return {rmin, rmax}; } } } <commit_msg>Rangeランダム生成関数のバグ修正<commit_after>#pragma once #include "../range.hpp" namespace frea { namespace random { template <class T, class RD> Range<T> GenRange(RD&& rd) { auto rmin = rd(), rmax = rd(); if(rmin > rmax) std::swap(rmin, rmax); return {rmin, rmax}; } } } <|endoftext|>
<commit_before>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <sys/socket.h> #include "utils.h" #include "cJSON.h" #include "client_http.h" // // Xapian http client // HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_) : BaseClient(loop, sock_, database_pool_, thread_pool_, active_timeout_, idle_timeout_) { parser.data = this; http_parser_init(&parser, HTTP_REQUEST); LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, XapiandServer::total_clients); } HttpClient::~HttpClient() { } void HttpClient::on_read(const char *buf, ssize_t received) { size_t parsed = http_parser_execute(&parser, &settings, buf, received); if (parsed == received) { if (parser.state == 1 || parser.state == 18) { // dead or message_complete try { // LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method); // LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str()); // LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str()); std::string content; cJSON *json = cJSON_Parse(body.c_str()); cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL; cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL; cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL; cJSON *root = cJSON_CreateObject(); cJSON *response = cJSON_CreateObject(); cJSON_AddItemToObject(root, "response", response); if (text) { cJSON_AddStringToObject(response, "status", "OK"); cJSON_AddStringToObject(response, "query", text->valuestring); cJSON_AddStringToObject(response, "title", "The title"); cJSON_AddNumberToObject(response, "items", 7); const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; cJSON *results = cJSON_CreateArray(); cJSON_AddItemToObject(response, "results", results); for (int i = 0; i < 7; i++) { cJSON *result = cJSON_CreateObject(); cJSON_AddNumberToObject(result, "id", i); cJSON_AddStringToObject(result, "name", strings[i]); cJSON_AddItemToArray(results, result); } } else { LOG_HTTP_PROTO(this, "Error before: [%s]\n", cJSON_GetErrorPtr()); cJSON_AddStringToObject(response, "status", "ERROR"); const char *message = cJSON_GetErrorPtr(); if (message) { cJSON_AddStringToObject(response, "message", message); } } cJSON_Delete(json); bool pretty = false; char *out; if (pretty) { out = cJSON_Print(root); } else { out = cJSON_PrintUnformatted(root); } content = out; cJSON_Delete(root); free(out); char tmp[20]; std::string http_response; http_response += "HTTP/"; sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor); http_response += tmp; http_response += " 200 OK\r\n"; http_response += "Content-Type: application/json; charset=UTF-8\r\n"; http_response += "Content-Length: "; sprintf(tmp, "%ld", content.size()); http_response += tmp; http_response += "\r\n"; write(http_response + "\r\n" + content); if (parser.state == 1) close(); } catch (...) { LOG_ERR(this, "ERROR!\n"); } } } else { enum http_errno err = HTTP_PARSER_ERRNO(&parser); const char *desc = http_errno_description(err); const char *msg = err != HPE_OK ? desc : "incomplete request"; LOG_HTTP_PROTO(this, msg); // Handle error. Just close the connection. destroy(); } } // // HTTP parser callbacks. // const http_parser_settings HttpClient::settings = { .on_message_begin = HttpClient::on_info, .on_url = HttpClient::on_data, .on_status = HttpClient::on_data, .on_header_field = HttpClient::on_data, .on_header_value = HttpClient::on_data, .on_headers_complete = HttpClient::on_info, .on_body = HttpClient::on_data, .on_message_complete = HttpClient::on_info }; int HttpClient::on_info(http_parser* p) { HttpClient *self = static_cast<HttpClient *>(p->data); LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state); switch (p->state) { case 18: // message_complete break; case 19: // message_begin self->path.clear(); self->body.clear(); break; } return 0; } int HttpClient::on_data(http_parser* p, const char *at, size_t length) { HttpClient *self = static_cast<HttpClient *>(p->data); LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str()); switch (p->state) { case 32: // path self->path = std::string(at, length); break; case 62: // data self->body = std::string(at, length); break; } return 0; } void HttpClient::run(void *) { } <commit_msg>JSON error message logged only if any<commit_after>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <sys/socket.h> #include "utils.h" #include "cJSON.h" #include "client_http.h" // // Xapian http client // HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_, double active_timeout_, double idle_timeout_) : BaseClient(loop, sock_, database_pool_, thread_pool_, active_timeout_, idle_timeout_) { parser.data = this; http_parser_init(&parser, HTTP_REQUEST); LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, XapiandServer::total_clients); } HttpClient::~HttpClient() { } void HttpClient::on_read(const char *buf, ssize_t received) { size_t parsed = http_parser_execute(&parser, &settings, buf, received); if (parsed == received) { if (parser.state == 1 || parser.state == 18) { // dead or message_complete try { // LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method); // LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str()); // LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str()); std::string content; cJSON *json = cJSON_Parse(body.c_str()); cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL; cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL; cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL; cJSON *root = cJSON_CreateObject(); cJSON *response = cJSON_CreateObject(); cJSON_AddItemToObject(root, "response", response); if (text) { cJSON_AddStringToObject(response, "status", "OK"); cJSON_AddStringToObject(response, "query", text->valuestring); cJSON_AddStringToObject(response, "title", "The title"); cJSON_AddNumberToObject(response, "items", 7); const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; cJSON *results = cJSON_CreateArray(); cJSON_AddItemToObject(response, "results", results); for (int i = 0; i < 7; i++) { cJSON *result = cJSON_CreateObject(); cJSON_AddNumberToObject(result, "id", i); cJSON_AddStringToObject(result, "name", strings[i]); cJSON_AddItemToArray(results, result); } } else { cJSON_AddStringToObject(response, "status", "ERROR"); const char *message = cJSON_GetErrorPtr(); if (message) { LOG_HTTP_PROTO(this, "JSON error before: [%s]\n", message); cJSON_AddStringToObject(response, "message", message); } } cJSON_Delete(json); bool pretty = false; char *out; if (pretty) { out = cJSON_Print(root); } else { out = cJSON_PrintUnformatted(root); } content = out; cJSON_Delete(root); free(out); char tmp[20]; std::string http_response; http_response += "HTTP/"; sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor); http_response += tmp; http_response += " 200 OK\r\n"; http_response += "Content-Type: application/json; charset=UTF-8\r\n"; http_response += "Content-Length: "; sprintf(tmp, "%ld", content.size()); http_response += tmp; http_response += "\r\n"; write(http_response + "\r\n" + content); if (parser.state == 1) close(); } catch (...) { LOG_ERR(this, "ERROR!\n"); } } } else { enum http_errno err = HTTP_PARSER_ERRNO(&parser); const char *desc = http_errno_description(err); const char *msg = err != HPE_OK ? desc : "incomplete request"; LOG_HTTP_PROTO(this, msg); // Handle error. Just close the connection. destroy(); } } // // HTTP parser callbacks. // const http_parser_settings HttpClient::settings = { .on_message_begin = HttpClient::on_info, .on_url = HttpClient::on_data, .on_status = HttpClient::on_data, .on_header_field = HttpClient::on_data, .on_header_value = HttpClient::on_data, .on_headers_complete = HttpClient::on_info, .on_body = HttpClient::on_data, .on_message_complete = HttpClient::on_info }; int HttpClient::on_info(http_parser* p) { HttpClient *self = static_cast<HttpClient *>(p->data); LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state); switch (p->state) { case 18: // message_complete break; case 19: // message_begin self->path.clear(); self->body.clear(); break; } return 0; } int HttpClient::on_data(http_parser* p, const char *at, size_t length) { HttpClient *self = static_cast<HttpClient *>(p->data); LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str()); switch (p->state) { case 32: // path self->path = std::string(at, length); break; case 62: // data self->body = std::string(at, length); break; } return 0; } void HttpClient::run(void *) { } <|endoftext|>
<commit_before>/** * @file c_api_version.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2016 MIT and Intel Corporation * * 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. * * @section DESCRIPTION * * Tests for the C API library version */ #include "c_api_version.h" #include "utils.h" #include <unistd.h> /* ****************************** */ /* GTEST FUNCTIONS */ /* ****************************** */ void LibraryVersionFixture::SetUp() { } void LibraryVersionFixture::TearDown() { } /* ****************************** */ /* TESTS */ /* ****************************** */ /** * Tests the library version */ TEST_F(LibraryVersionFixture, test_library_version) { int major = -1; int minor = -1; int rev = -1; tiledb_version(&major, &minor, &rev); ASSERT_EQ(major, 0); ASSERT_EQ(minor, 6); ASSERT_EQ(rev, 0); } <commit_msg>Changing the version on tests<commit_after>/** * @file c_api_version.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2016 MIT and Intel Corporation * * 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. * * @section DESCRIPTION * * Tests for the C API library version */ #include "c_api_version.h" #include "utils.h" #include <unistd.h> /* ****************************** */ /* GTEST FUNCTIONS */ /* ****************************** */ void LibraryVersionFixture::SetUp() { } void LibraryVersionFixture::TearDown() { } /* ****************************** */ /* TESTS */ /* ****************************** */ /** * Tests the library version */ TEST_F(LibraryVersionFixture, test_library_version) { int major = -1; int minor = -1; int rev = -1; tiledb_version(&major, &minor, &rev); ASSERT_EQ(major, 0); ASSERT_EQ(minor, 6); ASSERT_EQ(rev, 1); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // packet_manager_test.cpp // // Identification: test/wire/packet_manager_test.cpp // // Copyright (c) 2016-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "common/harness.h" #include "gtest/gtest.h" #include "common/logger.h" #include "wire/libevent_server.h" #include <pqxx/pqxx> /* libpqxx is used to instantiate C++ client */ #define NUM_THREADS 1 namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Packet Manager Tests //===--------------------------------------------------------------------===// class PacketManagerTests : public PelotonTest {}; static void *LaunchServer(peloton::wire::LibeventServer libeventserver) { try { libeventserver.StartServer(); } catch (peloton::ConnectionException exception) { LOG_INFO("[LaunchServer] exception in thread"); } return NULL; } /** * Simple select query test */ static void *SimpleQueryTest(void *) { try { pqxx::connection C( "host=127.0.0.1 port=15721 user=postgres sslmode=disable"); LOG_INFO("[SimpleQueryTest] Connected to %s", C.dbname()); pqxx::work W(C); peloton::wire::LibeventSocket *conn = peloton::wire::LibeventServer::GetConn( peloton::wire::LibeventServer::recent_connfd); EXPECT_EQ(conn->pkt_manager.is_started, true); EXPECT_EQ(conn->state, peloton::wire::CONN_READ); // create table and insert some data W.exec("DROP TABLE IF EXISTS employee;"); W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));"); W.exec("INSERT INTO employee VALUES (1, 'Han LI');"); W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');"); W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');"); pqxx::result R = W.exec("SELECT name FROM employee where id=1;"); EXPECT_EQ(R.size(), 1); LOG_INFO("[SimpleQueryTest] Found %lu employees", R.size()); W.commit(); } catch (const std::exception &e) { LOG_INFO("[SimpleQueryTest] Exception occurred"); } LOG_INFO("[SimpleQueryTest] Client has closed"); return NULL; } /** * named prepare statement without parameters * TODO: add prepare's parameters when parser team fix the bug */ static void *PrepareStatementTest(void *) { try { pqxx::connection C( "host=127.0.0.1 port=15721 user=postgres sslmode=disable"); LOG_INFO("[PrepareStatementTest] Connected to %s", C.dbname()); pqxx::work W(C); peloton::wire::LibeventSocket *conn = peloton::wire::LibeventServer::GetConn( peloton::wire::LibeventServer::recent_connfd); // create table and insert some data W.exec("DROP TABLE IF EXISTS employee;"); W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));"); W.exec("INSERT INTO employee VALUES (1, 'Han LI');"); W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');"); W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');"); // test prepare statement C.prepare("searchstmt","SELECT name FROM employee WHERE id=1;"); // invocation as in variable binding pqxx::result R = W.prepared("searchstmt").exec(); W.commit(); // test prepared statement already in statement cache // LOG_INFO("[Prepare statement cache] %d",conn->pkt_manager.ExistCachedStatement("searchstmt")); EXPECT_TRUE(conn->pkt_manager.ExistCachedStatement("searchstmt")); LOG_INFO("Prepare statement search result:%lu",R.size()); } catch (const std::exception &e) { LOG_INFO("[PrepareStatementTest] Exception occurred"); } LOG_INFO("[PrepareStatementTest] Client has closed"); return NULL; } /** * Use std::thread to initiate peloton server and pqxx client in separate * threads * Simple query test to guarantee both sides run correctly * Callback method to close server after client finishes */ TEST_F(PacketManagerTests, SimpleQueryTest) { peloton::PelotonInit::Initialize(); LOG_INFO("Server initialized"); peloton::wire::LibeventServer libeventserver; std::thread serverThread(LaunchServer, libeventserver); while (!libeventserver.is_started) { sleep(1); } /* server & client running correctly */ SimpleQueryTest(NULL); /* TODO: monitor packet_manager's status when receiving prepare statement from * client */ // PrepareStatementTest(NULL); libeventserver.CloseServer(); serverThread.join(); LOG_INFO("Thread has joined"); peloton::PelotonInit::Shutdown(); LOG_INFO("Peloton has shut down\n"); } TEST_F(PacketManagerTests, PrepareStatementTest) { peloton::PelotonInit::Initialize(); LOG_INFO("Server initialized"); peloton::wire::LibeventServer libeventserver; std::thread serverThread(LaunchServer, libeventserver); while (!libeventserver.is_started) { sleep(1); } PrepareStatementTest(NULL); libeventserver.CloseServer(); serverThread.join(); LOG_INFO("Thread has joined"); peloton::PelotonInit::Shutdown(); LOG_INFO("Peloton has shut down\n"); } } // End test namespace } // End peloton namespace <commit_msg>add rollback test<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // packet_manager_test.cpp // // Identification: test/wire/packet_manager_test.cpp // // Copyright (c) 2016-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "common/harness.h" #include "gtest/gtest.h" #include "common/logger.h" #include "wire/libevent_server.h" #include <pqxx/pqxx> /* libpqxx is used to instantiate C++ client */ #define NUM_THREADS 1 namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Packet Manager Tests //===--------------------------------------------------------------------===// class PacketManagerTests : public PelotonTest {}; static void *LaunchServer(peloton::wire::LibeventServer libeventserver) { try { libeventserver.StartServer(); } catch (peloton::ConnectionException exception) { LOG_INFO("[LaunchServer] exception in thread"); } return NULL; } /** * Simple select query test */ static void *SimpleQueryTest(void *) { try { pqxx::connection C( "host=127.0.0.1 port=15721 user=postgres sslmode=disable"); LOG_INFO("[SimpleQueryTest] Connected to %s", C.dbname()); pqxx::work W(C); peloton::wire::LibeventSocket *conn = peloton::wire::LibeventServer::GetConn( peloton::wire::LibeventServer::recent_connfd); EXPECT_EQ(conn->pkt_manager.is_started, true); EXPECT_EQ(conn->state, peloton::wire::CONN_READ); // create table and insert some data W.exec("DROP TABLE IF EXISTS employee;"); W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));"); W.exec("INSERT INTO employee VALUES (1, 'Han LI');"); W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');"); W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');"); pqxx::result R = W.exec("SELECT name FROM employee where id=1;"); EXPECT_EQ(R.size(), 1); LOG_INFO("[SimpleQueryTest] Found %lu employees", R.size()); W.commit(); } catch (const std::exception &e) { LOG_INFO("[SimpleQueryTest] Exception occurred"); } LOG_INFO("[SimpleQueryTest] Client has closed"); return NULL; } /** * named prepare statement without parameters * TODO: add prepare's parameters when parser team fix the bug */ static void *PrepareStatementTest(void *) { try { pqxx::connection C( "host=127.0.0.1 port=15721 user=postgres sslmode=disable"); LOG_INFO("[PrepareStatementTest] Connected to %s", C.dbname()); pqxx::work W(C); peloton::wire::LibeventSocket *conn = peloton::wire::LibeventServer::GetConn( peloton::wire::LibeventServer::recent_connfd); // create table and insert some data W.exec("DROP TABLE IF EXISTS employee;"); W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));"); W.exec("INSERT INTO employee VALUES (1, 'Han LI');"); W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');"); W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');"); // test prepare statement C.prepare("searchstmt","SELECT name FROM employee WHERE id=1;"); // invocation as in variable binding pqxx::result R = W.prepared("searchstmt").exec(); W.commit(); // test prepared statement already in statement cache // LOG_INFO("[Prepare statement cache] %d",conn->pkt_manager.ExistCachedStatement("searchstmt")); EXPECT_TRUE(conn->pkt_manager.ExistCachedStatement("searchstmt")); LOG_INFO("Prepare statement search result:%lu",R.size()); } catch (const std::exception &e) { LOG_INFO("[PrepareStatementTest] Exception occurred"); } LOG_INFO("[PrepareStatementTest] Client has closed"); return NULL; } /** * rollback test */ static void *RollbackTest(void *) { try { pqxx::connection C( "host=127.0.0.1 port=15721 user=postgres sslmode=disable"); LOG_INFO("[RollbackTest] Connected to %s", C.dbname()); pqxx::work W(C); peloton::wire::LibeventSocket *conn = peloton::wire::LibeventServer::GetConn( peloton::wire::LibeventServer::recent_connfd); EXPECT_EQ(conn->pkt_manager.is_started, true); EXPECT_EQ(conn->state, peloton::wire::CONN_READ); // create table and insert some data W.exec("DROP TABLE IF EXISTS employee;"); W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));"); w.abort(); // W.exec("INSERT INTO employee VALUES (1, 'Han LI');"); // W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');"); // W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');"); pqxx::result R = W.exec("SELECT name FROM employee where id=1;"); EXPECT_EQ(R.size(), 1); LOG_INFO("[RollbackTest] Found %lu employees", R.size()); W.commit(); } catch (const std::exception &e) { LOG_INFO("[RollbackTest] Exception occurred"); } LOG_INFO("[RollbackTest] Client has closed"); return NULL; } /** * Use std::thread to initiate peloton server and pqxx client in separate * threads * Simple query test to guarantee both sides run correctly * Callback method to close server after client finishes */ TEST_F(PacketManagerTests, SimpleQueryTest) { peloton::PelotonInit::Initialize(); LOG_INFO("Server initialized"); peloton::wire::LibeventServer libeventserver; std::thread serverThread(LaunchServer, libeventserver); while (!libeventserver.is_started) { sleep(1); } /* server & client running correctly */ SimpleQueryTest(NULL); /* TODO: monitor packet_manager's status when receiving prepare statement from * client */ // PrepareStatementTest(NULL); libeventserver.CloseServer(); serverThread.join(); LOG_INFO("Thread has joined"); peloton::PelotonInit::Shutdown(); LOG_INFO("Peloton has shut down\n"); } TEST_F(PacketManagerTests, PrepareStatementTest) { peloton::PelotonInit::Initialize(); LOG_INFO("Server initialized"); peloton::wire::LibeventServer libeventserver; std::thread serverThread(LaunchServer, libeventserver); while (!libeventserver.is_started) { sleep(1); } PrepareStatementTest(NULL); libeventserver.CloseServer(); serverThread.join(); LOG_INFO("Thread has joined"); peloton::PelotonInit::Shutdown(); LOG_INFO("Peloton has shut down\n"); } TEST_F(PacketManagerTests, RollbackTest) { peloton::PelotonInit::Initialize(); LOG_INFO("Server initialized"); peloton::wire::LibeventServer libeventserver; std::thread serverThread(LaunchServer, libeventserver); while (!libeventserver.is_started) { sleep(1); } RollbackTest(NULL); libeventserver.CloseServer(); serverThread.join(); LOG_INFO("Thread has joined"); peloton::PelotonInit::Shutdown(); LOG_INFO("Peloton has shut down\n"); } } // End test namespace } // End peloton namespace <|endoftext|>
<commit_before>#ifndef SPL_UPSAMPLER_HH #define SPL_UPSAMPLER_HH #include "2DSignal.hh" #include "stdtools.hh" namespace spl { template<typename V, unsigned L> struct BilinearInterpolation { const Signal2D<V>& _sig; BilinearInterpolation(const Signal2D<V>& sig) : _sig(sig) {} V operator()(unsigned x, unsigned y) { double x1 = x/(L+2); double y1 = y/(L+2); double x2 = x1+1; double y2 = y1+1; double f11 = _sig(x1, y1); double f12 = _sig(x1, y2); double f21 = _sig(x2, y1); double f22 = _sig(x2, y2); x1 *= (L+1); y1 *= (L+1); x2 *= (L+1); y2 *= (L+1); double res = /*(double)((1/((x2-x1)*(y2-y1))) */ (f11*(x2 - x)*(y2 - y) + f21*(x - x1)*(y2 - y) + f12*(x2 - x)*(y - y1) + f22*(x - x1)*(y - y1) ); res /= ((x2-x1)*(y2-y1)); return std::round(res); } }; template<typename V, template<typename V, unsigned L> class interpolation,unsigned L=1> struct Up2DSampler { const Signal2D<V>& _sig; std::unique_ptr<Signal2D<V> > _up_sig; const Signal2D<V>& res(){ return (*_up_sig); } Up2DSampler(const Signal2D<V>& sig) : _sig(sig) , _up_sig(nullptr) { traits_domain_type(Signal2D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] += L*(dom[i]-1); _up_sig.reset(new Signal2D<V>(dom)); } void operator()() { interpolation<V,L> op_int(_sig); traits_iterator_type(Signal2D<V>) it((*_up_sig).domain()); for_each_elements(it) (*_up_sig)[it] = op_int(it[0],it[1]); } }; template<typename V, template<typename V, unsigned L> class interpolation,unsigned L=1> struct Up2DSequenceSampler { const Signal3D<V> &_sig; std::unique_ptr<Signal3D<V> > _up_sig; const Signal3D<V> &res(){ return (*_up_sig); } Up2DSequenceSampler(const Signal3D<V>& sig) : _sig(sig) , _up_sig(nullptr) { traits_domain_type(Signal3D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] += L*(dom[i]-1); _up_sig = new Signal3D<V>(dom); } void operator()() { const std::vector<Signal2D<V> > &signal = static_cast<std::vector<Signal2D<V> > >(_sig); /*for(unsigned i=0; i < (*_up_sig).domain()[2]; ++i) { Up2DSampler<V,interpolation,L> s(signal[i]); s(); const Signal2D<V> &res = s.res(); for_each_pixels(res,x,y) (*_up_sig)(x,y,i) = res(x,y); }*/ std::cerr<<"Done "<<signal.size()<<std::endl; } }; template<typename V, unsigned L=1> struct Down2DSampler { const Signal2D<V>& _sig; std::unique_ptr<Signal2D<V> > _down_sig; const Signal2D<V>& res(){ return (*_down_sig); } Down2DSampler(const Signal2D<V>& sig) : _sig(sig) , _down_sig(nullptr) { traits_domain_type(Signal2D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] %= L; _down_sig.reset(new Signal2D<V>(dom)); } void operator()() { traits_iterator_type(Signal2D<V>) it((*_down_sig).domain()); for_each_elements(it) (*_down_sig)[it] = _sig[Point2D(it[0]*(L+1), it[1]*(L+1))]; } }; template<typename V,unsigned L=1> struct Down2DSequenceSampler { const Signal3D<V> &_sig; std::unique_ptr<Signal3D<V> > _down_sig; const Signal3D<V> &res(){ return (*_down_sig); } Down2DSequenceSampler(const Signal3D<V>& sig) : _sig(sig) , _down_sig(nullptr) { traits_domain_type(Signal3D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] += L*(dom[i]-1); _down_sig.reset(new Signal3D<V>(dom)); } void operator()() { std::vector<Signal2D<V> > signal(_sig); for(unsigned i=0; i < _sig.domain()[2]; ++i) { Down2DSampler<V,L> s(signal[i]); s(); for_each_pixels(s.res(), x, y) (*_down_sig)(x,y,i) = s.res()(x,y); } } }; template<typename V, bool Uniform> struct Up1DSampler; /* template<typename V> struct Up1DSampler<V, true> { Up1DSampler(const Signal1D<V> &in) : _sig(in) , _res(nb_point) {} void operator() { // Get min drivative double min_derivative = std::abs(_curve[1] - _curve[0]); // TODO : replace by max int for(unsigned i=1; i < _curve.length(); ++i) { std::cout << std::fabs(_curve[i] - _curve[i-1]) <<std::endl; min_derivative = std::min(min_derivative, std::fabs((double)_curve[i] - _curve[i-1])); } std::cout << "min =" << min_derivative << std::endl; // Oversample the curve : std::vector<double> over_sampled_curve; std::vector<double> over_sampled_time; double acc =0, j = 0; for(unsigned i=1; i < _curve.length(); ++i) { unsigned cnt=0; if(_curve[i-1] < _curve[i]) { for(j= _curve[i-1]+acc; j < _curve[i]; j+= min_derivative) { over_sampled_curve.push_back(j); ++cnt; } acc = j - _curve[i]; } else { for(j= _curve[i-1]+acc; j > _curve[i]; j-= min_derivative) { over_sampled_curve.push_back(j); ++cnt; } acc = j - _curve[i]; } for(unsigned j=0; j < cnt; ++j) over_sampled_time.push_back(i-1 + (double)j/cnt); } over_sampled_curve.push_back(_curve[_curve.length()-1]); over_sampled_time.push_back(_curve.length()-1); } private: const Signal1D<V> &_sig; const Signal1D<V> _res; }; */ }//!spl #endif <commit_msg>Update sampling functions<commit_after>#ifndef SPL_UPSAMPLER_HH #define SPL_UPSAMPLER_HH #include "2DSignal.hh" #include "stdtools.hh" namespace spl { template<typename V, unsigned L> struct BilinearInterpolation { const Signal2D<V>& _sig; BilinearInterpolation(const Signal2D<V>& sig) : _sig(sig) {} V operator()(unsigned x, unsigned y) { assert(std::is_signed_cast_safe(x)); assert(std::is_signed_cast_safe(y)); double x1 = x/(L+2); double y1 = y/(L+2); double x2 = x1+1; double y2 = y1+1; double f11 = _sig(x1, y1); double f12 = _sig(x1, y2); double f21 = _sig(x2, y1); double f22 = _sig(x2, y2); x1 *= (L+1); y1 *= (L+1); x2 *= (L+1); y2 *= (L+1); double res = /*(double)((1/((x2-x1)*(y2-y1))) */ (f11*(x2 - x)*(y2 - y) + f21*(x - x1)*(y2 - y) + f12*(x2 - x)*(y - y1) + f22*(x - x1)*(y - y1) ); res /= ((x2-x1)*(y2-y1)); return std::round(res); } }; template<typename V, template<typename V, unsigned L> class interpolation,unsigned L=1> struct Up2DSampler { const Signal2D<V>& _sig; std::unique_ptr<Signal2D<V> > _up_sig; const Signal2D<V>& res(){ return (*_up_sig); } Up2DSampler(const Signal2D<V>& sig) : _sig(sig) , _up_sig(nullptr) { traits_domain_type(Signal2D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] += L*(dom[i]-1); _up_sig.reset(new Signal2D<V>(dom)); } void operator()() { interpolation<V,L> op_int(_sig); traits_iterator_type(Signal2D<V>) it((*_up_sig).domain()); for_each_elements(it) for_each_inner_pixels((*_up_sig), x, y, 1) (*_up_sig)(x,y) = op_int(x,y); } }; template<typename V, template<typename V, unsigned L> class interpolation,unsigned L=1> struct Up2DSequenceSampler { const Signal3D<V> &_sig; std::unique_ptr<Signal3D<V> > _up_sig; const Signal3D<V> &res(){ return (*_up_sig); } Up2DSequenceSampler(const Signal3D<V>& sig) : _sig(sig) , _up_sig(nullptr) { traits_domain_type(Signal3D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] += L*(dom[i]-1); _up_sig.reset(new Signal3D<V>(dom)); } void operator()() { const std::vector<Signal2D<V> > signal = static_cast<std::vector<Signal2D<V> > >(_sig); for(unsigned i=0; i < (*_up_sig).domain()[2]; ++i) { Up2DSampler<V,interpolation,L> s(signal[i]); s(); const Signal2D<V> &res = s.res(); for_each_pixels(res,x,y) (*_up_sig)(x,y,i) = res(x,y); } std::cerr<<"Done "<<signal.size()<<std::endl; } }; template<typename V, unsigned L=1> struct Down2DSampler { const Signal2D<V>& _sig; std::unique_ptr<Signal2D<V> > _down_sig; const Signal2D<V>& res(){ return (*_down_sig); } Down2DSampler(const Signal2D<V>& sig) : _sig(sig) , _down_sig(nullptr) { traits_domain_type(Signal2D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] %= L; _down_sig.reset(new Signal2D<V>(dom)); } void operator()() { traits_iterator_type(Signal2D<V>) it((*_down_sig).domain()); for_each_elements(it) (*_down_sig)[it] = _sig[Point2D(it[0]*(L+1), it[1]*(L+1))]; } }; template<typename V,unsigned L=1> struct Down2DSequenceSampler { const Signal3D<V> &_sig; std::unique_ptr<Signal3D<V> > _down_sig; const Signal3D<V> &res(){ return (*_down_sig); } Down2DSequenceSampler(const Signal3D<V>& sig) : _sig(sig) , _down_sig(nullptr) { traits_domain_type(Signal3D<V>) dom(_sig.domain()); for(unsigned i=0; i < traits_domain_dim(Signal2D<V>); ++i) dom[i] += L*(dom[i]-1); _down_sig.reset(new Signal3D<V>(dom)); } void operator()() { std::vector<Signal2D<V> > signal(_sig); for(unsigned i=0; i < _sig.domain()[2]; ++i) { Down2DSampler<V,L> s(signal[i]); s(); for_each_pixels(s.res(), x, y) (*_down_sig)(x,y,i) = s.res()(x,y); } } }; template<typename V, bool Uniform> struct Up1DSampler; /* template<typename V> struct Up1DSampler<V, true> { Up1DSampler(const Signal1D<V> &in) : _sig(in) , _res(nb_point) {} void operator() { // Get min drivative double min_derivative = std::abs(_curve[1] - _curve[0]); // TODO : replace by max int for(unsigned i=1; i < _curve.length(); ++i) { std::cout << std::fabs(_curve[i] - _curve[i-1]) <<std::endl; min_derivative = std::min(min_derivative, std::fabs((double)_curve[i] - _curve[i-1])); } std::cout << "min =" << min_derivative << std::endl; // Oversample the curve : std::vector<double> over_sampled_curve; std::vector<double> over_sampled_time; double acc =0, j = 0; for(unsigned i=1; i < _curve.length(); ++i) { unsigned cnt=0; if(_curve[i-1] < _curve[i]) { for(j= _curve[i-1]+acc; j < _curve[i]; j+= min_derivative) { over_sampled_curve.push_back(j); ++cnt; } acc = j - _curve[i]; } else { for(j= _curve[i-1]+acc; j > _curve[i]; j-= min_derivative) { over_sampled_curve.push_back(j); ++cnt; } acc = j - _curve[i]; } for(unsigned j=0; j < cnt; ++j) over_sampled_time.push_back(i-1 + (double)j/cnt); } over_sampled_curve.push_back(_curve[_curve.length()-1]); over_sampled_time.push_back(_curve.length()-1); } private: const Signal1D<V> &_sig; const Signal1D<V> _res; }; */ }//!spl #endif <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // materialization_test.cpp // // Identification: tests/executor/materialization_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/planner/abstract_plan.h" #include "backend/planner/materialization_plan.h" #include "backend/planner/seq_scan_plan.h" #include "backend/catalog/manager.h" #include "backend/catalog/schema.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/materialization_executor.h" #include "backend/storage/backend_vm.h" #include "backend/storage/tile.h" #include "backend/storage/tile_group.h" #include "backend/storage/data_table.h" #include "backend/concurrency/transaction.h" #include "backend/executor/abstract_executor.h" #include "backend/executor/seq_scan_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/expression_util.h" #include "backend/storage/table_factory.h" #include "backend/index/index_factory.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" using ::testing::NotNull; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Tile Group Layout Tests //===--------------------------------------------------------------------===// void RunTest() { std::chrono::time_point<std::chrono::system_clock> start, end; const int tuples_per_tilegroup_count = 10; const int tile_group_count = 5; const int tuple_count = tuples_per_tilegroup_count * tile_group_count; const oid_t col_count = 250; const bool is_inlined = true; const bool indexes = false; std::vector<catalog::Column> columns; for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(col_itr), is_inlined); columns.push_back(column); } catalog::Schema *table_schema = new catalog::Schema(columns); std::string table_name("TEST_TABLE"); ///////////////////////////////////////////////////////// // Create table. ///////////////////////////////////////////////////////// bool own_schema = true; bool adapt_table = true; std::unique_ptr<storage::DataTable> table(storage::TableFactory::GetDataTable( INVALID_OID, INVALID_OID, table_schema, table_name, tuples_per_tilegroup_count, own_schema, adapt_table)); // PRIMARY INDEX if (indexes == true) { std::vector<oid_t> key_attrs; auto tuple_schema = table->GetSchema(); catalog::Schema *key_schema; index::IndexMetadata *index_metadata; bool unique; key_attrs = {0}; key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); unique = true; index_metadata = new index::IndexMetadata( "primary_index", 123, INDEX_TYPE_BTREE, INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique); index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata); table->AddIndex(pkey_index); } ///////////////////////////////////////////////////////// // Load in the data ///////////////////////////////////////////////////////// // Insert tuples into tile_group. auto &txn_manager = concurrency::TransactionManager::GetInstance(); const bool allocate = true; auto txn = txn_manager.BeginTransaction(); for (int rowid = 0; rowid < tuple_count; rowid++) { int populate_value = rowid; storage::Tuple tuple(table_schema, allocate); for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto value = ValueFactory::GetIntegerValue(populate_value + col_itr); tuple.SetValue(col_itr, value); } ItemPointer tuple_slot_id = table->InsertTuple(txn, &tuple); EXPECT_TRUE(tuple_slot_id.block != INVALID_OID); EXPECT_TRUE(tuple_slot_id.offset != INVALID_OID); txn->RecordInsert(tuple_slot_id); } txn_manager.CommitTransaction(txn); ///////////////////////////////////////////////////////// // Do a seq scan with predicate on top of the table ///////////////////////////////////////////////////////// start = std::chrono::system_clock::now(); txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Column ids to be added to logical tile after scan. //std::vector<oid_t> column_ids; //for(oid_t col_itr = 0 ; col_itr <= 200; col_itr++) { // column_ids.push_back(col_itr); //} std::vector<oid_t> column_ids({198, 206}); // Create and set up seq scan executor planner::SeqScanPlan seq_scan_node(table.get(), nullptr, column_ids); int expected_num_tiles = tile_group_count; executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get()); // Create and set up materialization executor std::vector<catalog::Column> output_columns; std::unordered_map<oid_t, oid_t> old_to_new_cols; oid_t col_itr = 0; for(auto column_id : column_ids) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(column_id), is_inlined); output_columns.push_back(column); old_to_new_cols[col_itr] = col_itr; col_itr++; } std::unique_ptr<catalog::Schema> output_schema( new catalog::Schema(output_columns)); bool physify_flag = true; // is going to create a physical tile planner::MaterializationPlan mat_node(old_to_new_cols, output_schema.release(), physify_flag); executor::MaterializationExecutor mat_executor(&mat_node, nullptr); mat_executor.AddChild(&seq_scan_executor); EXPECT_TRUE(mat_executor.Init()); std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; for (int i = 0; i < expected_num_tiles; i++) { EXPECT_TRUE(mat_executor.Execute()); std::unique_ptr<executor::LogicalTile> result_tile(mat_executor.GetOutput()); EXPECT_THAT(result_tile, NotNull()); result_tiles.emplace_back(result_tile.release()); } EXPECT_FALSE(mat_executor.Execute()); txn_manager.CommitTransaction(txn); end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "duration :: " << elapsed_seconds.count() << "s\n"; } TEST(TileGroupLayoutTest, RowLayout) { peloton_layout = LAYOUT_ROW; RunTest(); } TEST(TileGroupLayoutTest, ColumnLayout) { peloton_layout = LAYOUT_COLUMN; RunTest(); } TEST(TileGroupLayoutTest, HybridLayout) { peloton_layout = LAYOUT_HYBRID; RunTest(); } } // namespace test } // namespace peloton <commit_msg>Fix tile group layout test<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // materialization_test.cpp // // Identification: tests/executor/materialization_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <unordered_map> #include <vector> #include <chrono> #include <iostream> #include <ctime> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/planner/abstract_plan.h" #include "backend/planner/materialization_plan.h" #include "backend/planner/seq_scan_plan.h" #include "backend/catalog/manager.h" #include "backend/catalog/schema.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/common/value_factory.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/materialization_executor.h" #include "backend/storage/backend_vm.h" #include "backend/storage/tile.h" #include "backend/storage/tile_group.h" #include "backend/storage/data_table.h" #include "backend/concurrency/transaction.h" #include "backend/executor/abstract_executor.h" #include "backend/executor/seq_scan_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/expression_util.h" #include "backend/storage/table_factory.h" #include "backend/index/index_factory.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" using ::testing::NotNull; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Tile Group Layout Tests //===--------------------------------------------------------------------===// void RunTest() { std::chrono::time_point<std::chrono::system_clock> start, end; const int tuples_per_tilegroup_count = 10; const int tile_group_count = 5; const int tuple_count = tuples_per_tilegroup_count * tile_group_count; const oid_t col_count = 250; const bool is_inlined = true; const bool indexes = false; std::vector<catalog::Column> columns; for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(col_itr), is_inlined); columns.push_back(column); } catalog::Schema *table_schema = new catalog::Schema(columns); std::string table_name("TEST_TABLE"); ///////////////////////////////////////////////////////// // Create table. ///////////////////////////////////////////////////////// bool own_schema = true; bool adapt_table = true; std::unique_ptr<storage::DataTable> table(storage::TableFactory::GetDataTable( INVALID_OID, INVALID_OID, table_schema, table_name, tuples_per_tilegroup_count, own_schema, adapt_table)); // PRIMARY INDEX if (indexes == true) { std::vector<oid_t> key_attrs; auto tuple_schema = table->GetSchema(); catalog::Schema *key_schema; index::IndexMetadata *index_metadata; bool unique; key_attrs = {0}; key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); unique = true; index_metadata = new index::IndexMetadata( "primary_index", 123, INDEX_TYPE_BTREE, INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique); index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata); table->AddIndex(pkey_index); } ///////////////////////////////////////////////////////// // Load in the data ///////////////////////////////////////////////////////// // Insert tuples into tile_group. auto &txn_manager = concurrency::TransactionManager::GetInstance(); const bool allocate = true; auto txn = txn_manager.BeginTransaction(); for (int rowid = 0; rowid < tuple_count; rowid++) { int populate_value = rowid; storage::Tuple tuple(table_schema, allocate); for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) { auto value = ValueFactory::GetIntegerValue(populate_value + col_itr); tuple.SetValue(col_itr, value); } ItemPointer tuple_slot_id = table->InsertTuple(txn, &tuple); EXPECT_TRUE(tuple_slot_id.block != INVALID_OID); EXPECT_TRUE(tuple_slot_id.offset != INVALID_OID); txn->RecordInsert(tuple_slot_id); } txn_manager.CommitTransaction(txn); ///////////////////////////////////////////////////////// // Do a seq scan with predicate on top of the table ///////////////////////////////////////////////////////// start = std::chrono::system_clock::now(); txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Column ids to be added to logical tile after scan. //std::vector<oid_t> column_ids; //for(oid_t col_itr = 0 ; col_itr <= 200; col_itr++) { // column_ids.push_back(col_itr); //} std::vector<oid_t> column_ids({198, 206}); // Create and set up seq scan executor planner::SeqScanPlan seq_scan_node(table.get(), nullptr, column_ids); int expected_num_tiles = tile_group_count; executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get()); // Create and set up materialization executor std::vector<catalog::Column> output_columns; std::unordered_map<oid_t, oid_t> old_to_new_cols; oid_t col_itr = 0; for(auto column_id : column_ids) { auto column = catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "FIELD" + std::to_string(column_id), is_inlined); output_columns.push_back(column); old_to_new_cols[col_itr] = col_itr; col_itr++; } std::unique_ptr<catalog::Schema> output_schema( new catalog::Schema(output_columns)); bool physify_flag = true; // is going to create a physical tile planner::MaterializationPlan mat_node(old_to_new_cols, output_schema.release(), physify_flag); executor::MaterializationExecutor mat_executor(&mat_node, nullptr); mat_executor.AddChild(&seq_scan_executor); EXPECT_TRUE(mat_executor.Init()); std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles; for (int i = 0; i < expected_num_tiles; i++) { EXPECT_TRUE(mat_executor.Execute()); std::unique_ptr<executor::LogicalTile> result_tile(mat_executor.GetOutput()); EXPECT_THAT(result_tile, NotNull()); result_tiles.emplace_back(result_tile.release()); } EXPECT_FALSE(mat_executor.Execute()); txn_manager.CommitTransaction(txn); end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "duration :: " << elapsed_seconds.count() << "s\n"; } TEST(TileGroupLayoutTest, RowLayout) { peloton_layout = LAYOUT_ROW; RunTest(); } TEST(TileGroupLayoutTest, ColumnLayout) { peloton_layout = LAYOUT_COLUMN; RunTest(); } } // namespace test } // namespace peloton <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #include <gtest/gtest.h> #include <set> #include "core/util/thread_info.h" namespace bdm { void RunAllChecks(const ThreadInfo& ti) { EXPECT_EQ(omp_get_max_threads(), ti.GetMaxThreads()); EXPECT_EQ(numa_num_configured_nodes(), ti.GetNumaNodes()); std::vector<int> threads_per_numa(ti.GetNumaNodes()); std::vector<std::set<int>> all_numa_thread_ids(ti.GetNumaNodes()); #pragma omp parallel { #pragma omp critical { int tid = omp_get_thread_num(); auto nid = numa_node_of_cpu(sched_getcpu()); // check if mappting openmp thread id to numa node is correct EXPECT_EQ(nid, ti.GetNumaNode(tid)); auto numa_thread_id = ti.GetNumaThreadId(tid); // numa thread id must be smaller than the max number of threads for this // numa node. EXPECT_LT(numa_thread_id, ti.GetThreadsInNumaNode(nid)); std::set<int>& numa_thread_ids = all_numa_thread_ids[nid]; // check if this numa_thread id has not been used before EXPECT_TRUE(numa_thread_ids.find(numa_thread_id) == numa_thread_ids.end()); numa_thread_ids.insert(numa_thread_id); threads_per_numa[nid]++; } } for (uint16_t n = 0; n < ti.GetNumaNodes(); n++) { EXPECT_EQ(threads_per_numa[n], ti.GetThreadsInNumaNode(n)); } } TEST(ThreadInfoTest, All) { auto* ti = ThreadInfo::GetInstance(); RunAllChecks(*ti); } TEST(ThreadInfoTest, ThreadCPUBinding) { auto* ti = ThreadInfo::GetInstance(); RunAllChecks(*ti); // do some work std::vector<int> v; v.resize(1e4); #pragma omp parallel for for (uint64_t i = 0; i < v.size(); i++) { v[i]++; } // check if thread info is still correct RunAllChecks(*ti); } TEST(ThreadInfoTest, Renew) { auto* ti = ThreadInfo::GetInstance(); RunAllChecks(*ti); // schedule this thread on a different NUMA node numa_run_on_node(ti->GetNumaNodes() - 1); ti->Renew(); RunAllChecks(*ti); } } // namespace bdm <commit_msg>Modify ThreadInfoTest.Renew to avoid side effects on other tests<commit_after>// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #include <gtest/gtest.h> #include <set> #include "core/util/thread_info.h" namespace bdm { void RunAllChecks(const ThreadInfo& ti) { EXPECT_EQ(omp_get_max_threads(), ti.GetMaxThreads()); EXPECT_EQ(numa_num_configured_nodes(), ti.GetNumaNodes()); std::vector<int> threads_per_numa(ti.GetNumaNodes()); std::vector<std::set<int>> all_numa_thread_ids(ti.GetNumaNodes()); #pragma omp parallel { #pragma omp critical { int tid = omp_get_thread_num(); auto nid = numa_node_of_cpu(sched_getcpu()); // check if mappting openmp thread id to numa node is correct EXPECT_EQ(nid, ti.GetNumaNode(tid)); auto numa_thread_id = ti.GetNumaThreadId(tid); // numa thread id must be smaller than the max number of threads for this // numa node. EXPECT_LT(numa_thread_id, ti.GetThreadsInNumaNode(nid)); std::set<int>& numa_thread_ids = all_numa_thread_ids[nid]; // check if this numa_thread id has not been used before EXPECT_TRUE(numa_thread_ids.find(numa_thread_id) == numa_thread_ids.end()); numa_thread_ids.insert(numa_thread_id); threads_per_numa[nid]++; } } for (uint16_t n = 0; n < ti.GetNumaNodes(); n++) { EXPECT_EQ(threads_per_numa[n], ti.GetThreadsInNumaNode(n)); } } TEST(ThreadInfoTest, All) { auto* ti = ThreadInfo::GetInstance(); RunAllChecks(*ti); } TEST(ThreadInfoTest, ThreadCPUBinding) { auto* ti = ThreadInfo::GetInstance(); RunAllChecks(*ti); // do some work std::vector<int> v; v.resize(1e4); #pragma omp parallel for for (uint64_t i = 0; i < v.size(); i++) { v[i]++; } // check if thread info is still correct RunAllChecks(*ti); } TEST(ThreadInfoTest, Renew) { auto* ti = ThreadInfo::GetInstance(); RunAllChecks(*ti); // reduce number of threads to one auto omp_max_threads = omp_get_max_threads(); omp_set_num_threads(1); ThreadInfo::GetInstance()->Renew(); RunAllChecks(*ti); // Reset to previous condition omp_set_num_threads(omp_max_threads); ThreadInfo::GetInstance()->Renew(); } } // namespace bdm <|endoftext|>
<commit_before>// irview : simple viewer for adding false colour to IR or thermal images // / video / camera feed // usage: prog {image/video file} // Author : Toby Breckon, [email protected] // Copyright (c) 2008 School of Engineering, Cranfield University // Copyright (c) 2017 School of Engineering and Computing Sciences, Durham University // Copyright (c) 2019 Dept. Computer Science, Durham University // License : GPL - http://www.gnu.org/licenses/gpl.html /******************************************************************************/ #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> // standard C++ I/O #include <string> // standard C++ I/O #include <algorithm> // includes max() using namespace cv; // OpenCV API is in the C++ "cv" namespace using namespace std; /******************************************************************************/ // setup the camera index properly based on OS platform // 0 in linux gives first camera for v4l //-1 in windows gives first device or user dialog selection #ifdef linux #define CAMERA_INDEX 0 #else #define CAMERA_INDEX -1 #endif /******************************************************************************/ #define PROG_ID_STRING "IrView v0.3 - (c) Toby Breckon, 2008-2019+" #define LICENSE_STRING "GPL - http://www.gnu.org/licenses/gpl.html" static void print_help(char **name){ printf("\n%s\n", PROG_ID_STRING); printf ("\t with OpenCV version %s (%d.%d.%d)\n", CV_VERSION, CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION); printf("%s\n\n", LICENSE_STRING); printf("Usage :%s [image/video file]\n", name[0]); printf("Camera interface: run with no file agrument for direct camera use\n"); printf("\nKeyboard commands\n"); printf("\t a - automatic scaling (default: on)\n"); printf("\t b - show both false colour and original (default: off)\n"); printf("\t c - toggle false colour (default: on)\n"); printf("\t e - exit (as per x or ESC)\n"); printf("\t f - toggle full screen (default: off)\n"); printf("\t x - exit\n\n"); } /******************************************************************************/ // concatenate 2 OpenCV Mat Objects side-by-side (in general) Mat concatImages(Mat img1, Mat img2) { Mat out = Mat(img1.rows, img1.cols + img2.cols, img1.type()); Mat roi = out(Rect(0, 0, img1.cols, img1.rows)); Mat roi2 = out(Rect(img1.cols, 0, img2.cols, img2.rows)); img1.copyTo(roi); // depth of img1 is master, depth of img2 is slave // so convert if needed if (img1.depth() != img2.depth()) { // e.g. if img2 is 8-bit and img1 32-bit - scale to range 0->1 (32-bit) // otherwise img2 is 32-bit and img1 is 8-bit - scale to 0->255 (8-bit) img2.convertTo(roi2, img1.depth(), (img2.depth() < img1.depth()) ? 1.0 / 255.0 : 255); } else { img2.copyTo(roi2); } return out; } /******************************************************************************/ // set all mat values at given channel to given value // from: https://stackoverflow.com/questions/23510571/how-to-set-given-channel-of-a-cvmat-to-a-given-value-efficiently-without-chang/23518786 void setChannel(Mat &mat, int channel, unsigned char value) { // make sure have enough channels if (mat.channels() < channel+1) return; // check mat is continuous or not if (mat.isContinuous()) mat.reshape(1, mat.rows*mat.cols).col(channel).setTo(Scalar(value)); else{ for (int i = 0; i < mat.rows; i++) mat.row(i).reshape(1, mat.cols).col(channel).setTo(Scalar(value)); } } /******************************************************************************/ int main( int argc, char** argv ) { Mat img; // image object VideoCapture capture; // capture object const char* windowNameHSV = PROG_ID_STRING; // window name Mat HSV; // HSV image Mat singleChannelH; // Hue plain (from input image) Mat singleChannelPlain; // constant plane for S & V bool keepProcessing = true; // loop control flag unsigned char key; // user input int EVENT_LOOP_DELAY = 40; // 40ms equates to 1000ms/25fps = // 40ms per frame bool useFalseColour = true; // process flag - false colour bool useNormalisation = true; // process flag - normalisation bool useConcatImage = false; // process flag - show concatenated images bool useFullScreen = false; // process flag - run full screen // if command line arguments are provided try to read image/video_name // otherwise default to capture from attached H/W camera if( ( argc == 2 && (!(img = imread( argv[1], IMREAD_COLOR)).empty()))|| ( argc == 2 && (capture.open(argv[1]) == true )) || ( argc != 2 && (capture.open(CAMERA_INDEX) == true)) ) { // print help print_help(argv); // create window object (use flag=0 to allow resize, 1 to auto fix size) namedWindow(windowNameHSV, WINDOW_NORMAL); if (capture.isOpened()) { // if capture object in use (i.e. video/camera) // get initial image from capture object capture >> img; if(img.empty()){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } resizeWindow(windowNameHSV, img.cols, img.rows); // setup output image in HSV HSV = img.clone(); // set channels up for Saturation / Variance Mat HSV_channels[3]; // start main loop while (keepProcessing) { // if capture object in use (i.e. video/camera) // get image from capture object if (capture.isOpened()) { // if capture object in use (i.e. video/camera) // get initial image from capture object capture >> img; if(img.empty()){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } // extract H, S and V channels split(img,HSV_channels); // do colour normalisation (makes it look more impressive) if (useNormalisation){ normalize(HSV_channels[0], HSV_channels[0], 0, 255, NORM_MINMAX); normalize(HSV_channels[2], HSV_channels[2], 0, 255, NORM_MINMAX); } // set S channel to max values setChannel(HSV_channels[1], 0, 255); // do scaling to avoid Hue space wrap around (i.e. dark == bright!) // N.B. changing the scaling factor and addition will vary the colour // effect - OpenCV 8-bit Hue in range 0->120 => 0.5 * Hue + 90 maps // all values to (wrap-around) 180->60 range in Hue. HSV_channels[0].convertTo(HSV_channels[0], -1 , 0.5, 90); merge(HSV_channels, 3, HSV); // put it all back together in RGB cvtColor(HSV, HSV, COLOR_HSV2BGR); // display image in window if (useConcatImage){ imshow(windowNameHSV, concatImages(img, HSV)); } else { if (useFalseColour){ imshow(windowNameHSV, HSV); } else { imshow(windowNameHSV, img); } } // start event processing loop key = waitKey(EVENT_LOOP_DELAY); // process any keyboard input switch (tolower(key)) { case 'x': case 'e': case char(27): // ESC key // if user presses "x" then exit keepProcessing = false; ; break; case 'a': // toggle automatic scaling useNormalisation = (!useNormalisation); ; break; case 'b': // toggle concatenated images useConcatImage = (!useConcatImage); ; break; case 'c': // toggle false colour useFalseColour = (!useFalseColour); ; break; case 'f': // toggle false colour useFullScreen = (!useFullScreen); // set or unset the CV_WINDOW_FULLSCREEN flag via logical AND with toggle boolean setWindowProperty(windowNameHSV, WND_PROP_FULLSCREEN, (WINDOW_FULLSCREEN & useFullScreen)); ; break; } } // all OK : main returns 0 return 0; } // not OK : main returns -1 print_help(argv); return -1; } /******************************************************************************/ <commit_msg>remove unused Mat objects<commit_after>// irview : simple viewer for adding false colour to IR or thermal images // / video / camera feed // usage: prog {image/video file} // Author : Toby Breckon, [email protected] // Copyright (c) 2008 School of Engineering, Cranfield University // Copyright (c) 2017 School of Engineering and Computing Sciences, Durham University // Copyright (c) 2019 Dept. Computer Science, Durham University // License : GPL - http://www.gnu.org/licenses/gpl.html /******************************************************************************/ #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> // standard C++ I/O #include <string> // standard C++ I/O #include <algorithm> // includes max() using namespace cv; // OpenCV API is in the C++ "cv" namespace using namespace std; /******************************************************************************/ // setup the camera index properly based on OS platform // 0 in linux gives first camera for v4l //-1 in windows gives first device or user dialog selection #ifdef linux #define CAMERA_INDEX 0 #else #define CAMERA_INDEX -1 #endif /******************************************************************************/ #define PROG_ID_STRING "IrView v0.3 - (c) Toby Breckon, 2008-2019+" #define LICENSE_STRING "GPL - http://www.gnu.org/licenses/gpl.html" static void print_help(char **name){ printf("\n%s\n", PROG_ID_STRING); printf ("\t with OpenCV version %s (%d.%d.%d)\n", CV_VERSION, CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION); printf("%s\n\n", LICENSE_STRING); printf("Usage :%s [image/video file]\n", name[0]); printf("Camera interface: run with no file agrument for direct camera use\n"); printf("\nKeyboard commands\n"); printf("\t a - automatic scaling (default: on)\n"); printf("\t b - show both false colour and original (default: off)\n"); printf("\t c - toggle false colour (default: on)\n"); printf("\t e - exit (as per x or ESC)\n"); printf("\t f - toggle full screen (default: off)\n"); printf("\t x - exit\n\n"); } /******************************************************************************/ // concatenate 2 OpenCV Mat Objects side-by-side (in general) Mat concatImages(Mat img1, Mat img2) { Mat out = Mat(img1.rows, img1.cols + img2.cols, img1.type()); Mat roi = out(Rect(0, 0, img1.cols, img1.rows)); Mat roi2 = out(Rect(img1.cols, 0, img2.cols, img2.rows)); img1.copyTo(roi); // depth of img1 is master, depth of img2 is slave // so convert if needed if (img1.depth() != img2.depth()) { // e.g. if img2 is 8-bit and img1 32-bit - scale to range 0->1 (32-bit) // otherwise img2 is 32-bit and img1 is 8-bit - scale to 0->255 (8-bit) img2.convertTo(roi2, img1.depth(), (img2.depth() < img1.depth()) ? 1.0 / 255.0 : 255); } else { img2.copyTo(roi2); } return out; } /******************************************************************************/ // set all mat values at given channel to given value // from: https://stackoverflow.com/questions/23510571/how-to-set-given-channel-of-a-cvmat-to-a-given-value-efficiently-without-chang/23518786 void setChannel(Mat &mat, int channel, unsigned char value) { // make sure have enough channels if (mat.channels() < channel+1) return; // check mat is continuous or not if (mat.isContinuous()) mat.reshape(1, mat.rows*mat.cols).col(channel).setTo(Scalar(value)); else{ for (int i = 0; i < mat.rows; i++) mat.row(i).reshape(1, mat.cols).col(channel).setTo(Scalar(value)); } } /******************************************************************************/ int main( int argc, char** argv ) { Mat img; // image object VideoCapture capture; // capture object const char* windowNameHSV = PROG_ID_STRING; // window name Mat HSV; // HSV image bool keepProcessing = true; // loop control flag unsigned char key; // user input int EVENT_LOOP_DELAY = 40; // 40ms equates to 1000ms/25fps = // 40ms per frame bool useFalseColour = true; // process flag - false colour bool useNormalisation = true; // process flag - normalisation bool useConcatImage = false; // process flag - show concatenated images bool useFullScreen = false; // process flag - run full screen // if command line arguments are provided try to read image/video_name // otherwise default to capture from attached H/W camera if( ( argc == 2 && (!(img = imread( argv[1], IMREAD_COLOR)).empty()))|| ( argc == 2 && (capture.open(argv[1]) == true )) || ( argc != 2 && (capture.open(CAMERA_INDEX) == true)) ) { // print help print_help(argv); // create window object (use flag=0 to allow resize, 1 to auto fix size) namedWindow(windowNameHSV, WINDOW_NORMAL); if (capture.isOpened()) { // if capture object in use (i.e. video/camera) // get initial image from capture object capture >> img; if(img.empty()){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } resizeWindow(windowNameHSV, img.cols, img.rows); // setup output image in HSV HSV = img.clone(); // set channels up for Saturation / Variance Mat HSV_channels[3]; // start main loop while (keepProcessing) { // if capture object in use (i.e. video/camera) // get image from capture object if (capture.isOpened()) { // if capture object in use (i.e. video/camera) // get initial image from capture object capture >> img; if(img.empty()){ if (argc == 2){ printf("End of video file reached\n"); } else { printf("ERROR: cannot get next frame from camera\n"); } exit(0); } } // extract H, S and V channels split(img,HSV_channels); // do colour normalisation (makes it look more impressive) if (useNormalisation){ normalize(HSV_channels[0], HSV_channels[0], 0, 255, NORM_MINMAX); normalize(HSV_channels[2], HSV_channels[2], 0, 255, NORM_MINMAX); } // set S channel to max values setChannel(HSV_channels[1], 0, 255); // do scaling to avoid Hue space wrap around (i.e. dark == bright!) // N.B. changing the scaling factor and addition will vary the colour // effect - OpenCV 8-bit Hue in range 0->120 => 0.5 * Hue + 90 maps // all values to (wrap-around) 180->60 range in Hue. HSV_channels[0].convertTo(HSV_channels[0], -1 , 0.5, 90); merge(HSV_channels, 3, HSV); // put it all back together in RGB cvtColor(HSV, HSV, COLOR_HSV2BGR); // display image in window if (useConcatImage){ imshow(windowNameHSV, concatImages(img, HSV)); } else { if (useFalseColour){ imshow(windowNameHSV, HSV); } else { imshow(windowNameHSV, img); } } // start event processing loop key = waitKey(EVENT_LOOP_DELAY); // process any keyboard input switch (tolower(key)) { case 'x': case 'e': case char(27): // ESC key // if user presses "x" then exit keepProcessing = false; ; break; case 'a': // toggle automatic scaling useNormalisation = (!useNormalisation); ; break; case 'b': // toggle concatenated images useConcatImage = (!useConcatImage); ; break; case 'c': // toggle false colour useFalseColour = (!useFalseColour); ; break; case 'f': // toggle false colour useFullScreen = (!useFullScreen); // set or unset the CV_WINDOW_FULLSCREEN flag via logical AND with toggle boolean setWindowProperty(windowNameHSV, WND_PROP_FULLSCREEN, (WINDOW_FULLSCREEN & useFullScreen)); ; break; } } // all OK : main returns 0 return 0; } // not OK : main returns -1 print_help(argv); return -1; } /******************************************************************************/ <|endoftext|>
<commit_before>#include <async.h> #include <dbfe.h> #include <rxx.h> #define USENET_PORT 11999 // xxx dbfe *group_db, *article_db; // in group_db, each key is a group name. each record contains messageIDs // in article_db, each key is a messageID. each record is an article void timemark(str foo) { struct timeval tv; gettimeofday(&tv, NULL); warn << foo << " " << tv.tv_sec << " " << tv.tv_usec << "\n"; } struct grouplist { ptr<dbEnumeration> it; ptr<dbPair> d; grouplist (); void next (str *, int *); bool more (void) { return d; }; }; grouplist::grouplist () { it = group_db->enumerate(); d = it->nextElement(); }; static rxx listrx ("^(<.+?>)"); void grouplist::next (str *f, int *i) { ptr<dbrec> data = group_db->lookup (d->key); char *c = data->value; int len = data->len, cnt = 0; for (; listrx.search (str (c, len)) ; c += listrx.len (1), len -= listrx.len (1) ) cnt++; *f = str (d->key->value, d->key->len); *i = cnt; d = it->nextElement(); } struct group { ptr<dbrec> rec; // int cur_art; int start, stop; char *c; int len; group () : rec (0) {}; int open (str); str name (void); void xover (int, int); strbuf next (void); bool more (void) { return start <= stop; }; }; int group::open (str g) { rec = group_db->lookup(New refcounted<dbrec> (g, g.len ())); if (rec == NULL) return -1; char *c = rec->value; int len = rec->len, i = 0; for (; listrx.search (str (c, len)) ; c += listrx.len (1), len -= listrx.len (1) ) i++; return i; } str group::name (void) { if (rec) return str (rec->value, rec->len); return str (); } void group::xover (int a, int b) { start = a; stop = b; // xxx b == -1 c = rec->value; len = rec->len; } strbuf group::next (void) { ptr<dbrec> art; strbuf foo; foo << start << "\t"; if (more () && listrx.search (str (c, len))) { art = article_db->lookup(New refcounted<dbrec> (listrx[1], listrx[1].len ())); if (art == NULL) warn << "missing article\n"; else foo << str (art->value, art->len); // xxx c += listrx.len (1); len -= listrx.len (1); start++; } foo << "\t\r\n"; return foo; } char *hello = "200 DHash news server - posting allowed\r\n"; char *unknown = "500 command not recognized\r\n"; char *listb = "215 list of newsgroups follows\r\n"; char *period = ".\r\n"; char *groupb = "211 "; char *groupe = " group selected\r\n"; char *badgroup = "411 no such news group\r\n"; char *nogroup = "412 No news group current selected\r\n"; char *syntax = "501 command syntax error\r\n"; char *overview = "224 Overview information follows\r\n"; struct nntp; typedef struct c_jmp_entry { char *cmd; int len; cbs fn; c_jmp_entry (char *_cmd, cbs _fn) : cmd (_cmd), fn (_fn) { len = strlen (cmd); }; } c_jmp_entry_t; struct nntp { int s; suio out; group cur_group; nntp (int _s); ~nntp (); void command (void); void output (void); void cmd_hello (str); void cmd_list (str); void cmd_group (str); void cmd_over (str); void cmd_article (str); void cmd_quit (str); vec<c_jmp_entry_t> cmd_table; }; nntp::nntp (int _s) : s (_s) { warn << "connect " << s << "\n"; fdcb (s, selread, wrap (this, &nntp::command)); cmd_hello("\n"); cmd_table.push_back ( c_jmp_entry_t ("ARTICLE", wrap (this, &nntp::cmd_article)) ); cmd_table.push_back ( c_jmp_entry_t ("XOVER", wrap (this, &nntp::cmd_over)) ); cmd_table.push_back ( c_jmp_entry_t ("GROUP", wrap (this, &nntp::cmd_group)) ); cmd_table.push_back ( c_jmp_entry_t ("LIST", wrap (this, &nntp::cmd_list)) ); cmd_table.push_back ( c_jmp_entry_t ("MODE READER", wrap (this, &nntp::cmd_hello)) ); cmd_table.push_back ( c_jmp_entry_t ("QUIT", wrap (this, &nntp::cmd_quit)) ); // cmd_table.push_back ( c_jmp_entry_t ("", wrap (this, &nntp::cmd_quit)) ); // timemark("done"); } nntp::~nntp (void) { fdcb (s, selread, NULL); fdcb (s, selwrite, NULL); close (s); } void nntp::output (void) { int res; char *buf = (char *) malloc (out.resid () + 1); out.copyout (buf, out.resid ()); buf[out.resid ()] = 0; warn << buf; free (buf); res = out.output (s); // xxx check res if (out.resid () == 0) fdcb (s, selwrite, NULL); } void nntp::command (void) { suio in; int res; // timemark("cmd"); res = in.input (s); if (res <= 0) fdcb (s, selread, NULL); str cmd (in); for (unsigned int i = 0; i < cmd_table.size(); i++) { if (!strncmp (cmd, cmd_table[i].cmd, cmd_table[i].len)) { cmd_table[i].fn (cmd); return; } } warn << "unknown command: " << cmd; out.print (unknown, strlen (unknown)); fdcb (s, selwrite, wrap (this, &nntp::output)); } void nntp::cmd_hello (str c) { warn << "hello: " << c; out.print (hello, strlen (hello)); fdcb (s, selwrite, wrap (this, &nntp::output)); } void nntp::cmd_list (str c) { warn << "list\n"; out.print (listb, strlen (listb)); // foo 2 1 y\r\n grouplist g; str n; int i; strbuf foo; do { g.next (&n, &i); out.print (n, n.len ()); foo << " " << i << " 1 y\r\n"; out.take (foo.tosuio ()); } while (g.more ()); out.print (period, strlen (period)); fdcb (s, selwrite, wrap (this, &nntp::output)); } static rxx overrx ("^XOVER ?(\\d+)?(-)?(\\d+)?"); void nntp::cmd_over (str c) { warn << "over " << c; if (cur_group.name ().len () == 0) { out.print (nogroup, strlen (nogroup)); } else if (overrx.search (c)) { if (overrx[3]) { // range cur_group.xover (atoi (overrx[1]), atoi (overrx[3])); } else if (overrx[2]) { // endless } else if (overrx[1]) { // single } else { // current } out.print (overview, strlen (overview)); do { out.take (cur_group.next ().tosuio ()); out.print (period, strlen (period)); } while(cur_group.more ()); } else { // xxx er warn << "ror\n"; } fdcb (s, selwrite, wrap (this, &nntp::output)); } static rxx grouprx ("^GROUP (.+)\r\n", "m"); void nntp::cmd_group (str c) { warn << "group " << c; strbuf foo; int i; if (grouprx.search (c)) { if ((i = cur_group.open (grouprx[1])) < 0) { out.print (badgroup, strlen (badgroup)); } else { out.print (groupb, strlen (groupb)); foo << i << " 1 " << i << " "; out.take (foo.tosuio ()); out.print (cur_group.name (), cur_group.name ().len ()); out.print (groupe, strlen (groupe)); } } else out.print (syntax, strlen (syntax)); fdcb (s, selwrite, wrap (this, &nntp::output)); } void nntp::cmd_quit (str c) { warn << "quit\n"; delete this; } void tryaccept (int s) { int new_s; struct sockaddr *addr; unsigned int addrlen = sizeof (struct sockaddr_in); addr = (struct sockaddr *) calloc (1, addrlen); new_s = accept (s, addr, &addrlen); if (new_s > 0) { make_async (new_s); // timemark("new"); vNew nntp (new_s); } else perror (progname); free (addr); } void startlisten (void) { int s = inetsocket (SOCK_STREAM, USENET_PORT, INADDR_ANY); if (s > 0) { make_async (s); listen (s, 5); fdcb (s, selread, wrap (&tryaccept, s)); } } int main (int argc, char *argv[]) { setprogname (argv[0]); //set up the options we want dbOptions opts; opts.addOption ("opt_async", 1); opts.addOption ("opt_cachesize", 1000); opts.addOption ("opt_nodesize", 4096); group_db = New dbfe (); if (int err = group_db->opendb ("groups", opts)) { warn << "open returned: " << strerror (err) << "\n"; exit (-1); } article_db = New dbfe (); if (int err = article_db->opendb ("articles", opts)) { warn << "open returned: " << strerror (err) << "\n"; exit (-1); } // construct dummy group ref<dbrec> d = New refcounted<dbrec> ("<dd>", 4); ref<dbrec> k = New refcounted<dbrec> ("foo", 3); group_db->insert(k, d); // construct a dummy message k = New refcounted<dbrec> ("<dd>", 4); char *foomsg = "foosub\tfooauth\tfoodate\t<dd>\tfooref\t10000\t100"; d = New refcounted<dbrec> (foomsg, strlen (foomsg)); article_db->insert(k, d); startlisten (); amain (); return 0; } <commit_msg>no comment<commit_after>#include <async.h> #include <dbfe.h> #include <rxx.h> #define USENET_PORT 11999 // xxx dbfe *group_db, *article_db; // in group_db, each key is a group name. each record contains messageIDs // in article_db, each key is a messageID. each record is an article void timemark(str foo) { struct timeval tv; gettimeofday(&tv, NULL); warn << foo << " " << tv.tv_sec << " " << tv.tv_usec << "\n"; } struct grouplist { ptr<dbEnumeration> it; ptr<dbPair> d; grouplist (); void next (str *, int *); bool more (void) { return d; }; }; grouplist::grouplist () { it = group_db->enumerate(); d = it->nextElement(); }; static rxx listrx ("^(<.+?>)"); void grouplist::next (str *f, int *i) { ptr<dbrec> data = group_db->lookup (d->key); char *c = data->value; int len = data->len, cnt = 0; for (; listrx.search (str (c, len)) ; c += listrx.len (1), len -= listrx.len (1) ) cnt++; *f = str (d->key->value, d->key->len); *i = cnt; d = it->nextElement(); } struct group { ptr<dbrec> rec; // int cur_art; int start, stop; char *c; int len; group () : rec (0) {}; int open (str); str name (void); void xover (int, int); strbuf next (void); bool more (void) { return start <= stop; }; }; int group::open (str g) { rec = group_db->lookup(New refcounted<dbrec> (g, g.len ())); if (rec == NULL) return -1; char *c = rec->value; int len = rec->len, i = 0; for (; listrx.search (str (c, len)) ; c += listrx.len (1), len -= listrx.len (1) ) i++; return i; } str group::name (void) { if (rec) return str (rec->value, rec->len); return str (); } void group::xover (int a, int b) { start = a; stop = b; // xxx b == -1 c = rec->value; len = rec->len; } strbuf group::next (void) { ptr<dbrec> art; strbuf foo; foo << start << "\t"; if (more () && listrx.search (str (c, len))) { art = article_db->lookup(New refcounted<dbrec> (listrx[1], listrx[1].len ())); if (art == NULL) warn << "missing article\n"; else foo << str (art->value, art->len); // xxx c += listrx.len (1); len -= listrx.len (1); start++; } foo << "\t\r\n"; return foo; } char *hello = "200 DHash news server - posting allowed\r\n"; char *unknown = "500 command not recognized\r\n"; char *listb = "215 list of newsgroups follows\r\n"; char *period = ".\r\n"; char *groupb = "211 "; char *groupe = " group selected\r\n"; char *badgroup = "411 no such news group\r\n"; char *nogroup = "412 No news group current selected\r\n"; char *syntax = "501 command syntax error\r\n"; char *overview = "224 Overview information follows\r\n"; struct nntp; typedef struct c_jmp_entry { char *cmd; int len; cbs fn; c_jmp_entry (char *_cmd, cbs _fn) : cmd (_cmd), fn (_fn) { len = strlen (cmd); }; } c_jmp_entry_t; struct nntp { int s; suio out; group cur_group; nntp (int _s); ~nntp (); void command (void); void output (void); void cmd_hello (str); void cmd_list (str); void cmd_group (str); void cmd_over (str); void cmd_article (str); void cmd_quit (str); vec<c_jmp_entry_t> cmd_table; }; nntp::nntp (int _s) : s (_s) { warn << "connect " << s << "\n"; fdcb (s, selread, wrap (this, &nntp::command)); cmd_hello("\n"); cmd_table.push_back ( c_jmp_entry_t ("ARTICLE", wrap (this, &nntp::cmd_article)) ); cmd_table.push_back ( c_jmp_entry_t ("XOVER", wrap (this, &nntp::cmd_over)) ); cmd_table.push_back ( c_jmp_entry_t ("GROUP", wrap (this, &nntp::cmd_group)) ); cmd_table.push_back ( c_jmp_entry_t ("LIST", wrap (this, &nntp::cmd_list)) ); cmd_table.push_back ( c_jmp_entry_t ("MODE READER", wrap (this, &nntp::cmd_hello)) ); cmd_table.push_back ( c_jmp_entry_t ("QUIT", wrap (this, &nntp::cmd_quit)) ); // cmd_table.push_back ( c_jmp_entry_t ("", wrap (this, &nntp::cmd_quit)) ); // timemark("done"); } nntp::~nntp (void) { fdcb (s, selread, NULL); fdcb (s, selwrite, NULL); close (s); } void nntp::output (void) { int res; char *buf = (char *) malloc (out.resid () + 1); out.copyout (buf, out.resid ()); buf[out.resid ()] = 0; warn << buf; free (buf); res = out.output (s); // xxx check res if (out.resid () == 0) fdcb (s, selwrite, NULL); } void nntp::command (void) { suio in; int res; // timemark("cmd"); res = in.input (s); if (res <= 0) fdcb (s, selread, NULL); str cmd (in); for (unsigned int i = 0; i < cmd_table.size(); i++) { if (!strncmp (cmd, cmd_table[i].cmd, cmd_table[i].len)) { cmd_table[i].fn (cmd); return; } } warn << "unknown command: " << cmd; out.print (unknown, strlen (unknown)); fdcb (s, selwrite, wrap (this, &nntp::output)); } void nntp::cmd_hello (str c) { warn << "hello: " << c; out.print (hello, strlen (hello)); fdcb (s, selwrite, wrap (this, &nntp::output)); } void nntp::cmd_list (str c) { warn << "list\n"; out.print (listb, strlen (listb)); // foo 2 1 y\r\n grouplist g; str n; int i; strbuf foo; do { g.next (&n, &i); out.print (n, n.len ()); foo << " " << i << " 1 y\r\n"; out.take (foo.tosuio ()); } while (g.more ()); out.print (period, strlen (period)); fdcb (s, selwrite, wrap (this, &nntp::output)); } static rxx overrx ("^XOVER ?(\\d+)?(-)?(\\d+)?"); void nntp::cmd_over (str c) { warn << "over " << c; if (cur_group.name ().len () == 0) { out.print (nogroup, strlen (nogroup)); } else if (overrx.search (c)) { if (overrx[3]) { // range cur_group.xover (atoi (overrx[1]), atoi (overrx[3])); } else if (overrx[2]) { // endless } else if (overrx[1]) { // single } else { // current } out.print (overview, strlen (overview)); do { out.take (cur_group.next ().tosuio ()); out.print (period, strlen (period)); } while(cur_group.more ()); } else { // xxx er warn << "ror\n"; } fdcb (s, selwrite, wrap (this, &nntp::output)); } static rxx grouprx ("^GROUP (.+)\r\n", "m"); void nntp::cmd_group (str c) { warn << "group " << c; strbuf foo; int i; if (grouprx.search (c)) { if ((i = cur_group.open (grouprx[1])) < 0) { out.print (badgroup, strlen (badgroup)); } else { out.print (groupb, strlen (groupb)); foo << i << " 1 " << i << " "; out.take (foo.tosuio ()); out.print (cur_group.name (), cur_group.name ().len ()); out.print (groupe, strlen (groupe)); } } else out.print (syntax, strlen (syntax)); fdcb (s, selwrite, wrap (this, &nntp::output)); } void nntp::cmd_article (str c) { } void nntp::cmd_quit (str c) { warn << "quit\n"; delete this; } void tryaccept (int s) { int new_s; struct sockaddr *addr; unsigned int addrlen = sizeof (struct sockaddr_in); addr = (struct sockaddr *) calloc (1, addrlen); new_s = accept (s, addr, &addrlen); if (new_s > 0) { make_async (new_s); // timemark("new"); vNew nntp (new_s); } else perror (progname); free (addr); } void startlisten (void) { int s = inetsocket (SOCK_STREAM, USENET_PORT, INADDR_ANY); if (s > 0) { make_async (s); listen (s, 5); fdcb (s, selread, wrap (&tryaccept, s)); } } int main (int argc, char *argv[]) { setprogname (argv[0]); //set up the options we want dbOptions opts; opts.addOption ("opt_async", 1); opts.addOption ("opt_cachesize", 1000); opts.addOption ("opt_nodesize", 4096); group_db = New dbfe (); if (int err = group_db->opendb ("groups", opts)) { warn << "open returned: " << strerror (err) << "\n"; exit (-1); } article_db = New dbfe (); if (int err = article_db->opendb ("articles", opts)) { warn << "open returned: " << strerror (err) << "\n"; exit (-1); } // construct dummy group ref<dbrec> d = New refcounted<dbrec> ("<dd>", 4); ref<dbrec> k = New refcounted<dbrec> ("foo", 3); group_db->insert(k, d); // construct a dummy message k = New refcounted<dbrec> ("<dd>", 4); char *foomsg = "foosub\tfooauth\tfoodate\t<dd>\tfooref\t10000\t100"; d = New refcounted<dbrec> (foomsg, strlen (foomsg)); article_db->insert(k, d); startlisten (); amain (); return 0; } <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PARAMETER_FIXTURES_HPP_ #define PARAMETER_FIXTURES_HPP_ #include <iostream> #include <stdexcept> #include <string> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" const double test_epsilon = 1e-6; void set_test_parameters( std::shared_ptr<rclcpp::parameter_client::SyncParametersClient> parameters_client) { // Set several differnet types of parameters. auto set_parameters_results = parameters_client->set_parameters({ rclcpp::parameter::ParameterVariant("foo", 2), rclcpp::parameter::ParameterVariant("bar", "hello"), rclcpp::parameter::ParameterVariant("barstr", std::string("hello_str")), rclcpp::parameter::ParameterVariant("baz", 1.45), rclcpp::parameter::ParameterVariant("foo.first", 8), rclcpp::parameter::ParameterVariant("foo.second", 42), rclcpp::parameter::ParameterVariant("foobar", true), }); // Check to see if they were set. for (auto & result : set_parameters_results) { ASSERT_TRUE(result.successful); } } void verify_set_parameters_async( std::shared_ptr<rclcpp::Node> node, std::shared_ptr<rclcpp::parameter_client::AsyncParametersClient> parameters_client) { // Set several differnet types of parameters. auto set_parameters_results = parameters_client->set_parameters({ rclcpp::parameter::ParameterVariant("foo", 2), rclcpp::parameter::ParameterVariant("bar", "hello"), rclcpp::parameter::ParameterVariant("barstr", std::string("hello_str")), rclcpp::parameter::ParameterVariant("baz", 1.45), rclcpp::parameter::ParameterVariant("foo.first", 8), rclcpp::parameter::ParameterVariant("foo.second", 42), rclcpp::parameter::ParameterVariant("foobar", true), }); rclcpp::spin_until_future_complete(node, set_parameters_results); // Wait for the results. // Check to see if they were set. for (auto & result : set_parameters_results.get()) { ASSERT_TRUE(result.successful); } } void verify_test_parameters( std::shared_ptr<rclcpp::parameter_client::SyncParametersClient> parameters_client) { auto parameters_and_prefixes = parameters_client->list_parameters({"foo", "bar"}, 0); for (auto & name : parameters_and_prefixes.names) { EXPECT_TRUE(name == "foo" || name == "bar"); } for (auto & prefix : parameters_and_prefixes.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Test different depth auto parameters_and_prefixes4 = parameters_client->list_parameters({"foo"}, 1); for (auto & name : parameters_and_prefixes4.names) { EXPECT_TRUE(name == "foo" || name == "foo.first" || name == "foo.second"); } for (auto & prefix : parameters_and_prefixes4.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Get a few of the parameters just set. for (auto & parameter : parameters_client->get_parameters({"foo", "bar", "baz"})) { // std::cout << "Parameter is:" << std::endl << parameter.to_yaml() << std::endl; if (parameter.get_name() == "foo") { EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"2\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("integer", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "bar") { EXPECT_STREQ( "{\"name\": \"bar\", \"type\": \"string\", \"value\": \"hello\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("string", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "baz") { EXPECT_STREQ("double", parameter.get_type_name().c_str()); EXPECT_NEAR(1.45, parameter.as_double(), test_epsilon); } else { ASSERT_FALSE("you should never hit this"); } } // Get a few non existant parameters for (auto & parameter : parameters_client->get_parameters({"not_foo", "not_baz"})) { EXPECT_STREQ("There should be no matches", parameter.get_name().c_str()); } } void verify_get_parameters_async( std::shared_ptr<rclcpp::Node> node, std::shared_ptr<rclcpp::parameter_client::AsyncParametersClient> parameters_client) { auto result = parameters_client->list_parameters({"foo", "bar"}, 0); rclcpp::spin_until_future_complete(node, result); auto parameters_and_prefixes = result.get(); for (auto & name : parameters_and_prefixes.names) { EXPECT_TRUE(name == "foo" || name == "bar"); } for (auto & prefix : parameters_and_prefixes.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Test different depth auto result4 = parameters_client->list_parameters({"foo"}, 1); rclcpp::spin_until_future_complete(node, result4); auto parameters_and_prefixes4 = result4.get(); for (auto & name : parameters_and_prefixes4.names) { EXPECT_TRUE(name == "foo" || name == "foo.first" || name == "foo.second"); } for (auto & prefix : parameters_and_prefixes4.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Get a few of the parameters just set. auto result2 = parameters_client->get_parameters({"foo", "bar", "baz"}); rclcpp::spin_until_future_complete(node, result2); for (auto & parameter : result2.get()) { if (parameter.get_name() == "foo") { EXPECT_STREQ("foo", parameter.get_name().c_str()); EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"2\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("integer", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "bar") { EXPECT_STREQ( "{\"name\": \"bar\", \"type\": \"string\", \"value\": \"hello\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("string", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "baz") { EXPECT_STREQ("double", parameter.get_type_name().c_str()); EXPECT_NEAR(1.45, parameter.as_double(), test_epsilon); } else { ASSERT_FALSE("you should never hit this"); } } // Get a few non existant parameters auto result3 = parameters_client->get_parameters({"not_foo", "not_baz"}); rclcpp::spin_until_future_complete(node, result3); for (auto & parameter : result3.get()) { EXPECT_STREQ("There should be no matches", parameter.get_name().c_str()); } } #endif // PARAMETER_FIXTURES_HPP_ <commit_msg>Update tests for changes in parameter handling (#140)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PARAMETER_FIXTURES_HPP_ #define PARAMETER_FIXTURES_HPP_ #include <iostream> #include <stdexcept> #include <string> #include <vector> #include "gtest/gtest.h" #include "rcl_interfaces/srv/list_parameters.hpp" #include "rclcpp/rclcpp.hpp" const double test_epsilon = 1e-6; void set_test_parameters( std::shared_ptr<rclcpp::parameter_client::SyncParametersClient> parameters_client) { // Set several differnet types of parameters. auto set_parameters_results = parameters_client->set_parameters({ rclcpp::parameter::ParameterVariant("foo", 2), rclcpp::parameter::ParameterVariant("bar", "hello"), rclcpp::parameter::ParameterVariant("barstr", std::string("hello_str")), rclcpp::parameter::ParameterVariant("baz", 1.45), rclcpp::parameter::ParameterVariant("foo.first", 8), rclcpp::parameter::ParameterVariant("foo.second", 42), rclcpp::parameter::ParameterVariant("foobar", true), }); // Check to see if they were set. for (auto & result : set_parameters_results) { ASSERT_TRUE(result.successful); } } void verify_set_parameters_async( std::shared_ptr<rclcpp::Node> node, std::shared_ptr<rclcpp::parameter_client::AsyncParametersClient> parameters_client) { // Set several differnet types of parameters. auto set_parameters_results = parameters_client->set_parameters({ rclcpp::parameter::ParameterVariant("foo", 2), rclcpp::parameter::ParameterVariant("bar", "hello"), rclcpp::parameter::ParameterVariant("barstr", std::string("hello_str")), rclcpp::parameter::ParameterVariant("baz", 1.45), rclcpp::parameter::ParameterVariant("foo.first", 8), rclcpp::parameter::ParameterVariant("foo.second", 42), rclcpp::parameter::ParameterVariant("foobar", true), }); rclcpp::spin_until_future_complete(node, set_parameters_results); // Wait for the results. // Check to see if they were set. for (auto & result : set_parameters_results.get()) { ASSERT_TRUE(result.successful); } } void verify_test_parameters( std::shared_ptr<rclcpp::parameter_client::SyncParametersClient> parameters_client) { // Test recursive depth (=0) auto parameters_and_prefixes = parameters_client->list_parameters({"foo", "bar"}, rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE); for (auto & name : parameters_and_prefixes.names) { EXPECT_TRUE(name == "foo" || name == "bar" || name == "foo.first" || name == "foo.second"); } for (auto & prefix : parameters_and_prefixes.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Test different depth auto parameters_and_prefixes4 = parameters_client->list_parameters({"foo"}, 1); for (auto & name : parameters_and_prefixes4.names) { EXPECT_EQ(name, "foo"); } for (auto & prefix : parameters_and_prefixes4.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Test different depth auto parameters_and_prefixes5 = parameters_client->list_parameters({"foo"}, 2); for (auto & name : parameters_and_prefixes5.names) { EXPECT_TRUE(name == "foo" || name == "foo.first" || name == "foo.second"); } for (auto & prefix : parameters_and_prefixes5.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Get a few of the parameters just set. for (auto & parameter : parameters_client->get_parameters({"foo", "bar", "baz"})) { // std::cout << "Parameter is:" << std::endl << parameter.to_yaml() << std::endl; if (parameter.get_name() == "foo") { EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"2\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("integer", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "bar") { EXPECT_STREQ( "{\"name\": \"bar\", \"type\": \"string\", \"value\": \"hello\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("string", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "baz") { EXPECT_STREQ("double", parameter.get_type_name().c_str()); EXPECT_NEAR(1.45, parameter.as_double(), test_epsilon); } else { ASSERT_FALSE("you should never hit this"); } } // Get a few non existant parameters for (auto & parameter : parameters_client->get_parameters({"not_foo", "not_baz"})) { EXPECT_STREQ("There should be no matches", parameter.get_name().c_str()); } // List all of the parameters, using an empty prefix list and depth=0 parameters_and_prefixes = parameters_client->list_parameters({}, rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE); std::vector<std::string> all_names = { "foo", "bar", "barstr", "baz", "foo.first", "foo.second", "foobar" }; EXPECT_EQ(parameters_and_prefixes.names.size(), all_names.size()); for (auto & name : all_names) { EXPECT_NE(std::find( parameters_and_prefixes.names.cbegin(), parameters_and_prefixes.names.cend(), name), parameters_and_prefixes.names.cend()); } // List all of the parameters, using an empty prefix list and large depth parameters_and_prefixes = parameters_client->list_parameters({}, 100); EXPECT_EQ(parameters_and_prefixes.names.size(), all_names.size()); for (auto & name : all_names) { EXPECT_NE(std::find( parameters_and_prefixes.names.cbegin(), parameters_and_prefixes.names.cend(), name), parameters_and_prefixes.names.cend()); } // List most of the parameters, using an empty prefix list and depth=1 parameters_and_prefixes = parameters_client->list_parameters({}, 1); std::vector<std::string> depth_one_names = { "foo", "bar", "barstr", "baz", "foobar" }; EXPECT_EQ(parameters_and_prefixes.names.size(), depth_one_names.size()); for (auto & name : depth_one_names) { EXPECT_NE(std::find( parameters_and_prefixes.names.cbegin(), parameters_and_prefixes.names.cend(), name), parameters_and_prefixes.names.cend()); } } void verify_get_parameters_async( std::shared_ptr<rclcpp::Node> node, std::shared_ptr<rclcpp::parameter_client::AsyncParametersClient> parameters_client) { // Test recursive depth (=0) auto result = parameters_client->list_parameters({"foo", "bar"}, rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE); rclcpp::spin_until_future_complete(node, result); auto parameters_and_prefixes = result.get(); for (auto & name : parameters_and_prefixes.names) { EXPECT_TRUE(name == "foo" || name == "bar" || name == "foo.first" || name == "foo.second"); } for (auto & prefix : parameters_and_prefixes.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Test different depth auto result4 = parameters_client->list_parameters({"foo"}, 1); rclcpp::spin_until_future_complete(node, result4); auto parameters_and_prefixes4 = result4.get(); for (auto & name : parameters_and_prefixes4.names) { EXPECT_EQ(name, "foo"); } for (auto & prefix : parameters_and_prefixes4.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Test different depth auto result4a = parameters_client->list_parameters({"foo"}, 2); rclcpp::spin_until_future_complete(node, result4a); auto parameters_and_prefixes4a = result4a.get(); for (auto & name : parameters_and_prefixes4a.names) { EXPECT_TRUE(name == "foo" || name == "foo.first" || name == "foo.second"); } for (auto & prefix : parameters_and_prefixes4a.prefixes) { EXPECT_STREQ("foo", prefix.c_str()); } // Get a few of the parameters just set. auto result2 = parameters_client->get_parameters({"foo", "bar", "baz"}); rclcpp::spin_until_future_complete(node, result2); for (auto & parameter : result2.get()) { if (parameter.get_name() == "foo") { EXPECT_STREQ("foo", parameter.get_name().c_str()); EXPECT_STREQ( "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"2\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("integer", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "bar") { EXPECT_STREQ( "{\"name\": \"bar\", \"type\": \"string\", \"value\": \"hello\"}", std::to_string(parameter).c_str()); EXPECT_STREQ("string", parameter.get_type_name().c_str()); } else if (parameter.get_name() == "baz") { EXPECT_STREQ("double", parameter.get_type_name().c_str()); EXPECT_NEAR(1.45, parameter.as_double(), test_epsilon); } else { ASSERT_FALSE("you should never hit this"); } } // Get a few non existant parameters auto result3 = parameters_client->get_parameters({"not_foo", "not_baz"}); rclcpp::spin_until_future_complete(node, result3); for (auto & parameter : result3.get()) { EXPECT_STREQ("There should be no matches", parameter.get_name().c_str()); } // List all of the parameters, using an empty prefix list auto result5 = parameters_client->list_parameters({}, rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE); rclcpp::spin_until_future_complete(node, result5); parameters_and_prefixes = result5.get(); std::vector<std::string> all_names = { "foo", "bar", "barstr", "baz", "foo.first", "foo.second", "foobar" }; EXPECT_EQ(parameters_and_prefixes.names.size(), all_names.size()); for (auto & name : all_names) { EXPECT_NE(std::find( parameters_and_prefixes.names.cbegin(), parameters_and_prefixes.names.cend(), name), parameters_and_prefixes.names.cend()); } } #endif // PARAMETER_FIXTURES_HPP_ <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "../../vendor/catch/catch.hpp" #include "../share/json_helper.hpp" #include "grabber_alerts_manager.hpp" #include "thread_utility.hpp" #include <unistd.h> TEST_CASE("initialize") { krbn::thread_utility::register_main_thread(); } TEST_CASE("set_alert") { using namespace std::string_literals; std::vector<std::string> file_names{ "grabber_alerts_manager0.json"s, "grabber_alerts_manager1.json"s, "grabber_alerts_manager2.json"s, }; for (const auto& file_name : file_names) { auto tmp_file_path = "tmp/"s + file_name; unlink(tmp_file_path.c_str()); } krbn::grabber_alerts_manager::enable_json_output("tmp/grabber_alerts_manager0.json"); krbn::grabber_alerts_manager::save_to_file(); krbn::grabber_alerts_manager::enable_json_output("tmp/grabber_alerts_manager1.json"); krbn::grabber_alerts_manager::set_alert(krbn::grabber_alerts_manager::alert::system_policy_prevents_loading_kext, true); krbn::grabber_alerts_manager::enable_json_output("tmp/grabber_alerts_manager2.json"); krbn::grabber_alerts_manager::set_alert(krbn::grabber_alerts_manager::alert::system_policy_prevents_loading_kext, false); krbn::async_sequential_file_writer::get_instance().wait(); for (const auto& file_name : file_names) { REQUIRE(krbn::unit_testing::json_helper::compare_files("tmp/"s + file_name, "expected/"s + file_name)); } } <commit_msg>update tests<commit_after>#define CATCH_CONFIG_MAIN #include "../../vendor/catch/catch.hpp" #include "../share/json_helper.hpp" #include "grabber_alerts_manager.hpp" #include "thread_utility.hpp" #include <unistd.h> TEST_CASE("initialize") { krbn::thread_utility::register_main_thread(); } TEST_CASE("set_alert") { using namespace std::string_literals; std::vector<std::string> file_names{ "grabber_alerts_manager0.json"s, "grabber_alerts_manager1.json"s, "grabber_alerts_manager2.json"s, }; for (const auto& file_name : file_names) { auto tmp_file_path = "tmp/"s + file_name; unlink(tmp_file_path.c_str()); } { auto grabber_alerts_manager = std::make_unique<krbn::grabber_alerts_manager>( "tmp/grabber_alerts_manager0.json"); grabber_alerts_manager->async_save_to_file(); } { auto grabber_alerts_manager = std::make_unique<krbn::grabber_alerts_manager>( "tmp/grabber_alerts_manager1.json"); grabber_alerts_manager->async_set_alert(krbn::grabber_alerts_manager::alert::system_policy_prevents_loading_kext, true); } { auto grabber_alerts_manager = std::make_unique<krbn::grabber_alerts_manager>( "tmp/grabber_alerts_manager2.json"); grabber_alerts_manager->async_set_alert(krbn::grabber_alerts_manager::alert::system_policy_prevents_loading_kext, false); } krbn::async_sequential_file_writer::get_instance().wait(); for (const auto& file_name : file_names) { REQUIRE(krbn::unit_testing::json_helper::compare_files("tmp/"s + file_name, "expected/"s + file_name)); } } <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "rdb_protocol/var_types.hpp" #include "containers/archive/stl_types.hpp" #include "rdb_protocol/datum.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/env.hpp" #include "stl_utils.hpp" namespace ql { var_visibility_t::var_visibility_t() : implicit_depth(0) { } var_visibility_t var_visibility_t::with_func_arg_name_list(const std::vector<sym_t> &arg_names) const { var_visibility_t ret = *this; ret.visibles.insert(arg_names.begin(), arg_names.end()); if (function_emits_implicit_variable(arg_names)) { ++ret.implicit_depth; } return ret; } bool var_visibility_t::contains_var(sym_t varname) const { return visibles.find(varname) != visibles.end(); } bool var_visibility_t::implicit_is_accessible() const { return implicit_depth == 1; } void debug_print(printf_buffer_t *buf, const var_visibility_t &var_visibility) { buf->appendf("var_visibility{implicit_depth=%" PRIu32 ", visibles=", var_visibility.implicit_depth); debug_print(buf, var_visibility.visibles); buf->appendf("}"); } var_captures_t::var_captures_t(var_captures_t &&movee) : vars_captured(std::move(movee.vars_captured)), implicit_is_captured(std::move(movee.implicit_is_captured)) { // Just to leave things in a clean state... movee.implicit_is_captured = false; } var_captures_t &var_captures_t::operator=(var_captures_t &&movee) { var_captures_t tmp(std::move(movee)); vars_captured.swap(tmp.vars_captured); implicit_is_captured = tmp.implicit_is_captured; return *this; } var_scope_t::var_scope_t() : implicit_depth(0) { } var_scope_t var_scope_t::with_func_arg_list( const std::vector<sym_t> &arg_names, const std::vector<counted_t<const datum_t> > &arg_values) const { r_sanity_check(arg_names.size() == arg_values.size()); var_scope_t ret = *this; if (function_emits_implicit_variable(arg_names)) { if (ret.implicit_depth == 0) { ret.maybe_implicit = arg_values[0]; } else { ret.maybe_implicit.reset(); } ++ret.implicit_depth; } for (size_t i = 0; i < arg_names.size(); ++i) { r_sanity_check(arg_values[i].has()); ret.vars.insert(std::make_pair(arg_names[i], arg_values[i])); } return ret; } var_scope_t var_scope_t::filtered_by_captures(const var_captures_t &captures) const { var_scope_t ret; for (auto it = captures.vars_captured.begin(); it != captures.vars_captured.end(); ++it) { auto vars_it = vars.find(*it); r_sanity_check(vars_it != vars.end()); ret.vars.insert(*vars_it); } ret.implicit_depth = implicit_depth; if (captures.implicit_is_captured) { r_sanity_check(implicit_depth == 1); ret.maybe_implicit = maybe_implicit; } return ret; } counted_t<const datum_t> var_scope_t::lookup_var(sym_t varname) const { auto it = vars.find(varname); // This is a sanity check because we should never have constructed an expression // with an invalid variable name. r_sanity_check(it != vars.end()); return it->second; } counted_t<const datum_t> var_scope_t::lookup_implicit() const { r_sanity_check(implicit_depth == 1 && maybe_implicit.has()); return maybe_implicit; } std::string var_scope_t::print() const { std::string ret = "["; if (implicit_depth == 0) { ret += "(no implicit)"; } else if (implicit_depth == 1) { ret += "implicit: "; if (maybe_implicit.has()) { ret += maybe_implicit->print(); } else { ret += "(not stored)"; } } else { ret += "(multiple implicits)"; } for (auto it = vars.begin(); it != vars.end(); ++it) { ret += ", "; ret += strprintf("%" PRIi64 ": ", it->first.value); ret += it->second->print(); } ret += "]"; return ret; } var_visibility_t var_scope_t::compute_visibility() const { var_visibility_t ret; for (auto it = vars.begin(); it != vars.end(); ++it) { ret.visibles.insert(it->first); } ret.implicit_depth = implicit_depth; return ret; } template <cluster_version_t W> void var_scope_t::rdb_serialize(write_message_t *wm) const { serialize<W>(wm, vars); serialize<W>(wm, implicit_depth); if (implicit_depth == 1) { const bool has = maybe_implicit.has(); serialize<W>(wm, has); if (has) { serialize<W>(wm, maybe_implicit); } } } template <cluster_version_t W> archive_result_t var_scope_t::rdb_deserialize(read_stream_t *s) { std::map<sym_t, counted_t<const datum_t> > local_vars; archive_result_t res = deserialize<W>(s, &local_vars); if (bad(res)) { return res; } uint32_t local_implicit_depth; res = deserialize<W>(s, &local_implicit_depth); if (bad(res)) { return res; } counted_t<const datum_t> local_maybe_implicit; if (local_implicit_depth == 1) { bool has; res = deserialize<W>(s, &has); if (bad(res)) { return res; } if (has) { res = deserialize<W>(s, &local_maybe_implicit); if (bad(res)) { return res; } } } vars = std::move(local_vars); implicit_depth = local_implicit_depth; maybe_implicit = std::move(local_maybe_implicit); return archive_result_t::SUCCESS; } INSTANTIATE_SERIALIZE_FOR_CLUSTER_AND_DISK(var_scope_t); template archive_result_t var_scope_t::rdb_deserialize<cluster_version_t::v1_13>(read_stream_t *s); template archive_result_t var_scope_t::rdb_deserialize<cluster_version_t::v1_13_2_is_latest>(read_stream_t *s); } // namespace ql <commit_msg>Use the right macro. Fixes #2648<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "rdb_protocol/var_types.hpp" #include "containers/archive/stl_types.hpp" #include "rdb_protocol/datum.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/env.hpp" #include "stl_utils.hpp" namespace ql { var_visibility_t::var_visibility_t() : implicit_depth(0) { } var_visibility_t var_visibility_t::with_func_arg_name_list(const std::vector<sym_t> &arg_names) const { var_visibility_t ret = *this; ret.visibles.insert(arg_names.begin(), arg_names.end()); if (function_emits_implicit_variable(arg_names)) { ++ret.implicit_depth; } return ret; } bool var_visibility_t::contains_var(sym_t varname) const { return visibles.find(varname) != visibles.end(); } bool var_visibility_t::implicit_is_accessible() const { return implicit_depth == 1; } void debug_print(printf_buffer_t *buf, const var_visibility_t &var_visibility) { buf->appendf("var_visibility{implicit_depth=%" PRIu32 ", visibles=", var_visibility.implicit_depth); debug_print(buf, var_visibility.visibles); buf->appendf("}"); } var_captures_t::var_captures_t(var_captures_t &&movee) : vars_captured(std::move(movee.vars_captured)), implicit_is_captured(std::move(movee.implicit_is_captured)) { // Just to leave things in a clean state... movee.implicit_is_captured = false; } var_captures_t &var_captures_t::operator=(var_captures_t &&movee) { var_captures_t tmp(std::move(movee)); vars_captured.swap(tmp.vars_captured); implicit_is_captured = tmp.implicit_is_captured; return *this; } var_scope_t::var_scope_t() : implicit_depth(0) { } var_scope_t var_scope_t::with_func_arg_list( const std::vector<sym_t> &arg_names, const std::vector<counted_t<const datum_t> > &arg_values) const { r_sanity_check(arg_names.size() == arg_values.size()); var_scope_t ret = *this; if (function_emits_implicit_variable(arg_names)) { if (ret.implicit_depth == 0) { ret.maybe_implicit = arg_values[0]; } else { ret.maybe_implicit.reset(); } ++ret.implicit_depth; } for (size_t i = 0; i < arg_names.size(); ++i) { r_sanity_check(arg_values[i].has()); ret.vars.insert(std::make_pair(arg_names[i], arg_values[i])); } return ret; } var_scope_t var_scope_t::filtered_by_captures(const var_captures_t &captures) const { var_scope_t ret; for (auto it = captures.vars_captured.begin(); it != captures.vars_captured.end(); ++it) { auto vars_it = vars.find(*it); r_sanity_check(vars_it != vars.end()); ret.vars.insert(*vars_it); } ret.implicit_depth = implicit_depth; if (captures.implicit_is_captured) { r_sanity_check(implicit_depth == 1); ret.maybe_implicit = maybe_implicit; } return ret; } counted_t<const datum_t> var_scope_t::lookup_var(sym_t varname) const { auto it = vars.find(varname); // This is a sanity check because we should never have constructed an expression // with an invalid variable name. r_sanity_check(it != vars.end()); return it->second; } counted_t<const datum_t> var_scope_t::lookup_implicit() const { r_sanity_check(implicit_depth == 1 && maybe_implicit.has()); return maybe_implicit; } std::string var_scope_t::print() const { std::string ret = "["; if (implicit_depth == 0) { ret += "(no implicit)"; } else if (implicit_depth == 1) { ret += "implicit: "; if (maybe_implicit.has()) { ret += maybe_implicit->print(); } else { ret += "(not stored)"; } } else { ret += "(multiple implicits)"; } for (auto it = vars.begin(); it != vars.end(); ++it) { ret += ", "; ret += strprintf("%" PRIi64 ": ", it->first.value); ret += it->second->print(); } ret += "]"; return ret; } var_visibility_t var_scope_t::compute_visibility() const { var_visibility_t ret; for (auto it = vars.begin(); it != vars.end(); ++it) { ret.visibles.insert(it->first); } ret.implicit_depth = implicit_depth; return ret; } template <cluster_version_t W> void var_scope_t::rdb_serialize(write_message_t *wm) const { serialize<W>(wm, vars); serialize<W>(wm, implicit_depth); if (implicit_depth == 1) { const bool has = maybe_implicit.has(); serialize<W>(wm, has); if (has) { serialize<W>(wm, maybe_implicit); } } } template <cluster_version_t W> archive_result_t var_scope_t::rdb_deserialize(read_stream_t *s) { std::map<sym_t, counted_t<const datum_t> > local_vars; archive_result_t res = deserialize<W>(s, &local_vars); if (bad(res)) { return res; } uint32_t local_implicit_depth; res = deserialize<W>(s, &local_implicit_depth); if (bad(res)) { return res; } counted_t<const datum_t> local_maybe_implicit; if (local_implicit_depth == 1) { bool has; res = deserialize<W>(s, &has); if (bad(res)) { return res; } if (has) { res = deserialize<W>(s, &local_maybe_implicit); if (bad(res)) { return res; } } } vars = std::move(local_vars); implicit_depth = local_implicit_depth; maybe_implicit = std::move(local_maybe_implicit); return archive_result_t::SUCCESS; } INSTANTIATE_SERIALIZE_SELF_FOR_CLUSTER_AND_DISK(var_scope_t); template archive_result_t var_scope_t::rdb_deserialize<cluster_version_t::v1_13>(read_stream_t *s); template archive_result_t var_scope_t::rdb_deserialize<cluster_version_t::v1_13_2_is_latest>(read_stream_t *s); } // namespace ql <|endoftext|>
<commit_before>#include "renderer/frame_buffer.h" #include "engine/json_serializer.h" #include "engine/log.h" #include "engine/string.h" #include "engine/vec.h" #include <bgfx/bgfx.h> #include <lua.hpp> #include <lauxlib.h> namespace Lumix { FrameBuffer::FrameBuffer(const Declaration& decl) : m_declaration(decl) { m_autodestroy_handle = true; bgfx::TextureHandle texture_handles[16]; for (int i = 0; i < decl.m_renderbuffers_count; ++i) { const RenderBuffer& renderbuffer = decl.m_renderbuffers[i]; texture_handles[i] = bgfx::createTexture2D((uint16_t)decl.m_width, (uint16_t)decl.m_height, 1, renderbuffer.m_format, BGFX_TEXTURE_RT); m_declaration.m_renderbuffers[i].m_handle = texture_handles[i]; } m_window_handle = nullptr; m_handle = bgfx::createFrameBuffer((uint8_t)decl.m_renderbuffers_count, texture_handles); ASSERT(bgfx::isValid(m_handle)); } FrameBuffer::FrameBuffer(const char* name, int width, int height, void* window_handle) { m_autodestroy_handle = false; copyString(m_declaration.m_name, name); m_declaration.m_width = width; m_declaration.m_height = height; m_declaration.m_renderbuffers_count = 0; m_window_handle = window_handle; m_handle = bgfx::createFrameBuffer(window_handle, (uint16_t)width, (uint16_t)height); ASSERT(bgfx::isValid(m_handle)); } FrameBuffer::~FrameBuffer() { if (m_autodestroy_handle) { destroyRenderbuffers(); bgfx::destroyFrameBuffer(m_handle); } } void FrameBuffer::destroyRenderbuffers() { for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i) { bgfx::destroyTexture(m_declaration.m_renderbuffers[i].m_handle); } } void FrameBuffer::resize(int width, int height) { if (bgfx::isValid(m_handle)) { destroyRenderbuffers(); bgfx::destroyFrameBuffer(m_handle); } m_declaration.m_width = width; m_declaration.m_height = height; if (m_window_handle) { m_handle = bgfx::createFrameBuffer(m_window_handle, (uint16_t)width, (uint16_t)height); } else { bgfx::TextureHandle texture_handles[16]; for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i) { const RenderBuffer& renderbuffer = m_declaration.m_renderbuffers[i]; texture_handles[i] = bgfx::createTexture2D((uint16_t)width, (uint16_t)height, 1, renderbuffer.m_format, BGFX_TEXTURE_RT); m_declaration.m_renderbuffers[i].m_handle = texture_handles[i]; } m_window_handle = nullptr; m_handle = bgfx::createFrameBuffer((uint8_t)m_declaration.m_renderbuffers_count, texture_handles); } } bool FrameBuffer::RenderBuffer::isDepth() const { switch(m_format) { case bgfx::TextureFormat::D0S8: case bgfx::TextureFormat::D16: case bgfx::TextureFormat::D16F: case bgfx::TextureFormat::D24: case bgfx::TextureFormat::D24F: case bgfx::TextureFormat::D24S8: case bgfx::TextureFormat::D32: case bgfx::TextureFormat::D32F: return true; default: return false; } } static bgfx::TextureFormat::Enum getFormat(const char* name) { if (equalStrings(name, "depth32")) { return bgfx::TextureFormat::D32; } else if (equalStrings(name, "depth24")) { return bgfx::TextureFormat::D24; } else if (equalStrings(name, "rgba8")) { return bgfx::TextureFormat::RGBA8; } else if (equalStrings(name, "rgba16f")) { return bgfx::TextureFormat::RGBA16F; } else if (equalStrings(name, "r32f")) { return bgfx::TextureFormat::R32F; } else { g_log_error.log("Renderer") << "Uknown texture format " << name; return bgfx::TextureFormat::RGBA8; } } void FrameBuffer::RenderBuffer::parse(lua_State* L) { if (lua_getfield(L, -1, "format") == LUA_TSTRING) { m_format = getFormat(lua_tostring(L, -1)); } else { m_format = bgfx::TextureFormat::RGBA8; } lua_pop(L, 1); } } // ~namespace Lumix <commit_msg>d24s8 renderbuffer format<commit_after>#include "renderer/frame_buffer.h" #include "engine/json_serializer.h" #include "engine/log.h" #include "engine/string.h" #include "engine/vec.h" #include <bgfx/bgfx.h> #include <lua.hpp> #include <lauxlib.h> namespace Lumix { FrameBuffer::FrameBuffer(const Declaration& decl) : m_declaration(decl) { m_autodestroy_handle = true; bgfx::TextureHandle texture_handles[16]; for (int i = 0; i < decl.m_renderbuffers_count; ++i) { const RenderBuffer& renderbuffer = decl.m_renderbuffers[i]; texture_handles[i] = bgfx::createTexture2D((uint16_t)decl.m_width, (uint16_t)decl.m_height, 1, renderbuffer.m_format, BGFX_TEXTURE_RT); m_declaration.m_renderbuffers[i].m_handle = texture_handles[i]; } m_window_handle = nullptr; m_handle = bgfx::createFrameBuffer((uint8_t)decl.m_renderbuffers_count, texture_handles); ASSERT(bgfx::isValid(m_handle)); } FrameBuffer::FrameBuffer(const char* name, int width, int height, void* window_handle) { m_autodestroy_handle = false; copyString(m_declaration.m_name, name); m_declaration.m_width = width; m_declaration.m_height = height; m_declaration.m_renderbuffers_count = 0; m_window_handle = window_handle; m_handle = bgfx::createFrameBuffer(window_handle, (uint16_t)width, (uint16_t)height); ASSERT(bgfx::isValid(m_handle)); } FrameBuffer::~FrameBuffer() { if (m_autodestroy_handle) { destroyRenderbuffers(); bgfx::destroyFrameBuffer(m_handle); } } void FrameBuffer::destroyRenderbuffers() { for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i) { bgfx::destroyTexture(m_declaration.m_renderbuffers[i].m_handle); } } void FrameBuffer::resize(int width, int height) { if (bgfx::isValid(m_handle)) { destroyRenderbuffers(); bgfx::destroyFrameBuffer(m_handle); } m_declaration.m_width = width; m_declaration.m_height = height; if (m_window_handle) { m_handle = bgfx::createFrameBuffer(m_window_handle, (uint16_t)width, (uint16_t)height); } else { bgfx::TextureHandle texture_handles[16]; for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i) { const RenderBuffer& renderbuffer = m_declaration.m_renderbuffers[i]; texture_handles[i] = bgfx::createTexture2D((uint16_t)width, (uint16_t)height, 1, renderbuffer.m_format, BGFX_TEXTURE_RT); m_declaration.m_renderbuffers[i].m_handle = texture_handles[i]; } m_window_handle = nullptr; m_handle = bgfx::createFrameBuffer((uint8_t)m_declaration.m_renderbuffers_count, texture_handles); } } bool FrameBuffer::RenderBuffer::isDepth() const { switch(m_format) { case bgfx::TextureFormat::D0S8: case bgfx::TextureFormat::D16: case bgfx::TextureFormat::D16F: case bgfx::TextureFormat::D24: case bgfx::TextureFormat::D24F: case bgfx::TextureFormat::D24S8: case bgfx::TextureFormat::D32: case bgfx::TextureFormat::D32F: return true; default: return false; } } static bgfx::TextureFormat::Enum getFormat(const char* name) { static const struct { const char* name; bgfx::TextureFormat::Enum value; } FORMATS[] = { { "depth32", bgfx::TextureFormat::D32 }, { "depth24", bgfx::TextureFormat::D24 }, { "depth24stencil8", bgfx::TextureFormat::D24S8 }, { "rgba8", bgfx::TextureFormat::RGBA8 }, { "rgba16f", bgfx::TextureFormat::RGBA16F }, { "r32f", bgfx::TextureFormat::R32F }, }; for (auto& i : FORMATS) { if (equalStrings(i.name, name)) return i.value; } g_log_error.log("Renderer") << "Uknown texture format " << name; return bgfx::TextureFormat::RGBA8; } void FrameBuffer::RenderBuffer::parse(lua_State* L) { if (lua_getfield(L, -1, "format") == LUA_TSTRING) { m_format = getFormat(lua_tostring(L, -1)); } else { m_format = bgfx::TextureFormat::RGBA8; } lua_pop(L, 1); } } // ~namespace Lumix <|endoftext|>
<commit_before>/// /// @file fast_div.hpp /// @brief Integer division of small types is much faster than /// integer division of large types on most CPUs. The /// fast_div(x, y) function tries to take advantage of /// this by casting x and y to smaller types (if possible) /// before doing the division. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef FAST_DIV_HPP #define FAST_DIV_HPP #include <int128_t.hpp> #include <cassert> #include <limits> #include <type_traits> namespace primecount { template <typename T> struct fastdiv { typedef typename std::conditional<sizeof(T) / 2 <= sizeof(uint8_t), uint8_t, typename std::conditional<sizeof(T) / 2 == sizeof(uint16_t), uint16_t, typename std::conditional<sizeof(T) / 2 == sizeof(uint32_t), uint32_t, uint64_t>::type>::type>::type type; }; template <typename T> T fast_div(T x, T y) { static_assert(prt::is_integral<T>::value, "fast_div(x, y): type must be integral"); using fastdiv_t = typename fastdiv<T>::type; if (x <= std::numeric_limits<fastdiv_t>::max() && y <= std::numeric_limits<fastdiv_t>::max()) { return (fastdiv_t) x / (fastdiv_t) y; } return x / y; } template <typename X, typename Y> X fast_div(X x, Y y) { static_assert(prt::is_integral<X>::value && prt::is_integral<Y>::value && sizeof(X) >= sizeof(Y), "fast_div(x, y): invalid types"); using fastdiv_t = typename fastdiv<X>::type; if (x <= std::numeric_limits<fastdiv_t>::max()) return (fastdiv_t) x / (fastdiv_t) y; return x / y; } } // namespace #endif <commit_msg>Use std::enable_if<commit_after>/// /// @file fast_div.hpp /// @brief Integer division of small types is much faster than /// integer division of large types on most CPUs. The /// fast_div(x, y) function tries to take advantage of /// this by casting x and y to smaller types (if possible) /// before doing the division. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef FAST_DIV_HPP #define FAST_DIV_HPP #include <int128_t.hpp> #include <cassert> #include <limits> #include <type_traits> namespace primecount { template <typename T> struct fastdiv { typedef typename std::conditional<sizeof(T) / 2 <= sizeof(uint8_t), uint8_t, typename std::conditional<sizeof(T) / 2 == sizeof(uint16_t), uint16_t, typename std::conditional<sizeof(T) / 2 == sizeof(uint32_t), uint32_t, uint64_t>::type>::type>::type type; }; template <typename X, typename Y> typename std::enable_if<(sizeof(X) == sizeof(Y)), X>::type fast_div(X x, Y y) { static_assert(prt::is_integral<X>::value && prt::is_integral<Y>::value, "fast_div(x, y): types must be integral"); using fastdiv_t = typename fastdiv<X>::type; if (x <= std::numeric_limits<fastdiv_t>::max() && y <= std::numeric_limits<fastdiv_t>::max()) { return (fastdiv_t) x / (fastdiv_t) y; } return x / y; } template <typename X, typename Y> typename std::enable_if<(sizeof(X) > sizeof(Y)), X>::type fast_div(X x, Y y) { static_assert(prt::is_integral<X>::value && prt::is_integral<Y>::value, "fast_div(x, y): types must be integral"); using fastdiv_t = typename fastdiv<X>::type; if (x <= std::numeric_limits<fastdiv_t>::max()) return (fastdiv_t) x / (fastdiv_t) y; return x / y; } } // namespace #endif <|endoftext|>
<commit_before>#include <atomic> #include "percpu.hh" class filetable { private: static const int cpushift = 16; static const int fdmask = (1 << cpushift) - 1; public: static filetable* alloc() { return new filetable(); } filetable* copy() { filetable* t = new filetable(false); for(int cpu = 0; cpu < NCPU; cpu++) { for(int fd = 0; fd < NOFILE; fd++) { sref<file> f; if (getfile((cpu << cpushift) | fd, &f)) { f->inc(); t->ofile_[cpu][fd].store(f.get()); } else { t->ofile_[cpu][fd].store(nullptr); } } } return t; } bool getfile(int fd, sref<file> *sf) { int cpu = fd >> cpushift; fd = fd & fdmask; if (cpu < 0 || cpu >= NCPU) return false; if (fd < 0 || fd >= NOFILE) return false; scoped_gc_epoch gc; file* f = ofile_[cpu][fd]; if (!f || !sf->init_nonzero(f)) return false; return true; } int allocfd(struct file *f, bool percpu = false) { int cpu = percpu ? myid() : 0; for (int fd = 0; fd < NOFILE; fd++) if (ofile_[cpu][fd] == nullptr && cmpxch(&ofile_[cpu][fd], (file*)nullptr, f)) return (cpu << cpushift) | fd; cprintf("filetable::allocfd: failed\n"); return -1; } void close(int fd) { // XXX(sbw) if f->ref_ > 1 the kernel will not actually close // the file when this function returns (i.e. sys_close can return // while the file/pipe/socket is still open). int cpu = fd >> cpushift; fd = fd & fdmask; if (cpu < 0 || cpu >= NCPU) { cprintf("filetable::close: bad fd cpu %u\n", cpu); return; } if (fd < 0 || fd >= NOFILE) { cprintf("filetable::close: bad fd %u\n", fd); return; } file* f = ofile_[cpu][fd].exchange(nullptr); if (f != nullptr) f->dec(); else cprintf("filetable::close: bad fd %u\n", fd); } void decref() { if (--ref_ == 0) delete this; } void incref() { ref_++; } private: filetable(bool clear = true) : ref_(1) { if (!clear) return; for(int cpu = 0; cpu < NCPU; cpu++) for(int fd = 0; fd < NOFILE; fd++) ofile_[cpu][fd].store(nullptr); } ~filetable() { for(int cpu = 0; cpu < NCPU; cpu++){ for(int fd = 0; fd < NOFILE; fd++){ if (ofile_[cpu][fd].load() != nullptr) { ofile_[cpu][fd].load()->dec(); ofile_[cpu][fd] = nullptr; } } } } filetable& operator=(const filetable&); filetable(const filetable& x); NEW_DELETE_OPS(filetable); percpu<std::atomic<file*>[NOFILE]> ofile_; std::atomic<u64> ref_; }; <commit_msg>filetable: Use relaxed stores to initialize<commit_after>#include <atomic> #include "percpu.hh" class filetable { private: static const int cpushift = 16; static const int fdmask = (1 << cpushift) - 1; public: static filetable* alloc() { return new filetable(); } filetable* copy() { filetable* t = new filetable(false); for(int cpu = 0; cpu < NCPU; cpu++) { for(int fd = 0; fd < NOFILE; fd++) { sref<file> f; if (getfile((cpu << cpushift) | fd, &f)) { f->inc(); t->ofile_[cpu][fd].store(f.get(), std::memory_order_relaxed); } else { t->ofile_[cpu][fd].store(nullptr, std::memory_order_relaxed); } } } std::atomic_thread_fence(std::memory_order_release); return t; } bool getfile(int fd, sref<file> *sf) { int cpu = fd >> cpushift; fd = fd & fdmask; if (cpu < 0 || cpu >= NCPU) return false; if (fd < 0 || fd >= NOFILE) return false; scoped_gc_epoch gc; file* f = ofile_[cpu][fd]; if (!f || !sf->init_nonzero(f)) return false; return true; } int allocfd(struct file *f, bool percpu = false) { int cpu = percpu ? myid() : 0; for (int fd = 0; fd < NOFILE; fd++) if (ofile_[cpu][fd] == nullptr && cmpxch(&ofile_[cpu][fd], (file*)nullptr, f)) return (cpu << cpushift) | fd; cprintf("filetable::allocfd: failed\n"); return -1; } void close(int fd) { // XXX(sbw) if f->ref_ > 1 the kernel will not actually close // the file when this function returns (i.e. sys_close can return // while the file/pipe/socket is still open). int cpu = fd >> cpushift; fd = fd & fdmask; if (cpu < 0 || cpu >= NCPU) { cprintf("filetable::close: bad fd cpu %u\n", cpu); return; } if (fd < 0 || fd >= NOFILE) { cprintf("filetable::close: bad fd %u\n", fd); return; } file* f = ofile_[cpu][fd].exchange(nullptr); if (f != nullptr) f->dec(); else cprintf("filetable::close: bad fd %u\n", fd); } void decref() { if (--ref_ == 0) delete this; } void incref() { ref_++; } private: filetable(bool clear = true) : ref_(1) { if (!clear) return; for(int cpu = 0; cpu < NCPU; cpu++) for(int fd = 0; fd < NOFILE; fd++) ofile_[cpu][fd].store(nullptr, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_release); } ~filetable() { for(int cpu = 0; cpu < NCPU; cpu++){ for(int fd = 0; fd < NOFILE; fd++){ if (ofile_[cpu][fd].load() != nullptr) { ofile_[cpu][fd].load()->dec(); ofile_[cpu][fd] = nullptr; } } } } filetable& operator=(const filetable&); filetable(const filetable& x); NEW_DELETE_OPS(filetable); percpu<std::atomic<file*>[NOFILE]> ofile_; std::atomic<u64> ref_; }; <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include "move.hpp" #include "types.hpp" #include "unique_ptr.hpp" namespace yacppl { namespace detail { template <typename R, typename ...Args> class callable { public: virtual ~callable() {} virtual R operator()(Args ...args) = 0; }; template<typename ClosureType, typename R, typename ...Args> class closure: public callable<R, Args...> { const ClosureType func_; public: closure(const ClosureType &handler) : func_(handler) { } ~closure() { } R operator()(Args ...args) override { if (is_void<R>::value) func_(forward<Args>(args)...); else return func_(forward<Args>(args)...); } constexpr void *operator new(size_t, void *address) { return address; } }; } // namespace detail template <typename FunctionType> class function : public function<decltype(&FunctionType::operator())> { }; template <typename R, typename ...Args> class function<R(Args...)> { detail::callable<R, Args...> *func_wrapper_ = nullptr; char data_[2 * sizeof(void *)]; // FIXME: why? public: function() = default; template<typename ClosureType> function(const ClosureType &function) : func_wrapper_(new (data_) detail::closure<decltype(function), R, Args...>(function)) { } function &operator=(nullptr_t) = delete; template<typename ClosureType> function &operator=(const ClosureType &function) { func_wrapper_ = new (data_) detail::closure<decltype(function), R, Args...>(function); return *this; } template <typename T = R> typename enable_if<is_void<T>::value, T>::type operator()(Args ...args) { (*func_wrapper_)(forward<Args>(args)...); } template <typename T = R> typename enable_if<!is_void<T>::value, T>::type operator()(Args ...args) { return (*func_wrapper_)(forward<Args>(args)...); } operator bool() const { return func_wrapper_ != nullptr; } }; } // namespace yacppl <commit_msg>Add const qualifier to some methods in function.hpp<commit_after>#pragma once #include <cstddef> #include "move.hpp" #include "types.hpp" #include "unique_ptr.hpp" namespace yacppl { namespace detail { template <typename R, typename ...Args> class callable { public: virtual ~callable() {} virtual R operator()(Args ...args) const = 0; }; template<typename ClosureType, typename R, typename ...Args> class closure: public callable<R, Args...> { const ClosureType func_; public: closure(const ClosureType &handler) : func_(handler) { } ~closure() { } R operator()(Args ...args) const override { if (is_void<R>::value) func_(forward<Args>(args)...); else return func_(forward<Args>(args)...); } constexpr void *operator new(size_t, void *address) { return address; } }; } // namespace detail template <typename FunctionType> class function : public function<decltype(&FunctionType::operator())> { }; template <typename R, typename ...Args> class function<R(Args...)> { const detail::callable<R, Args...> *func_wrapper_ = nullptr; char data_[2 * sizeof(void *)]; // FIXME: why? public: function() = default; template<typename ClosureType> function(const ClosureType &function) : func_wrapper_(new (data_) detail::closure<decltype(function), R, Args...>(function)) { } function &operator=(nullptr_t) = delete; template<typename ClosureType> function &operator=(const ClosureType &function) { func_wrapper_ = new (data_) detail::closure<decltype(function), R, Args...>(function); return *this; } template <typename T = R> typename enable_if<is_void<T>::value, T>::type operator()(Args ...args) const { (*func_wrapper_)(forward<Args>(args)...); } template <typename T = R> typename enable_if<!is_void<T>::value, T>::type operator()(Args ...args) const { return (*func_wrapper_)(forward<Args>(args)...); } operator bool() const { return func_wrapper_ != nullptr; } }; } // namespace yacppl <|endoftext|>
<commit_before>#ifndef HORNET_VM_HH #define HORNET_VM_HH #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include <mutex> #include <map> #include <classfile_constants.h> namespace hornet { class constant_pool; struct method; struct field; struct klass; class loader; class jvm { public: std::shared_ptr<klass> lookup_class(std::string name); void register_class(std::shared_ptr<klass> klass); void invoke(method* method); private: std::map<std::string, std::shared_ptr<klass>> _classes; }; extern jvm *_jvm; typedef uint64_t value_t; struct object { struct object* fwd; struct klass* klass; std::vector<value_t> _fields; std::mutex _mutex; object(struct klass* _klass); ~object(); object& operator=(const object&) = delete; object(const object&) = delete; value_t get_field(size_t offset) const { return _fields[offset]; } void set_field(size_t offset, value_t value) { _fields[offset] = value; } void lock() { _mutex.lock(); } void unlock() { _mutex.unlock(); } }; using method_list_type = std::vector<std::shared_ptr<method>>; using field_list_type = std::vector<std::shared_ptr<field>>; enum class klass_state { loaded, initialized, }; struct klass { struct object object; std::string name; klass* super; uint16_t access_flags; klass_state state = klass_state::loaded; uint32_t nr_fields; std::vector<value_t> static_values; std::vector<std::shared_ptr<klass>> interfaces; klass(); klass(loader* loader, std::shared_ptr<constant_pool> const_pool); ~klass(); klass& operator=(const klass&) = delete; klass(const klass&) = delete; void init(); bool verify(); void add(std::shared_ptr<klass> iface); void add(std::shared_ptr<method> method); void add(std::shared_ptr<field> field); virtual bool is_primitive() const { return false; } virtual size_t size() const { return sizeof(void*); } std::shared_ptr<constant_pool> const_pool() const { return _const_pool; } bool is_subclass_of(klass* klass) { auto* super = this; while (super != nullptr) { if (super == klass) { return true; } super = super->super; } return false; } std::shared_ptr<klass> load_class(std::string name); std::shared_ptr<method> lookup_method(std::string name, std::string desciptor); std::shared_ptr<field> lookup_field(std::string name, std::string desciptor); std::shared_ptr<klass> resolve_class (uint16_t idx); std::shared_ptr<field> resolve_field (uint16_t idx); std::shared_ptr<method> resolve_method(uint16_t idx); std::shared_ptr<method> resolve_interface_method(uint16_t idx); private: std::shared_ptr<constant_pool> _const_pool; method_list_type _methods; field_list_type _fields; loader* _loader; }; struct field { struct klass* klass; std::string name; std::string descriptor; uint32_t offset; uint16_t access_flags; field(struct klass* klass_); ~field(); field& operator=(const field&) = delete; field(const field&) = delete; bool is_static() const { return access_flags & JVM_ACC_STATIC; } bool matches(std::string name, std::string descriptor); }; struct method { // Method lifecycle is tied to the class it belongs to. Use a pointer to // klass instead of a smart pointer to break the cyclic dependency during // destruction. struct klass* klass; uint16_t access_flags; std::string name; std::string descriptor; struct klass* return_type; std::vector<struct klass*> arg_types; uint16_t args_count; uint16_t max_locals; char* code; uint32_t code_length; std::vector<uint8_t> trampoline; method() { } ~method() { delete[] code; } method& operator=(const method&) = delete; method(const method&) = delete; std::string full_name() const { return klass->name + "::" + name + descriptor; } bool is_init() const { return name[0] == '<'; } bool is_native() const { return access_flags & JVM_ACC_NATIVE; } bool matches(std::string n, std::string d) { return name == n && descriptor == d; } }; struct array { struct object object; uint32_t length; char data[]; array(klass* klass, uint32_t length) : object(klass) , length(length) { } ~array() { } array& operator=(const array&) = delete; array(const array&) = delete; template<typename T> void set(size_t idx, T value) { T* p = reinterpret_cast<T*>(data); p[idx] = value; } template<typename T> T get(size_t idx) const { auto* p = reinterpret_cast<const T*>(data); return p[idx]; } }; struct string { struct object object; const char* data; string(const char* data_) : object(nullptr) , data(data_) { } ~string() { } string& operator=(const string&) = delete; string(const string&) = delete; }; inline bool is_array_type_name(std::string name) { return !name.empty() && name[0] == '['; } #define java_lang_NoClassDefFoundError reinterpret_cast<hornet::object *>(0xdeabeef) #define java_lang_NoSuchMethodError reinterpret_cast<hornet::object *>(0xdeabeef) #define java_lang_VerifyError reinterpret_cast<hornet::object *>(0xdeabeef) void gc_init(); object* gc_new_object(klass* klass); array* gc_new_object_array(klass* klass, size_t length); } #endif <commit_msg>vm: Make method::matches() const<commit_after>#ifndef HORNET_VM_HH #define HORNET_VM_HH #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include <mutex> #include <map> #include <classfile_constants.h> namespace hornet { class constant_pool; struct method; struct field; struct klass; class loader; class jvm { public: std::shared_ptr<klass> lookup_class(std::string name); void register_class(std::shared_ptr<klass> klass); void invoke(method* method); private: std::map<std::string, std::shared_ptr<klass>> _classes; }; extern jvm *_jvm; typedef uint64_t value_t; struct object { struct object* fwd; struct klass* klass; std::vector<value_t> _fields; std::mutex _mutex; object(struct klass* _klass); ~object(); object& operator=(const object&) = delete; object(const object&) = delete; value_t get_field(size_t offset) const { return _fields[offset]; } void set_field(size_t offset, value_t value) { _fields[offset] = value; } void lock() { _mutex.lock(); } void unlock() { _mutex.unlock(); } }; using method_list_type = std::vector<std::shared_ptr<method>>; using field_list_type = std::vector<std::shared_ptr<field>>; enum class klass_state { loaded, initialized, }; struct klass { struct object object; std::string name; klass* super; uint16_t access_flags; klass_state state = klass_state::loaded; uint32_t nr_fields; std::vector<value_t> static_values; std::vector<std::shared_ptr<klass>> interfaces; klass(); klass(loader* loader, std::shared_ptr<constant_pool> const_pool); ~klass(); klass& operator=(const klass&) = delete; klass(const klass&) = delete; void init(); bool verify(); void add(std::shared_ptr<klass> iface); void add(std::shared_ptr<method> method); void add(std::shared_ptr<field> field); virtual bool is_primitive() const { return false; } virtual size_t size() const { return sizeof(void*); } std::shared_ptr<constant_pool> const_pool() const { return _const_pool; } bool is_subclass_of(klass* klass) { auto* super = this; while (super != nullptr) { if (super == klass) { return true; } super = super->super; } return false; } std::shared_ptr<klass> load_class(std::string name); std::shared_ptr<method> lookup_method(std::string name, std::string desciptor); std::shared_ptr<field> lookup_field(std::string name, std::string desciptor); std::shared_ptr<klass> resolve_class (uint16_t idx); std::shared_ptr<field> resolve_field (uint16_t idx); std::shared_ptr<method> resolve_method(uint16_t idx); std::shared_ptr<method> resolve_interface_method(uint16_t idx); private: std::shared_ptr<constant_pool> _const_pool; method_list_type _methods; field_list_type _fields; loader* _loader; }; struct field { struct klass* klass; std::string name; std::string descriptor; uint32_t offset; uint16_t access_flags; field(struct klass* klass_); ~field(); field& operator=(const field&) = delete; field(const field&) = delete; bool is_static() const { return access_flags & JVM_ACC_STATIC; } bool matches(std::string name, std::string descriptor); }; struct method { // Method lifecycle is tied to the class it belongs to. Use a pointer to // klass instead of a smart pointer to break the cyclic dependency during // destruction. struct klass* klass; uint16_t access_flags; std::string name; std::string descriptor; struct klass* return_type; std::vector<struct klass*> arg_types; uint16_t args_count; uint16_t max_locals; char* code; uint32_t code_length; std::vector<uint8_t> trampoline; method() { } ~method() { delete[] code; } method& operator=(const method&) = delete; method(const method&) = delete; std::string full_name() const { return klass->name + "::" + name + descriptor; } bool is_init() const { return name[0] == '<'; } bool is_native() const { return access_flags & JVM_ACC_NATIVE; } bool matches(const std::string& n, const std::string d) const { return name == n && descriptor == d; } }; struct array { struct object object; uint32_t length; char data[]; array(klass* klass, uint32_t length) : object(klass) , length(length) { } ~array() { } array& operator=(const array&) = delete; array(const array&) = delete; template<typename T> void set(size_t idx, T value) { T* p = reinterpret_cast<T*>(data); p[idx] = value; } template<typename T> T get(size_t idx) const { auto* p = reinterpret_cast<const T*>(data); return p[idx]; } }; struct string { struct object object; const char* data; string(const char* data_) : object(nullptr) , data(data_) { } ~string() { } string& operator=(const string&) = delete; string(const string&) = delete; }; inline bool is_array_type_name(std::string name) { return !name.empty() && name[0] == '['; } #define java_lang_NoClassDefFoundError reinterpret_cast<hornet::object *>(0xdeabeef) #define java_lang_NoSuchMethodError reinterpret_cast<hornet::object *>(0xdeabeef) #define java_lang_VerifyError reinterpret_cast<hornet::object *>(0xdeabeef) void gc_init(); object* gc_new_object(klass* klass); array* gc_new_object_array(klass* klass, size_t length); } #endif <|endoftext|>
<commit_before>#include <limits.h> #include "gtest/gtest.h" #include "hybrid_automaton/DescriptionTreeXML.h" using namespace ha; //This just tests the structure of the tree - no XML specific things are tested TEST(TestDescriptionTreeStructure, Positive) { DescriptionTreeXML::Ptr tree(new DescriptionTreeXML()); DescriptionTreeNodeXML::Ptr rootNode(new DescriptionTreeNodeXML("root")); EXPECT_EQ(rootNode->getType(), "root"); DescriptionTreeNodeXML::Ptr daughterNode(new DescriptionTreeNodeXML("daughter")); DescriptionTreeNodeXML::Ptr sonNode(new DescriptionTreeNodeXML("son")); DescriptionTreeNodeXML::Ptr son2Node(new DescriptionTreeNodeXML("son")); DescriptionTreeNodeXML::Ptr grandDaughterNode(new DescriptionTreeNodeXML("granddaughter")); DescriptionTreeNode::Ptr raw = tree->getRootNode(); rootNode = boost::dynamic_pointer_cast<DescriptionTreeNodeXML>(raw); rootNode->addChildNode(daughterNode); rootNode->addChildNode(sonNode); rootNode->addChildNode(son2Node); sonNode->addChildNode(grandDaughterNode); //test getter for children nodes DescriptionTreeNode::ConstNodeList childrenOfRoot; EXPECT_TRUE(rootNode->getChildrenNodes(childrenOfRoot)); EXPECT_EQ(childrenOfRoot.size(), 3); DescriptionTreeNode::ConstNodeList childrenOfDaughter; EXPECT_FALSE(daughterNode->getChildrenNodes(childrenOfDaughter)); EXPECT_EQ(childrenOfDaughter.size(), 0); //test named getter for children nodes DescriptionTreeNode::ConstNodeList sonsOfRoot; EXPECT_TRUE(rootNode->getChildrenNodes("son", sonsOfRoot)); EXPECT_EQ(sonsOfRoot.size(), 2); DescriptionTreeNode::ConstNodeListIterator it = sonsOfRoot.begin(); for(it; it!=sonsOfRoot.end(); it++) { EXPECT_EQ(it->get()->getType(), "son"); } DescriptionTreeNode::ConstNodeList daughtersOfRoot; EXPECT_TRUE(rootNode->getChildrenNodes("daughter", daughtersOfRoot)); EXPECT_EQ(daughtersOfRoot.size(), 1); DescriptionTreeNode::ConstNodeList sonsOfSon; EXPECT_FALSE(sonNode->getChildrenNodes("son", sonsOfSon)); EXPECT_EQ(sonsOfSon.size(), 0); //test fields daughterNode->setAttribute<std::string>("name", "lucy"); std::string daughtersname; EXPECT_TRUE(daughterNode->getAttribute<std::string>("name", daughtersname)); EXPECT_FALSE(daughterNode->getAttribute<std::string>("beer", std::string("Lucy is too young too drink!"))); EXPECT_EQ(daughtersname, "lucy"); //Oh my god, what happened to Lucy? daughterNode->setAttribute<std::string>("name", "lucifer"); EXPECT_TRUE(daughterNode->getAttribute<std::string>("name", daughtersname)); EXPECT_EQ(daughtersname, "lucifer"); std::map<std::string, std::string> map; daughterNode->getAllAttributes(map); EXPECT_EQ("lucifer", map["name"]); EXPECT_EQ(1, map.size()); } //This test tests deparsing and reading out an xml string TEST(TestDescriptionTreeFromXMLString, Positive) { DescriptionTreeXML::Ptr tree(new DescriptionTreeXML()); //Test three xml cases - field with parameter a, child field b, and empty field c. std::string XMLString("<a par=k><b></b><c/></a>"); tree->initTree(XMLString); DescriptionTreeNode::Ptr root = tree->getRootNode(); DescriptionTreeNode::ConstNodeList childrenOfRoot; root->getChildrenNodes(childrenOfRoot); EXPECT_EQ(root->getType(), "a"); std::string ret; EXPECT_TRUE(root->getAttribute<std::string>("par", ret)); EXPECT_EQ(ret, "k"); //Case sensitive!!! EXPECT_FALSE(root->getAttribute<std::string>("Par", ret)); DescriptionTreeNode::ConstNodeListIterator it = childrenOfRoot.begin(); EXPECT_EQ(it->get()->getType(), "b"); it++; EXPECT_EQ(it->get()->getType(), "c"); } //This test tests out an xml string TEST(TestDescriptionTreeToXMLString, Positive) { DescriptionTreeXML::Ptr tree(new DescriptionTreeXML()); DescriptionTreeNodeXML::Ptr rootNode(new DescriptionTreeNodeXML("root")); DescriptionTreeNodeXML::Ptr firstNode(new DescriptionTreeNodeXML("firstchild")); DescriptionTreeNodeXML::Ptr secondNode(new DescriptionTreeNodeXML("secondchild")); DescriptionTreeNode::Ptr raw = tree->getRootNode(); rootNode = boost::dynamic_pointer_cast<DescriptionTreeNodeXML>(raw); rootNode->addChildNode(firstNode); secondNode->setAttribute<std::string>("param", "value"); ::Eigen::MatrixXd eigen_vector(5,1); eigen_vector << 1.8673, 2., 3., 4., 5.; secondNode->setAttribute<::Eigen::MatrixXd>("vector", eigen_vector); ::Eigen::MatrixXd eigen_matrix(5,2); eigen_matrix << 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.; secondNode->setAttribute<::Eigen::MatrixXd>("matrix", eigen_matrix); rootNode->addChildNode(secondNode); //New test: change vlaue after insertion secondNode->setAttribute<std::string>("param2", "value2"); std::string outString = tree->writeTreeXML(); //std::cout << outString << std::endl; //Now parse again and compare DescriptionTreeXML::Ptr tree2(new DescriptionTreeXML()); //Test three xml cases - field with parameter a, child field b, and empty field c. tree->initTree(outString); DescriptionTreeNode::Ptr root2 = tree->getRootNode(); DescriptionTreeNode::ConstNodeList childrenOfRoot; root2->getChildrenNodes(childrenOfRoot); DescriptionTreeNode::ConstNodeListIterator it = childrenOfRoot.begin(); EXPECT_EQ(it->get()->getType(), "firstchild"); it++; EXPECT_EQ(it->get()->getType(), "secondchild"); std::string ret; EXPECT_TRUE(it->get()->getAttribute<std::string>("param", ret)); EXPECT_EQ(ret, "value"); EXPECT_TRUE(it->get()->getAttribute<std::string>("param2", ret)); EXPECT_EQ(ret, "value2"); ::Eigen::MatrixXd result(0,0); EXPECT_TRUE(it->get()->getAttribute<::Eigen::MatrixXd>("vector", result)); EXPECT_EQ(eigen_vector, result); EXPECT_TRUE(it->get()->getAttribute<::Eigen::MatrixXd>("matrix", result)); EXPECT_EQ(eigen_matrix, result); } <commit_msg>When setting an argument as an string, please, do not create it when passing it. This compiles on windows but not on linux<commit_after>#include <limits.h> #include "gtest/gtest.h" #include "hybrid_automaton/DescriptionTreeXML.h" using namespace ha; //This just tests the structure of the tree - no XML specific things are tested TEST(TestDescriptionTreeStructure, Positive) { DescriptionTreeXML::Ptr tree(new DescriptionTreeXML()); DescriptionTreeNodeXML::Ptr rootNode(new DescriptionTreeNodeXML("root")); EXPECT_EQ(rootNode->getType(), "root"); DescriptionTreeNodeXML::Ptr daughterNode(new DescriptionTreeNodeXML("daughter")); DescriptionTreeNodeXML::Ptr sonNode(new DescriptionTreeNodeXML("son")); DescriptionTreeNodeXML::Ptr son2Node(new DescriptionTreeNodeXML("son")); DescriptionTreeNodeXML::Ptr grandDaughterNode(new DescriptionTreeNodeXML("granddaughter")); DescriptionTreeNode::Ptr raw = tree->getRootNode(); rootNode = boost::dynamic_pointer_cast<DescriptionTreeNodeXML>(raw); rootNode->addChildNode(daughterNode); rootNode->addChildNode(sonNode); rootNode->addChildNode(son2Node); sonNode->addChildNode(grandDaughterNode); //test getter for children nodes DescriptionTreeNode::ConstNodeList childrenOfRoot; EXPECT_TRUE(rootNode->getChildrenNodes(childrenOfRoot)); EXPECT_EQ(childrenOfRoot.size(), 3); DescriptionTreeNode::ConstNodeList childrenOfDaughter; EXPECT_FALSE(daughterNode->getChildrenNodes(childrenOfDaughter)); EXPECT_EQ(childrenOfDaughter.size(), 0); //test named getter for children nodes DescriptionTreeNode::ConstNodeList sonsOfRoot; EXPECT_TRUE(rootNode->getChildrenNodes("son", sonsOfRoot)); EXPECT_EQ(sonsOfRoot.size(), 2); DescriptionTreeNode::ConstNodeListIterator it = sonsOfRoot.begin(); for(it; it!=sonsOfRoot.end(); it++) { EXPECT_EQ(it->get()->getType(), "son"); } DescriptionTreeNode::ConstNodeList daughtersOfRoot; EXPECT_TRUE(rootNode->getChildrenNodes("daughter", daughtersOfRoot)); EXPECT_EQ(daughtersOfRoot.size(), 1); DescriptionTreeNode::ConstNodeList sonsOfSon; EXPECT_FALSE(sonNode->getChildrenNodes("son", sonsOfSon)); EXPECT_EQ(sonsOfSon.size(), 0); //test fields daughterNode->setAttribute<std::string>("name", "lucy"); std::string daughtersname; EXPECT_TRUE(daughterNode->getAttribute<std::string>("name", daughtersname)); std::string beer_str("Lucy is too young too drink!"); EXPECT_FALSE(daughterNode->getAttribute<std::string>("beer", beer_str)); EXPECT_EQ(daughtersname, "lucy"); //Oh my god, what happened to Lucy? daughterNode->setAttribute<std::string>("name", "lucifer"); EXPECT_TRUE(daughterNode->getAttribute<std::string>("name", daughtersname)); EXPECT_EQ(daughtersname, "lucifer"); std::map<std::string, std::string> map; daughterNode->getAllAttributes(map); EXPECT_EQ("lucifer", map["name"]); EXPECT_EQ(1, map.size()); } //This test tests deparsing and reading out an xml string TEST(TestDescriptionTreeFromXMLString, Positive) { DescriptionTreeXML::Ptr tree(new DescriptionTreeXML()); //Test three xml cases - field with parameter a, child field b, and empty field c. std::string XMLString("<a par=k><b></b><c/></a>"); tree->initTree(XMLString); DescriptionTreeNode::Ptr root = tree->getRootNode(); DescriptionTreeNode::ConstNodeList childrenOfRoot; root->getChildrenNodes(childrenOfRoot); EXPECT_EQ(root->getType(), "a"); std::string ret; EXPECT_TRUE(root->getAttribute<std::string>("par", ret)); EXPECT_EQ(ret, "k"); //Case sensitive!!! EXPECT_FALSE(root->getAttribute<std::string>("Par", ret)); DescriptionTreeNode::ConstNodeListIterator it = childrenOfRoot.begin(); EXPECT_EQ(it->get()->getType(), "b"); it++; EXPECT_EQ(it->get()->getType(), "c"); } //This test tests out an xml string TEST(TestDescriptionTreeToXMLString, Positive) { DescriptionTreeXML::Ptr tree(new DescriptionTreeXML()); DescriptionTreeNodeXML::Ptr rootNode(new DescriptionTreeNodeXML("root")); DescriptionTreeNodeXML::Ptr firstNode(new DescriptionTreeNodeXML("firstchild")); DescriptionTreeNodeXML::Ptr secondNode(new DescriptionTreeNodeXML("secondchild")); DescriptionTreeNode::Ptr raw = tree->getRootNode(); rootNode = boost::dynamic_pointer_cast<DescriptionTreeNodeXML>(raw); rootNode->addChildNode(firstNode); secondNode->setAttribute<std::string>("param", "value"); ::Eigen::MatrixXd eigen_vector(5,1); eigen_vector << 1.8673, 2., 3., 4., 5.; secondNode->setAttribute<::Eigen::MatrixXd>("vector", eigen_vector); ::Eigen::MatrixXd eigen_matrix(5,2); eigen_matrix << 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.; secondNode->setAttribute<::Eigen::MatrixXd>("matrix", eigen_matrix); rootNode->addChildNode(secondNode); //New test: change vlaue after insertion secondNode->setAttribute<std::string>("param2", "value2"); std::string outString = tree->writeTreeXML(); //std::cout << outString << std::endl; //Now parse again and compare DescriptionTreeXML::Ptr tree2(new DescriptionTreeXML()); //Test three xml cases - field with parameter a, child field b, and empty field c. tree->initTree(outString); DescriptionTreeNode::Ptr root2 = tree->getRootNode(); DescriptionTreeNode::ConstNodeList childrenOfRoot; root2->getChildrenNodes(childrenOfRoot); DescriptionTreeNode::ConstNodeListIterator it = childrenOfRoot.begin(); EXPECT_EQ(it->get()->getType(), "firstchild"); it++; EXPECT_EQ(it->get()->getType(), "secondchild"); std::string ret; EXPECT_TRUE(it->get()->getAttribute<std::string>("param", ret)); EXPECT_EQ(ret, "value"); EXPECT_TRUE(it->get()->getAttribute<std::string>("param2", ret)); EXPECT_EQ(ret, "value2"); ::Eigen::MatrixXd result(0,0); EXPECT_TRUE(it->get()->getAttribute<::Eigen::MatrixXd>("vector", result)); EXPECT_EQ(eigen_vector, result); EXPECT_TRUE(it->get()->getAttribute<::Eigen::MatrixXd>("matrix", result)); EXPECT_EQ(eigen_matrix, result); } <|endoftext|>
<commit_before>// -*- coding:utf-8-unix; -*- #pragma once #include <stdint.h> #include "mpmc/queue.hh" #include "processor.hh" #include "thread.hh" // namespace NAMESPACE { // const size_t kDefaultMaxCPU(32); // class _Task : public mpmc::Node<_Task> { public: virtual bool DoWork() = 0; }; // template<typename Task, size_t kMaxCPU = kDefaultMaxCPU> class Scheduler { public: // typedef Scheduler<Task, kMaxCPU> Self; typedef int Value; // static bool Start(Self& scheduler, size_t threads) { bool done(false); done = scheduler.StartWorkerThread(threads); if (not done) { return false; } // scheduler.InitWorker(&scheduler); return done; } // void Stop() { Value tmp; int done(0); size_t i(0); for(i = 0; i < _worker_threads; ++i) { _worker[i].Signal(kStop); } for(i = 0; i < _worker_threads; ++i) { done = _thread[i].Join(&tmp); if (0 not_eq done) { _thread[i].Cancel(); } } } // void Add(Task* task) { if (nullptr not_eq task) { uint32_t which = Processor<Task>::Current(); _worker[which].Add(task); } } // protected: // enum Status { kInit = 0, kStop = 1, kAbort = 2 }; // void InitWorker(Self* scheduler) { for(size_t i(0); i < _worker_threads; ++i) { _worker[i].Init(scheduler); } } // bool StartWorkerThread(size_t threads) { _worker_threads = threads < kMaxCPU ? threads : kMaxCPU; // int done(0); for(size_t i(0); i < threads; ++i) { done = _thread[i].Run(_worker + i); // create worker thread failed should canncel all if (0 not_eq done) { for(size_t j(0); j < i; ++j) { _thread[j].Cancel(); } return false; } } return true; } // friend class Worker; Task* Steal() { return nullptr; } // private: // class Worker { public: // inline void Init(Self* scheduler) { _status = kInit; _scheduler = scheduler; } // Value* Loop() { while(true) { if(kAbort == _status) { return &_status; } Task* task = _processor.Pop(); if (nullptr == task) { task = _scheduler->Steal(); if (nullptr == task) { if (kStop == _status) { return &_status; } Thread<Worker, Value>::Yield(); continue; } // bool redo = task->DoWork(); if (redo) { _processor.Push(task); } } } // while return nullptr; } // inline void Add(Task* task) { if (kInit == _status) { _processor.Push(task); } } // inline void Signal(int status) { _status = status; } // protected: // private: Self* _scheduler; Processor<Task> _processor; Value _status; }; // Worker _worker[kMaxCPU]; Thread<Worker, Value> _thread[kMaxCPU]; size_t _worker_threads; }; // class Scheduler // } // namespace NAMESPACE <commit_msg>impl Scheduler::Steal<commit_after>// -*- coding:utf-8-unix; -*- #pragma once #include <stdint.h> #include "mpmc/queue.hh" #include "processor.hh" #include "thread.hh" // namespace NAMESPACE { // const uint32_t kDefaultMaxCPU(32); // class _Task : public mpmc::Node<_Task> { public: virtual bool DoWork() = 0; }; // template<typename Task, uint32_t kMaxCPU = kDefaultMaxCPU> class Scheduler { public: // typedef Scheduler<Task, kMaxCPU> Self; typedef int Value; // static bool Start(Self& scheduler, size_t threads) { bool done(false); done = scheduler.StartWorkerThread(threads); if (not done) { return false; } // scheduler.InitWorker(&scheduler); return done; } // void Stop() { Value tmp; int done(0); size_t i(0); for(i = 0; i < _worker_threads; ++i) { _worker[i].Signal(kStop); } for(i = 0; i < _worker_threads; ++i) { done = _thread[i].Join(&tmp); if (0 not_eq done) { _thread[i].Cancel(); } } } // void Add(Task* task) { if (nullptr not_eq task) { uint32_t which = Processor<Task>::Current(); _worker[which].Add(task); } } // protected: // enum Status { kInit = 0, kStop = 1, kAbort = 2 }; // void InitWorker(Self* scheduler) { for(size_t i(0); i < _worker_threads; ++i) { _worker[i].Init(scheduler); } } // bool StartWorkerThread(size_t threads) { _worker_threads = threads < kMaxCPU ? threads : kMaxCPU; // int done(0); for(size_t i(0); i < threads; ++i) { _last_victim[i] = i; done = _thread[i].Run(_worker + i); // create worker thread failed should canncel all if (0 not_eq done) { for(size_t j(0); j < i; ++j) { _thread[j].Cancel(); } return false; } } return true; } // friend class Worker; Task* Steal() { uint32_t which = Processor<Task>::Current(); uint32_t victim = Self::ChooseVictim(which); Task* task = _worker[victim].Steal(); return task; } // uint32_t ChooseVictim(uint32_t which) { uint32_t victim = _last_victim[which]; if (++victim == _worker_threads) { victim = 0; } for (; victim < _worker_threads; ++victim) { if (which == victim) { continue; } _last_victim[which] = victim; break; } return victim; } // private: // class Worker { public: // inline void Init(Self* scheduler) { _status = kInit; _scheduler = scheduler; } // inline Task* Steal() { return _processor.Pop(); } // Value* Loop() { while(true) { if(kAbort == _status) { return &_status; } Task* task = _processor.Pop(); if (nullptr == task) { task = _scheduler->Steal(); if (nullptr == task) { if (kStop == _status) { return &_status; } Thread<Worker, Value>::Yield(); continue; } // bool redo = task->DoWork(); if (redo) { _processor.Push(task); } } } // while return nullptr; } // inline void Add(Task* task) { if (kInit == _status) { _processor.Push(task); } } // inline void Signal(int status) { _status = status; } // protected: // private: Self* _scheduler; Processor<Task> _processor; Value _status; }; // Worker _worker[kMaxCPU]; Thread<Worker, Value> _thread[kMaxCPU]; uint32_t _last_victim[kMaxCPU]; uint32_t _worker_threads; }; // class Scheduler // } // namespace NAMESPACE <|endoftext|>
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "../bse.hh" #include "v8bse.cc" #include <node.h> #include <uv.h> // v8pp binding for Bse static V8stub *bse_v8stub = NULL; // event loop integration static uv_poll_t bse_uv_watcher; static Rapicorn::Aida::ClientConnectionP bse_client_connection; static Bse::ServerH bse_server; // register bindings and start Bse static void v8bse_register_module (v8::Local<v8::Object> exports) { assert (bse_v8stub == NULL); v8::Isolate *const isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope (isolate); // start Bse Bse::String bseoptions = Bse::string_format ("debug-extensions=%d", 0); Bse::init_async (NULL, NULL, "BEAST", Bse::string_split (bseoptions, ":")); // fetch server handle assert (bse_server == NULL); assert (bse_client_connection == NULL); bse_client_connection = Bse::init_server_connection(); assert (bse_client_connection != NULL); bse_server = Bse::init_server_instance(); assert (bse_server != NULL); // hook BSE connection into libuv event loop uv_loop_t *loop = uv_default_loop(); uv_poll_init (loop, &bse_uv_watcher, bse_client_connection->notify_fd()); auto bse_uv_callback = [] (uv_poll_t *watcher, int status, int revents) { if (bse_client_connection && bse_client_connection->pending()) bse_client_connection->dispatch(); }; uv_poll_start (&bse_uv_watcher, UV_READABLE, bse_uv_callback); // hook BSE connection into GLib event loop Bse::AidaGlibSource *source = Bse::AidaGlibSource::create (bse_client_connection.get()); g_source_set_priority (source, G_PRIORITY_DEFAULT); g_source_attach (source, g_main_context_default()); // register v8stub v8::Local<v8::Context> context = isolate->GetCurrentContext(); bse_v8stub = new V8stub (isolate); v8::Local<v8::Object> module_instance = bse_v8stub->module_.new_instance(); v8::Maybe<bool> ok = exports->SetPrototype (context, module_instance); assert (ok.FromJust() == true); } // node.js registration NODE_MODULE (v8bse, v8bse_register_module); <commit_msg>V8BSE: export bse.server object<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "../bse.hh" #include "v8bse.cc" #include <node.h> #include <uv.h> // v8pp binding for Bse static V8stub *bse_v8stub = NULL; // event loop integration static uv_poll_t bse_uv_watcher; static Rapicorn::Aida::ClientConnectionP bse_client_connection; static Bse::ServerH bse_server; // register bindings and start Bse static void v8bse_register_module (v8::Local<v8::Object> exports) { assert (bse_v8stub == NULL); v8::Isolate *const isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope (isolate); // start Bse Bse::String bseoptions = Bse::string_format ("debug-extensions=%d", 0); Bse::init_async (NULL, NULL, "BEAST", Bse::string_split (bseoptions, ":")); // fetch server handle assert (bse_server == NULL); assert (bse_client_connection == NULL); bse_client_connection = Bse::init_server_connection(); assert (bse_client_connection != NULL); bse_server = Bse::init_server_instance(); assert (bse_server != NULL); // hook BSE connection into libuv event loop uv_loop_t *loop = uv_default_loop(); uv_poll_init (loop, &bse_uv_watcher, bse_client_connection->notify_fd()); auto bse_uv_callback = [] (uv_poll_t *watcher, int status, int revents) { if (bse_client_connection && bse_client_connection->pending()) bse_client_connection->dispatch(); }; uv_poll_start (&bse_uv_watcher, UV_READABLE, bse_uv_callback); // hook BSE connection into GLib event loop Bse::AidaGlibSource *source = Bse::AidaGlibSource::create (bse_client_connection.get()); g_source_set_priority (source, G_PRIORITY_DEFAULT); g_source_attach (source, g_main_context_default()); // register v8stub v8::Local<v8::Context> context = isolate->GetCurrentContext(); bse_v8stub = new V8stub (isolate); v8::Local<v8::Object> module_instance = bse_v8stub->module_.new_instance(); v8::Maybe<bool> ok = exports->SetPrototype (context, module_instance); assert (ok.FromJust() == true); // export server handle V8ppType_BseServer &class_ = bse_v8stub->BseServer_class_; v8::Local<v8::Object> v8_server = class_.import_external (isolate, new Bse::ServerH (bse_server)); module_instance->DefineOwnProperty (context, v8pp::to_v8 (isolate, "server"), v8_server, v8::PropertyAttribute (v8::ReadOnly | v8::DontDelete)); } // node.js registration NODE_MODULE (v8bse, v8bse_register_module); <|endoftext|>
<commit_before>/** * @page shaders Shaders * @section tzsl Topaz Shader Language * @section Introduction * TZSL is a high-level shader language with a syntax very similar to that of GLSL. A tool named tzslc ships with the engine, which can be used to build tzsl shaders to output SPIRV, GLSL shaders or SPIRV encoded within a C++ header. * * TZSL Shaders come in three types: * - Vertex Shaders, which specify the locations of individual vertices. * - There are no vertex buffers, so vertex-pulling is a must. * - Index buffers are planned, but not yet implemented. For the time being you must perform index-pulling aswell. * - Fragment Shaders, which processes fragments into a set of colours and optionally depth value. * - Compute Shaders, which can be used to perform general-purpose computation on the GPU. * - Compute Shaders are not yet implemented. However, it is high on the priority list. * * TZSL Shaders have first-class support in the engine's build system. When specifying your application in CMake, you can specify tzsl shader files. When the application needs to be built, the shaders are compiled into specially-encoded C++ headers which you can include in your application at compile-time. This is known as a TZSL Header Import. * * @section Language * @subsection Inputs * Fragment shaders may have inputs. These are variable passed from the output of a vertex shader. Because Topaz does not deal with input state (there are no vertex buffers), vertex shaders cannot have inputs. Compute shaders cannot have inputs either, but that is normal. Every input must have an index, type and name. * * * Syntax: * `input(id = x) variable_type variable_name;` * Example: * `input(id = 0) vec2 texcoord;` * @subsection Outputs * Vertex and fragment shaders may have any number of outputs. These are similar to `out` variables from GLSL, although the syntax is slightly different. Every output must have an index, type and name. * * Syntax: * `output(id = x) variable_type variable_name;` * Example: * `output(id = 0) vec3 frag_colour;` * @subsection Resources * When writing a shader, you will know about the shader resources it has access to. You might be used to the following syntaxes in OpenGL: * ```c * uniform sampler2D my_image; * layout(binding = 0) uniform MyUniformBuffer * { * ... * } buf; * ``` * Note that the syntax for specifying image and buffer resources are quite different. Because image and buffer resources are first-class objects as far as Topaz renderers are concerned, the syntax is unified and obvious: * ```c * resource(id = 0) const texture my_image; * resource(id = 0) const buffer MyUniformBuffer * { * ... * } buf; * ``` * Note that specifying resource ids for shader resources is mandatory, regardless of resource type. The resource id is constant and corresponds to the @ref tz::gl::ResourceHandle when being specified to a renderer. This means that resources have unique identifiers. That is, if a vertex shader specifies an image resource at id 0, and again in a fragment shader (within the same shader program), they both refer to the same resource. * * Note: The example above is actually ill-formed -- An image and buffer resource are specified, but they share the same id which is impossible; a resource is either a buffer or an image resource, never both. * @subsection preproc Preprocessor Definitions * A number of preprocessor definitions are guaranteed to be exist for all TZSL shaders. These are always defined, but their value depends on the build parameters of the target program. * * Below are the defines whose value depends on the render-api: * <table> * <tr> * <th>Define</th> * <th>Value (OpenGL)</th> * <th>Value (Vulkan)</th> * </tr> * <tr> * <td>TZ_VULKAN</td> * <td style="text-align: center;">0</td> * <td style="text-align: center;">1</td> * </tr> * <tr> * <td>TZ_OGL</td> * <td style="text-align: center;">1</td> * <td style="text-align: center;">0</td> * </tr> * </table> * * Below are the defines whose value depends on the build-config: * <table> * <tr> * <th>Define</th> * <th>Value (Debug)</th> * <th>Value (Release)</th> * </tr> * <tr> * <td>TZ_DEBUG</td> * <td style="text-align: center;">1</td> * <td style="text-align: center;">0</td> * </tr> * </table> * Just for clarity, these are preprocessor definitions as in GLSL or C. These are useful if you want your shader to act differently on certain build configurations, but without having to write different shaders. * * @subsubsection ex0 Example Fragment Shader * ```c * shader(type = fragment); * output(id = 0) vec4 frag_colour; * * void main() * { * // Output is a solid colour. Red if we're on Vulkan, otherwise white. * #if TZ_VULKAN * frag_colour = vec4(1.0, 0.0, 0.0, 1.0); * #else * frag_colour = vec4(1.0, 1.0, 1.0, 1.0); * #endif * } * ``` * @section stypes IO Blocks * Below are the input and output blocks for each programmable shader type. Each shader stage has a fixed-set of input and output variables, in the `in::` and `out::` namespaces respectively. These are not the same as input and output language specifiers. * <details> * <summary>Vertex Shader</summary> * <table> * <tr> * <th>Variable</th> * <th>GLSL Equivalent</th> * </tr> * <tr> * <td>in::vertex_id</td> * <td>gl_VertexID</td> * </tr> * <tr> * <td>in::instance_id</td> * <td>gl_InstanceID</td> * </tr> * <tr> * <td>out::position</td> * <td>gl_Position</td> * </tr> * </table> * </details> * * <details> * <summary>Fragment Shader</summary> * <table> * <tr> * <th>Variable</th> * <th>GLSL Equivalent</th> * </tr> * <tr> * <td>in::fragment_coord</td> * <td>gl_FragCoord</td> * </tr> * <tr> * <td>out::fragment_depth</td> * <td>gl_FragDepth</td> * </tr> * </table> * </details> * * <details> * <summary>Compute Shader</summary> * <table> * <tr> * <th>Variable</th> * <th>GLSL Equivalent</th> * </tr> * <tr> * <td>in::workgroup_count</td> * <td>gl_NumWorkGroups</td> * </tr> * <tr> * <td>in::workgroup_id</td> * <td>gl_WorkGroupID</td> * </tr> * <tr> * <td>in::local_id</td> * <td>gl_LocalInvocationID</td> * </tr> * <tr> * <td>in::global_id</td> * <td>gl_GlobalInvocationID</td> * </tr> * </table> * </details> * * @section bif Built-in Functions * @subsection bif_printf tz_printf * `void tz_printf(fmt: string-literal, ...)` * @note This is only available for Vulkan Debug builds. Otherwise, compiles down to no-op. * * Specifies a debug-printf statement. The syntax is c-like. Intuitively you might expect the printed output to be sent to the host program's stdout. This is not the case. At present, you can only view these in graphics debuggers which support the vulkan `debugPrintfEXT`, namely RenderDoc. * * The frequency of this output logically matches that of the context. If for example you're invoking `tz_printf` in a vertex shader's main function, a message will be emitted for each vertex drawn. * * To view the output message in RenderDoc: * <ol> * <li>Capture a frame using a renderer that uses a shader with this debug output. Ensure the host program is Vulkan Debug.</li> * <li>In the 'Event Browser', navigate to the draw call that invokes the shader.</li> * <li>You should see 'X msg(s)' annotated on the draw call. Click on this to see each printf invocation.</li> * </ol> * @subsubsection tz_printf_params Parameters * The parameters are much like C `printf`: * - String-literal specifying how to interpret the data. Regarding scalar types, format modifiers match that of C's `printf` function. However, format modifiers also exist for the built-in GLSL vector types. * - Format for specifier is "%"precision <d, i, o, u, x, X, a, A, e, E, f, F, g, G, ul, lu, lx> * - Format for vector specifier is "%"precision"v" [2, 3, 4] [specifiers above] * - Arguments specifying data to print. There must be an entry for each format modifier within the format string. Like `printf`, if no modifiers were specified in the format string, this parameter can be omitted. * @subsubsection debug_printf_example Examples * Here are a few example usages: * ```c * float myfloat = 3.1415f; * vec4 floatvec = vec4(1.2f, 2.2f, 3.2f, 4.2f); * uint64_t bigvar = 0x2000000000000001ul; * * tz_printf("Here's a float value with full precision %f", myfloat); * tz_printf("Here's a float value to 2 decimal places %1.2f", myfloat); * tz_printf("Here's a vector of floats %1.2v4f", floatvec); * tz_printf("Unsigned long as decimal %lu and as hex 0x%lx", bigvar, bigvar); * ``` * Outputs: * ```diff * Here's a float value with full precision 3.141500 * Here's a float value to 2 decimal places 3.14 * Here's a vector of floats 1.20, 2.20, 3.20, 4.20 * Unsigned long as decimal 2305843009213693953 and as hex 0x2000000000000001 * ``` * * @section header_imports TZSL Header Imports * Note that this feature is optional. If you don't like it, you can completely ignore it. * * * Say you have a project structure similar to the file tree below: * * <table> * <tr> * <th>Projects/MyGame</th> * </tr> * <tr> * <td>CMakeLists.txt</td> * </tr> * <tr> * <td>main.cpp</td> * </tr> * <tr> * <td>my_shader.vertex.tzsl</td> * </tr> * <tr> * <td>my_shader.fragment.tzsl</td> * </tr> * </table> * * Using a header import, you can access the shaders at compile-time within main.cpp. * @subsubsection cml_example CMakeLists.txt * ```cmake * add_app( * TARGET MyGame * SOURCE_FILES main.cpp * SHADER_SOURCES * my_shader.vertex.tzsl * my_shader.fragment.tzsl * ) * ``` * * @subsubsection maincpp main.cpp * ```cpp * #include "gl/imported_shaders.hpp" * #include <string_view> * * // Includes the compiled tzsl c++ header within this translation unit. * // NOTE: This is only doable if you specified the shader files within `add_application` in the build system. * #include ImportedShaderHeader(my_shader, vertex) * #include ImportedShaderHeader(my_shader, fragment) * int main() * { * constexpr std::string_view vtx_src = ImportedShaderSource(my_shader, vertex); * constexpr std::string_view frg_src = ImportedShaderSource(my_shader, fragment); * // Note: The contents of the string depend on the current render-api. However, this is guaranteed to be compatible with tz::gl::ShaderInfo::set_shader(...). * // For the curious: In Vulkan, the string contains SPIRV. In OpenGL, the string contains GLSL source. * } * ``` * * * <hr> * @section rwe Example Shader: tz_dynamic_triangle_demo.fragment.tzsl * The following is the fragment shader used by `tz_dynamic_triangle_demo`: * @include gl/tz_dynamic_triangle_demo.fragment.tzsl * * @subsection rwe_analysis Analysis * - The shader contains a type declaration at the top, like all shaders. This informs tzslc that this is a fragment shader. * - The shader uses a single resource, an array of samplers with index 1. * - The shader has one input and one output, both with index 0. * - As you might expect, output 0 goes to the colour attachment 0, and input 0 is the first output from the vertex shader. */ <commit_msg>* Amend shader documentation to remove the part which said compute shaders are NYI<commit_after>/** * @page shaders Shaders * @section tzsl Topaz Shader Language * @section Introduction * TZSL is a high-level shader language with a syntax very similar to that of GLSL. A tool named tzslc ships with the engine, which can be used to build tzsl shaders to output SPIRV, GLSL shaders or SPIRV encoded within a C++ header. * * TZSL Shaders come in three types: * - Vertex Shaders, which specify the locations of individual vertices. * - There are no vertex buffers, so vertex-pulling is a must. * - Index buffers are planned, but not yet implemented. For the time being you must perform index-pulling aswell. * - Fragment Shaders, which processes fragments into a set of colours and optionally depth value. * - Compute Shaders, which can be used to perform general-purpose computation on the GPU. * * TZSL Shaders have first-class support in the engine's build system. When specifying your application in CMake, you can specify tzsl shader files. When the application needs to be built, the shaders are compiled into specially-encoded C++ headers which you can include in your application at compile-time. This is known as a TZSL Header Import. * * @section Language * @subsection Inputs * Fragment shaders may have inputs. These are variable passed from the output of a vertex shader. Because Topaz does not deal with input state (there are no vertex buffers), vertex shaders cannot have inputs. Compute shaders cannot have inputs either, but that is normal. Every input must have an index, type and name. * * * Syntax: * `input(id = x) variable_type variable_name;` * Example: * `input(id = 0) vec2 texcoord;` * @subsection Outputs * Vertex and fragment shaders may have any number of outputs. These are similar to `out` variables from GLSL, although the syntax is slightly different. Every output must have an index, type and name. * * Syntax: * `output(id = x) variable_type variable_name;` * Example: * `output(id = 0) vec3 frag_colour;` * @subsection Resources * When writing a shader, you will know about the shader resources it has access to. You might be used to the following syntaxes in OpenGL: * ```c * uniform sampler2D my_image; * layout(binding = 0) uniform MyUniformBuffer * { * ... * } buf; * ``` * Note that the syntax for specifying image and buffer resources are quite different. Because image and buffer resources are first-class objects as far as Topaz renderers are concerned, the syntax is unified and obvious: * ```c * resource(id = 0) const texture my_image; * resource(id = 0) const buffer MyUniformBuffer * { * ... * } buf; * ``` * Note that specifying resource ids for shader resources is mandatory, regardless of resource type. The resource id is constant and corresponds to the @ref tz::gl::ResourceHandle when being specified to a renderer. This means that resources have unique identifiers. That is, if a vertex shader specifies an image resource at id 0, and again in a fragment shader (within the same shader program), they both refer to the same resource. * * Note: The example above is actually ill-formed -- An image and buffer resource are specified, but they share the same id which is impossible; a resource is either a buffer or an image resource, never both. * @subsection preproc Preprocessor Definitions * A number of preprocessor definitions are guaranteed to be exist for all TZSL shaders. These are always defined, but their value depends on the build parameters of the target program. * * Below are the defines whose value depends on the render-api: * <table> * <tr> * <th>Define</th> * <th>Value (OpenGL)</th> * <th>Value (Vulkan)</th> * </tr> * <tr> * <td>TZ_VULKAN</td> * <td style="text-align: center;">0</td> * <td style="text-align: center;">1</td> * </tr> * <tr> * <td>TZ_OGL</td> * <td style="text-align: center;">1</td> * <td style="text-align: center;">0</td> * </tr> * </table> * * Below are the defines whose value depends on the build-config: * <table> * <tr> * <th>Define</th> * <th>Value (Debug)</th> * <th>Value (Release)</th> * </tr> * <tr> * <td>TZ_DEBUG</td> * <td style="text-align: center;">1</td> * <td style="text-align: center;">0</td> * </tr> * </table> * Just for clarity, these are preprocessor definitions as in GLSL or C. These are useful if you want your shader to act differently on certain build configurations, but without having to write different shaders. * * @subsubsection ex0 Example Fragment Shader * ```c * shader(type = fragment); * output(id = 0) vec4 frag_colour; * * void main() * { * // Output is a solid colour. Red if we're on Vulkan, otherwise white. * #if TZ_VULKAN * frag_colour = vec4(1.0, 0.0, 0.0, 1.0); * #else * frag_colour = vec4(1.0, 1.0, 1.0, 1.0); * #endif * } * ``` * @section stypes IO Blocks * Below are the input and output blocks for each programmable shader type. Each shader stage has a fixed-set of input and output variables, in the `in::` and `out::` namespaces respectively. These are not the same as input and output language specifiers. * <details> * <summary>Vertex Shader</summary> * <table> * <tr> * <th>Variable</th> * <th>GLSL Equivalent</th> * </tr> * <tr> * <td>in::vertex_id</td> * <td>gl_VertexID</td> * </tr> * <tr> * <td>in::instance_id</td> * <td>gl_InstanceID</td> * </tr> * <tr> * <td>out::position</td> * <td>gl_Position</td> * </tr> * </table> * </details> * * <details> * <summary>Fragment Shader</summary> * <table> * <tr> * <th>Variable</th> * <th>GLSL Equivalent</th> * </tr> * <tr> * <td>in::fragment_coord</td> * <td>gl_FragCoord</td> * </tr> * <tr> * <td>out::fragment_depth</td> * <td>gl_FragDepth</td> * </tr> * </table> * </details> * * <details> * <summary>Compute Shader</summary> * <table> * <tr> * <th>Variable</th> * <th>GLSL Equivalent</th> * </tr> * <tr> * <td>in::workgroup_count</td> * <td>gl_NumWorkGroups</td> * </tr> * <tr> * <td>in::workgroup_id</td> * <td>gl_WorkGroupID</td> * </tr> * <tr> * <td>in::local_id</td> * <td>gl_LocalInvocationID</td> * </tr> * <tr> * <td>in::global_id</td> * <td>gl_GlobalInvocationID</td> * </tr> * </table> * </details> * * @section bif Built-in Functions * @subsection bif_printf tz_printf * `void tz_printf(fmt: string-literal, ...)` * @note This is only available for Vulkan Debug builds. Otherwise, compiles down to no-op. * * Specifies a debug-printf statement. The syntax is c-like. Intuitively you might expect the printed output to be sent to the host program's stdout. This is not the case. At present, you can only view these in graphics debuggers which support the vulkan `debugPrintfEXT`, namely RenderDoc. * * The frequency of this output logically matches that of the context. If for example you're invoking `tz_printf` in a vertex shader's main function, a message will be emitted for each vertex drawn. * * To view the output message in RenderDoc: * <ol> * <li>Capture a frame using a renderer that uses a shader with this debug output. Ensure the host program is Vulkan Debug.</li> * <li>In the 'Event Browser', navigate to the draw call that invokes the shader.</li> * <li>You should see 'X msg(s)' annotated on the draw call. Click on this to see each printf invocation.</li> * </ol> * @subsubsection tz_printf_params Parameters * The parameters are much like C `printf`: * - String-literal specifying how to interpret the data. Regarding scalar types, format modifiers match that of C's `printf` function. However, format modifiers also exist for the built-in GLSL vector types. * - Format for specifier is "%"precision <d, i, o, u, x, X, a, A, e, E, f, F, g, G, ul, lu, lx> * - Format for vector specifier is "%"precision"v" [2, 3, 4] [specifiers above] * - Arguments specifying data to print. There must be an entry for each format modifier within the format string. Like `printf`, if no modifiers were specified in the format string, this parameter can be omitted. * @subsubsection debug_printf_example Examples * Here are a few example usages: * ```c * float myfloat = 3.1415f; * vec4 floatvec = vec4(1.2f, 2.2f, 3.2f, 4.2f); * uint64_t bigvar = 0x2000000000000001ul; * * tz_printf("Here's a float value with full precision %f", myfloat); * tz_printf("Here's a float value to 2 decimal places %1.2f", myfloat); * tz_printf("Here's a vector of floats %1.2v4f", floatvec); * tz_printf("Unsigned long as decimal %lu and as hex 0x%lx", bigvar, bigvar); * ``` * Outputs: * ```diff * Here's a float value with full precision 3.141500 * Here's a float value to 2 decimal places 3.14 * Here's a vector of floats 1.20, 2.20, 3.20, 4.20 * Unsigned long as decimal 2305843009213693953 and as hex 0x2000000000000001 * ``` * * @section header_imports TZSL Header Imports * Note that this feature is optional. If you don't like it, you can completely ignore it. * * * Say you have a project structure similar to the file tree below: * * <table> * <tr> * <th>Projects/MyGame</th> * </tr> * <tr> * <td>CMakeLists.txt</td> * </tr> * <tr> * <td>main.cpp</td> * </tr> * <tr> * <td>my_shader.vertex.tzsl</td> * </tr> * <tr> * <td>my_shader.fragment.tzsl</td> * </tr> * </table> * * Using a header import, you can access the shaders at compile-time within main.cpp. * @subsubsection cml_example CMakeLists.txt * ```cmake * add_app( * TARGET MyGame * SOURCE_FILES main.cpp * SHADER_SOURCES * my_shader.vertex.tzsl * my_shader.fragment.tzsl * ) * ``` * * @subsubsection maincpp main.cpp * ```cpp * #include "gl/imported_shaders.hpp" * #include <string_view> * * // Includes the compiled tzsl c++ header within this translation unit. * // NOTE: This is only doable if you specified the shader files within `add_application` in the build system. * #include ImportedShaderHeader(my_shader, vertex) * #include ImportedShaderHeader(my_shader, fragment) * int main() * { * constexpr std::string_view vtx_src = ImportedShaderSource(my_shader, vertex); * constexpr std::string_view frg_src = ImportedShaderSource(my_shader, fragment); * // Note: The contents of the string depend on the current render-api. However, this is guaranteed to be compatible with tz::gl::ShaderInfo::set_shader(...). * // For the curious: In Vulkan, the string contains SPIRV. In OpenGL, the string contains GLSL source. * } * ``` * * * <hr> * @section rwe Example Shader: tz_dynamic_triangle_demo.fragment.tzsl * The following is the fragment shader used by `tz_dynamic_triangle_demo`: * @include gl/tz_dynamic_triangle_demo.fragment.tzsl * * @subsection rwe_analysis Analysis * - The shader contains a type declaration at the top, like all shaders. This informs tzslc that this is a fragment shader. * - The shader uses a single resource, an array of samplers with index 1. * - The shader has one input and one output, both with index 0. * - As you might expect, output 0 goes to the colour attachment 0, and input 0 is the first output from the vertex shader. */ <|endoftext|>
<commit_before>#include <cmath> #include <array> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <sys/stat.h> #include "simulation.h" #include "codes/codes.h" namespace detail { inline bool file_exists(const std::string &fname) { struct stat buf; return (stat(fname.c_str(), &buf) != -1); } } static std::array<double, 131> rates{ { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872, 0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938, 0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974, 0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989, 0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 } }; static std::array<double, 131> limits = { { -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316, -1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028, -0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724, -0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394, -0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032, 0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374, 0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844, 0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412, 1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108, 2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009, 3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906, 4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841, 4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615, 5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495, 6.651, 6.837, 7.072, 7.378, 7.864 } }; static constexpr double ebno(const double rate) { if (rate <= 0.800) { const size_t index = static_cast<size_t>(rate * 100); return limits.at(index); } else if (rate >= 0.999) { return limits.back(); } else { const size_t offset = 80; const size_t index = static_cast<size_t>(std::distance( std::cbegin(rates), std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1, [=](const double r) { return r >= rate; }))); return limits.at(index); } } static std::ofstream open_file(const std::string &fname) { if (detail::file_exists(fname)) { std::ostringstream os; os << "File " << fname << " already exists."; throw std::runtime_error(os.str()); } std::ofstream log_file(fname.c_str(), std::ofstream::out); return log_file; } double awgn_simulation::sigma(const double eb_no) const { return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0))); } awgn_simulation::awgn_simulation(const class decoder &decoder_, const double step_, const uint64_t seed_) : decoder(decoder_), step(step_), seed(seed_) {} void awgn_simulation::operator()() { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "ebno" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step); const double start = (tmp + (1.0 / step)) * step; const double max = std::max(8.0, start) + step / 2; /* TODO round ebno() up to next step */ for (double eb_no = start; eb_no < max; eb_no += step) { std::normal_distribution<float> distribution( 1.0, static_cast<float>(sigma(eb_no))); auto noise = std::bind(std::ref(distribution), std::ref(generator)); size_t word_errors = 0; size_t samples = 10000; std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": E_b/N_0 = " << eb_no << " with " << samples << " … "; std::cout.flush(); auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < samples; i++) { std::generate(std::begin(b), std::end(b), noise); try { auto result = decoder.correct(b); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } auto end_time = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>( end_time - start_time).count(); std::cout << seconds << " s" << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << eb_no << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << static_cast<double>(word_errors) / samples << std::endl; } } bitflip_simulation::bitflip_simulation(const class decoder &decoder_, const size_t errors_) : decoder(decoder_), errors(errors_) {} void bitflip_simulation::operator()() const { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "errors" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t length = decoder.n(); for (size_t error = 0; error <= errors; error++) { size_t patterns = 0; size_t word_errors = 0; std::vector<int> b; std::fill_n(std::back_inserter(b), length - error, 0); std::fill_n(std::back_inserter(b), error, 1); std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": errors = " << error << " … "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); do { std::vector<float> x; x.reserve(length); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x), [](const auto &bit) { return -2 * bit + 1; }); patterns++; try { auto result = decoder.correct(x); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } while (std::next_permutation(std::begin(b), std::end(b))); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s " << word_errors << " " << patterns << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << error << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / patterns << std::endl; } } std::atomic_bool thread_pool::running{ true }; std::mutex thread_pool::lock; std::condition_variable thread_pool::cv; std::list<std::function<void(void)> > thread_pool::queue; thread_pool::thread_pool() { for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) { pool.emplace_back(std::bind(&thread_pool::thread_function, this)); } } thread_pool::~thread_pool() { running = false; cv.notify_all(); for (auto &&t : pool) t.join(); } void thread_pool::thread_function() const { for (;;) { bool have_work = false; std::function<void(void)> work; { std::unique_lock<std::mutex> m(lock); /* * empty running wait * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 */ cv.wait(m, [&]() { return !(queue.empty() && running); }); if (!queue.empty()) { work = queue.front(); queue.pop_front(); have_work = true; } } if (have_work) { try { work(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else if (!running) { return; } } } <commit_msg>Remove unsused variable<commit_after>#include <cmath> #include <array> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <sys/stat.h> #include "simulation.h" #include "codes/codes.h" namespace detail { inline bool file_exists(const std::string &fname) { struct stat buf; return (stat(fname.c_str(), &buf) != -1); } } static std::array<double, 131> rates{ { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872, 0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938, 0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974, 0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989, 0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 } }; static std::array<double, 131> limits = { { -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316, -1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028, -0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724, -0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394, -0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032, 0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374, 0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844, 0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412, 1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108, 2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009, 3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906, 4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841, 4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615, 5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495, 6.651, 6.837, 7.072, 7.378, 7.864 } }; static constexpr double ebno(const double rate) { if (rate <= 0.800) { const size_t index = static_cast<size_t>(rate * 100); return limits.at(index); } else if (rate >= 0.999) { return limits.back(); } else { const size_t offset = 80; const size_t index = static_cast<size_t>(std::distance( std::cbegin(rates), std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1, [=](const double r) { return r >= rate; }))); return limits.at(index); } } static std::ofstream open_file(const std::string &fname) { if (detail::file_exists(fname)) { std::ostringstream os; os << "File " << fname << " already exists."; throw std::runtime_error(os.str()); } std::ofstream log_file(fname.c_str(), std::ofstream::out); return log_file; } double awgn_simulation::sigma(const double eb_no) const { return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0))); } awgn_simulation::awgn_simulation(const class decoder &decoder_, const double step_, const uint64_t seed_) : decoder(decoder_), step(step_), seed(seed_) {} void awgn_simulation::operator()() { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "ebno" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step); const double start = (tmp + (1.0 / step)) * step; const double max = std::max(8.0, start) + step / 2; /* TODO round ebno() up to next step */ for (double eb_no = start; eb_no < max; eb_no += step) { std::normal_distribution<float> distribution( 1.0, static_cast<float>(sigma(eb_no))); auto noise = std::bind(std::ref(distribution), std::ref(generator)); size_t word_errors = 0; size_t samples = 10000; std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": E_b/N_0 = " << eb_no << " with " << samples << " … "; std::cout.flush(); auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < samples; i++) { std::generate(std::begin(b), std::end(b), noise); try { auto result = decoder.correct(b); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } auto end_time = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>( end_time - start_time).count(); std::cout << seconds << " s" << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << eb_no << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << static_cast<double>(word_errors) / samples << std::endl; } } bitflip_simulation::bitflip_simulation(const class decoder &decoder_, const size_t errors_) : decoder(decoder_), errors(errors_) {} void bitflip_simulation::operator()() const { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); log_file << std::setw(ebno_width + 1) << "errors" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t length = decoder.n(); for (size_t error = 0; error <= errors; error++) { size_t patterns = 0; size_t word_errors = 0; std::vector<int> b; std::fill_n(std::back_inserter(b), length - error, 0); std::fill_n(std::back_inserter(b), error, 1); std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": errors = " << error << " … "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); do { std::vector<float> x; x.reserve(length); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x), [](const auto &bit) { return -2 * bit + 1; }); patterns++; try { auto result = decoder.correct(x); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } while (std::next_permutation(std::begin(b), std::end(b))); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s " << word_errors << " " << patterns << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << error << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / patterns << std::endl; } } std::atomic_bool thread_pool::running{ true }; std::mutex thread_pool::lock; std::condition_variable thread_pool::cv; std::list<std::function<void(void)> > thread_pool::queue; thread_pool::thread_pool() { for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) { pool.emplace_back(std::bind(&thread_pool::thread_function, this)); } } thread_pool::~thread_pool() { running = false; cv.notify_all(); for (auto &&t : pool) t.join(); } void thread_pool::thread_function() const { for (;;) { bool have_work = false; std::function<void(void)> work; { std::unique_lock<std::mutex> m(lock); /* * empty running wait * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 */ cv.wait(m, [&]() { return !(queue.empty() && running); }); if (!queue.empty()) { work = queue.front(); queue.pop_front(); have_work = true; } } if (have_work) { try { work(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else if (!running) { return; } } } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Libmemcached Client and Server * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <mem_config.h> #include <libtest/test.hpp> using namespace libtest; #include <libmemcached-1.0/memcached.h> #include <libmemcachedutil-1.0/util.h> #include "tests/touch.h" static test_return_t pre_touch(memcached_st *memc) { test_compare(MEMCACHED_SUCCESS, memcached_version(memc)); test_skip(true, libmemcached_util_version_check(memc, 1, 4, 8)); return TEST_SUCCESS; } test_return_t test_memcached_touch(memcached_st *memc) { test_skip(TEST_SUCCESS, pre_touch(memc)); size_t len; uint32_t flags; memcached_return rc; test_null(memcached_get(memc, test_literal_param(__func__), &len, &flags, &rc)); test_zero(len); test_compare(MEMCACHED_NOTFOUND, rc); test_compare(MEMCACHED_SUCCESS, memcached_set(memc, test_literal_param(__func__), test_literal_param("touchval"), 2, 0)); { char *value= memcached_get(memc, test_literal_param(__func__), &len, &flags, &rc); test_compare(8U, test_literal_param_size("touchval")); test_true(value); test_strcmp(value, "touchval"); test_compare(MEMCACHED_SUCCESS, rc); free(value); } rc= memcached_touch(memc, test_literal_param(__func__), 60 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); rc= memcached_touch(memc, test_literal_param(__func__), 60 *60 *24 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); rc= memcached_exist(memc, test_literal_param(__func__)); ASSERT_EQ_(MEMCACHED_NOTFOUND, rc, "%s", memcached_last_error_message(memc)); return TEST_SUCCESS; } test_return_t test_memcached_touch_by_key(memcached_st *memc) { test_skip(TEST_SUCCESS, pre_touch(memc)); size_t len; uint32_t flags; memcached_return rc; test_null(memcached_get_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), &len, &flags, &rc)); test_zero(len); test_compare(MEMCACHED_NOTFOUND, rc); test_compare(MEMCACHED_SUCCESS, memcached_set_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), test_literal_param("touchval"), 2, 0)); { char *value= memcached_get_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), &len, &flags, &rc); test_compare(8U, test_literal_param_size("touchval")); test_true(value); test_strcmp(value, "touchval"); test_compare(MEMCACHED_SUCCESS, rc); free(value); } rc= memcached_touch_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), 60 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); rc= memcached_touch_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), 60 *60 *24 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); rc= memcached_exist_by_key(memc, test_literal_param("grouping_key"),test_literal_param(__func__)); ASSERT_EQ_(MEMCACHED_NOTFOUND, rc, "%s", memcached_last_error_message(memc)); return TEST_SUCCESS; } <commit_msg>Only use touch with the latest version of memcached.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Libmemcached Client and Server * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <mem_config.h> #include <libtest/test.hpp> using namespace libtest; #include <libmemcached-1.0/memcached.h> #include <libmemcachedutil-1.0/util.h> #include "tests/touch.h" static test_return_t pre_touch(memcached_st *memc) { test_compare(MEMCACHED_SUCCESS, memcached_version(memc)); test_skip(true, libmemcached_util_version_check(memc, 1, 4, 8)); return TEST_SUCCESS; } test_return_t test_memcached_touch(memcached_st *memc) { test_skip(TEST_SUCCESS, pre_touch(memc)); size_t len; uint32_t flags; memcached_return rc; test_null(memcached_get(memc, test_literal_param(__func__), &len, &flags, &rc)); test_zero(len); test_compare(MEMCACHED_NOTFOUND, rc); test_compare(MEMCACHED_SUCCESS, memcached_set(memc, test_literal_param(__func__), test_literal_param("touchval"), 2, 0)); { char *value= memcached_get(memc, test_literal_param(__func__), &len, &flags, &rc); test_compare(8U, test_literal_param_size("touchval")); test_true(value); test_strcmp(value, "touchval"); test_compare(MEMCACHED_SUCCESS, rc); free(value); } rc= memcached_touch(memc, test_literal_param(__func__), 60 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); if (libmemcached_util_version_check(memc, 1, 2, 15)) { rc= memcached_touch(memc, test_literal_param(__func__), 60 *60 *24 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); rc= memcached_exist(memc, test_literal_param(__func__)); ASSERT_EQ_(MEMCACHED_NOTFOUND, rc, "%s", memcached_last_error_message(memc)); } return TEST_SUCCESS; } test_return_t test_memcached_touch_by_key(memcached_st *memc) { test_skip(TEST_SUCCESS, pre_touch(memc)); size_t len; uint32_t flags; memcached_return rc; test_null(memcached_get_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), &len, &flags, &rc)); test_zero(len); test_compare(MEMCACHED_NOTFOUND, rc); test_compare(MEMCACHED_SUCCESS, memcached_set_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), test_literal_param("touchval"), 2, 0)); { char *value= memcached_get_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), &len, &flags, &rc); test_compare(8U, test_literal_param_size("touchval")); test_true(value); test_strcmp(value, "touchval"); test_compare(MEMCACHED_SUCCESS, rc); free(value); } rc= memcached_touch_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), 60 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); if (libmemcached_util_version_check(memc, 1, 2, 15)) { rc= memcached_touch_by_key(memc, test_literal_param("grouping_key"), test_literal_param(__func__), 60 *60 *24 *60); ASSERT_EQ_(MEMCACHED_SUCCESS, rc, "%s", memcached_last_error_message(memc)); rc= memcached_exist_by_key(memc, test_literal_param("grouping_key"),test_literal_param(__func__)); ASSERT_EQ_(MEMCACHED_NOTFOUND, rc, "%s", memcached_last_error_message(memc)); } return TEST_SUCCESS; } <|endoftext|>
<commit_before>/* * This file is part of cryptopp-bindings-api. * * (c) Stephen Berquet <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "src/exception/api_exception.h" #include "src/keying/api_symmetric_key_abstract.h" #include "src/mac/api_mac_cmac.h" #include "src/symmetric/cipher/block/api_block_cipher_aes.h" #include "src/utils/api_hex_utils.h" #include "tests/test_api_assertions.h" #include <gtest/gtest.h> TEST(MacCmacTest, inheritance) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::HashTransformationInterface*>(&mac)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::MacInterface*>(&mac)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::MacAbstract*>(&mac)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::SymmetricKeyAbstract*>(&mac)); } TEST(MacCmacTest, infos) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_STREQ("cmac(aes)", mac.getName()); EXPECT_EQ(0, mac.getBlockSize()); EXPECT_EQ(16, mac.getDigestSize()); } TEST(MacCmacTest, isValidKeyLength) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_TRUE(mac.isValidKeyLength(32)); EXPECT_TRUE(mac.isValidKeyLength(24)); EXPECT_TRUE(mac.isValidKeyLength(16)); EXPECT_FALSE(mac.isValidKeyLength(23)); EXPECT_FALSE(mac.isValidKeyLength(125)); EXPECT_FALSE(mac.isValidKeyLength(0)); } TEST(MacCmacTest, setGetKey) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("0102030405060708090a0b0c0d0e0f10", 32, &key, keyLength); mac.setKey(key, keyLength); // get key size_t key2Length = mac.getKeyLength(); byte *key2 = new byte[key2Length]; mac.getKey(key2); // test key EXPECT_BYTE_ARRAY_EQ(key, keyLength, key2, key2Length); delete[] key; delete[] key2; } TEST(MacCmacTest, calculateDigest) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digests byte *expected1; byte *expected2; size_t expected1Length = 0; size_t expected2Length = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected1, expected1Length); CryptoppApi::HexUtils::hex2bin("6cc65b89ebbfbbb933a0db79d8c5f629", 32, &expected2, expected2Length); // calculate actual digests const char *input1 = "qwertyuiop"; const char *input2 = "azerty"; size_t digestSize = mac.getDigestSize(); byte actual1[digestSize]; byte actual2[digestSize]; mac.calculateDigest(reinterpret_cast<const byte*>(input1), strlen(input1), actual1); mac.calculateDigest(reinterpret_cast<const byte*>(input2), strlen(input2), actual2); // test digests EXPECT_BYTE_ARRAY_EQ(expected1, expected1Length, actual1, digestSize); EXPECT_BYTE_ARRAY_EQ(expected2, expected2Length, actual2, digestSize); delete[] expected1; delete[] expected2; } TEST(MacCmacTest, update) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digest byte *expected; size_t expectedLength = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected, expectedLength); // calculate actual digest const char *input1 = "qwerty"; const char *input2 = "uio"; const char *input3 = "p"; size_t digestSize = mac.getDigestSize(); byte actual[digestSize]; mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input2), strlen(input2)); mac.update(reinterpret_cast<const byte*>(input3), strlen(input3)); mac.finalize(actual); // test digest EXPECT_BYTE_ARRAY_EQ(expected, expectedLength, actual, digestSize); delete[] expected; } TEST(MacCmacTest, restartNotNecessaryAfterFinalize) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digest byte *expected; size_t expectedLength = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected, expectedLength); // calculate actual digest const char *input1 = "qwerty"; const char *input2 = "uio"; const char *input3 = "p"; size_t digestSize = mac.getDigestSize(); byte actual[digestSize]; mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.finalize(actual); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input2), strlen(input2)); mac.update(reinterpret_cast<const byte*>(input3), strlen(input3)); mac.finalize(actual); // test digest EXPECT_BYTE_ARRAY_EQ(expected, expectedLength, actual, digestSize); delete[] expected; } TEST(MacCmacTest, restart) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digest byte *expected; size_t expectedLength = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected, expectedLength); // calculate actual digest const char *input1 = "qwerty"; const char *input2 = "uio"; const char *input3 = "p"; size_t digestSize = mac.getDigestSize(); byte actual[digestSize]; mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.restart(); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input2), strlen(input2)); mac.update(reinterpret_cast<const byte*>(input3), strlen(input3)); mac.finalize(actual); // test digest EXPECT_BYTE_ARRAY_EQ(expected, expectedLength, actual, digestSize); delete[] expected; } TEST(MacCmacTest, largeData) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // calculate digest size_t digestSize = mac.getDigestSize(); byte *input = new byte[10485760]; byte output[digestSize]; mac.calculateDigest(input, 10485760, output); mac.update(input, 10485760); mac.finalize(output); delete[] input; } TEST(MacCmacTest, setEmptyKey) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_THROW_MSG(mac.setKey(NULL, 0), CryptoppApi::Exception, "a key is required"); } TEST(MacCmacTest, calculateDigestWithoutKey) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // calculate digest without key size_t digestSize = mac.getDigestSize(); const char *input = "qwerty"; byte actual[digestSize]; EXPECT_THROW_MSG(mac.calculateDigest(reinterpret_cast<const byte*>(input), strlen(input), actual), CryptoppApi::Exception, "a key is required"); EXPECT_THROW_MSG(mac.update(reinterpret_cast<const byte*>(input), strlen(input)), CryptoppApi::Exception, "a key is required"); EXPECT_THROW_MSG(mac.finalize(actual), CryptoppApi::Exception, "a key is required"); } TEST(MacCmacTest, keyNotMatchingUnderlyingOne) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac1(&cipher); CryptoppApi::MacCmac mac2(&cipher); std::string key1("1234567890123456"); std::string key2("azertyuiopqwerty"); std::string key3("wxcvbnqsdfghjklm"); mac1.setKey(reinterpret_cast<const byte*>(key1.c_str()), key1.length()); size_t inputLength = 20; byte input[inputLength]; byte output[mac1.getDigestSize()]; mac2.setKey(reinterpret_cast<const byte*>(key2.c_str()), key2.length()); EXPECT_THROW_MSG(mac1.calculateDigest(input, inputLength, output), CryptoppApi::Exception, "key is not matching the one owned by the underlying cipher object"); cipher.setKey(reinterpret_cast<const byte*>(key3.c_str()), key3.length()); EXPECT_THROW_MSG(mac1.calculateDigest(input, inputLength, output), CryptoppApi::Exception, "key is not matching the one owned by the underlying cipher object"); } <commit_msg>cmac unit tests: fixed valgrind warnings<commit_after>/* * This file is part of cryptopp-bindings-api. * * (c) Stephen Berquet <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "src/exception/api_exception.h" #include "src/keying/api_symmetric_key_abstract.h" #include "src/mac/api_mac_cmac.h" #include "src/symmetric/cipher/block/api_block_cipher_aes.h" #include "src/utils/api_hex_utils.h" #include "tests/test_api_assertions.h" #include <gtest/gtest.h> TEST(MacCmacTest, inheritance) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::HashTransformationInterface*>(&mac)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::MacInterface*>(&mac)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::MacAbstract*>(&mac)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::SymmetricKeyAbstract*>(&mac)); } TEST(MacCmacTest, infos) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_STREQ("cmac(aes)", mac.getName()); EXPECT_EQ(0, mac.getBlockSize()); EXPECT_EQ(16, mac.getDigestSize()); } TEST(MacCmacTest, isValidKeyLength) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_TRUE(mac.isValidKeyLength(32)); EXPECT_TRUE(mac.isValidKeyLength(24)); EXPECT_TRUE(mac.isValidKeyLength(16)); EXPECT_FALSE(mac.isValidKeyLength(23)); EXPECT_FALSE(mac.isValidKeyLength(125)); EXPECT_FALSE(mac.isValidKeyLength(0)); } TEST(MacCmacTest, setGetKey) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("0102030405060708090a0b0c0d0e0f10", 32, &key, keyLength); mac.setKey(key, keyLength); // get key size_t key2Length = mac.getKeyLength(); byte *key2 = new byte[key2Length]; mac.getKey(key2); // test key EXPECT_BYTE_ARRAY_EQ(key, keyLength, key2, key2Length); delete[] key; delete[] key2; } TEST(MacCmacTest, calculateDigest) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digests byte *expected1; byte *expected2; size_t expected1Length = 0; size_t expected2Length = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected1, expected1Length); CryptoppApi::HexUtils::hex2bin("6cc65b89ebbfbbb933a0db79d8c5f629", 32, &expected2, expected2Length); // calculate actual digests const char *input1 = "qwertyuiop"; const char *input2 = "azerty"; size_t digestSize = mac.getDigestSize(); byte actual1[digestSize]; byte actual2[digestSize]; mac.calculateDigest(reinterpret_cast<const byte*>(input1), strlen(input1), actual1); mac.calculateDigest(reinterpret_cast<const byte*>(input2), strlen(input2), actual2); // test digests EXPECT_BYTE_ARRAY_EQ(expected1, expected1Length, actual1, digestSize); EXPECT_BYTE_ARRAY_EQ(expected2, expected2Length, actual2, digestSize); delete[] expected1; delete[] expected2; } TEST(MacCmacTest, update) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digest byte *expected; size_t expectedLength = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected, expectedLength); // calculate actual digest const char *input1 = "qwerty"; const char *input2 = "uio"; const char *input3 = "p"; size_t digestSize = mac.getDigestSize(); byte actual[digestSize]; mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input2), strlen(input2)); mac.update(reinterpret_cast<const byte*>(input3), strlen(input3)); mac.finalize(actual); // test digest EXPECT_BYTE_ARRAY_EQ(expected, expectedLength, actual, digestSize); delete[] expected; } TEST(MacCmacTest, restartNotNecessaryAfterFinalize) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digest byte *expected; size_t expectedLength = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected, expectedLength); // calculate actual digest const char *input1 = "qwerty"; const char *input2 = "uio"; const char *input3 = "p"; size_t digestSize = mac.getDigestSize(); byte actual[digestSize]; mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.finalize(actual); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input2), strlen(input2)); mac.update(reinterpret_cast<const byte*>(input3), strlen(input3)); mac.finalize(actual); // test digest EXPECT_BYTE_ARRAY_EQ(expected, expectedLength, actual, digestSize); delete[] expected; } TEST(MacCmacTest, restart) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // build expected digest byte *expected; size_t expectedLength = 0; CryptoppApi::HexUtils::hex2bin("caa7624159a7b2f383509739843c8f3f", 32, &expected, expectedLength); // calculate actual digest const char *input1 = "qwerty"; const char *input2 = "uio"; const char *input3 = "p"; size_t digestSize = mac.getDigestSize(); byte actual[digestSize]; mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.restart(); mac.update(reinterpret_cast<const byte*>(input1), strlen(input1)); mac.update(reinterpret_cast<const byte*>(input2), strlen(input2)); mac.update(reinterpret_cast<const byte*>(input3), strlen(input3)); mac.finalize(actual); // test digest EXPECT_BYTE_ARRAY_EQ(expected, expectedLength, actual, digestSize); delete[] expected; } TEST(MacCmacTest, largeData) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // set key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("2b7e151628aed2a6abf7158809cf4f3c", 32, &key, keyLength); mac.setKey(key, keyLength); delete[] key; // calculate digest size_t digestSize = mac.getDigestSize(); byte *input = new byte[10485760]; byte output[digestSize]; memset(input, 0, 10485760); mac.calculateDigest(input, 10485760, output); mac.update(input, 10485760); mac.finalize(output); delete[] input; } TEST(MacCmacTest, setEmptyKey) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); EXPECT_THROW_MSG(mac.setKey(NULL, 0), CryptoppApi::Exception, "a key is required"); } TEST(MacCmacTest, calculateDigestWithoutKey) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac(&cipher); // calculate digest without key size_t digestSize = mac.getDigestSize(); const char *input = "qwerty"; byte actual[digestSize]; EXPECT_THROW_MSG(mac.calculateDigest(reinterpret_cast<const byte*>(input), strlen(input), actual), CryptoppApi::Exception, "a key is required"); EXPECT_THROW_MSG(mac.update(reinterpret_cast<const byte*>(input), strlen(input)), CryptoppApi::Exception, "a key is required"); EXPECT_THROW_MSG(mac.finalize(actual), CryptoppApi::Exception, "a key is required"); } TEST(MacCmacTest, keyNotMatchingUnderlyingOne) { CryptoppApi::BlockCipherAes cipher; CryptoppApi::MacCmac mac1(&cipher); CryptoppApi::MacCmac mac2(&cipher); std::string key1("1234567890123456"); std::string key2("azertyuiopqwerty"); std::string key3("wxcvbnqsdfghjklm"); mac1.setKey(reinterpret_cast<const byte*>(key1.c_str()), key1.length()); size_t inputLength = 20; byte input[inputLength]; byte output[mac1.getDigestSize()]; mac2.setKey(reinterpret_cast<const byte*>(key2.c_str()), key2.length()); EXPECT_THROW_MSG(mac1.calculateDigest(input, inputLength, output), CryptoppApi::Exception, "key is not matching the one owned by the underlying cipher object"); cipher.setKey(reinterpret_cast<const byte*>(key3.c_str()), key3.length()); EXPECT_THROW_MSG(mac1.calculateDigest(input, inputLength, output), CryptoppApi::Exception, "key is not matching the one owned by the underlying cipher object"); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011-2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author : Christian Potthast * Email : [email protected] * */ #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/common/transforms.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/filters/voxel_grid_occlusion_estimation.h> #include <vtkLine.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; typedef PointXYZ PointT; typedef PointCloud<PointT> CloudT; float default_leaf_size = 0.01f; vtkDataSet* createDataSetFromVTKPoints (vtkPoints *points) { vtkCellArray *verts = vtkCellArray::New (); vtkPolyData *data = vtkPolyData::New (); // Iterate through the points for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++) verts->InsertNextCell ((vtkIdType)1, &i); data->SetPoints (points); data->SetVerts (verts); return data; } vtkSmartPointer<vtkPolyData> getCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New (); cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ); return cube->GetOutput (); } void getAxisActors (Eigen::Vector4f origin, Eigen::Quaternionf orientation, vtkSmartPointer<vtkActorCollection> coll) { Eigen::Vector3f x (0.25, 0.0, 0.0); Eigen::Vector3f y (0.0, 0.25, 0.0); Eigen::Vector3f z (0.0, 0.0, 0.25); Eigen::Matrix3f rot = orientation.toRotationMatrix (); x = rot * x; y = rot * y; z = rot * z; x = origin.head (3) + x; y = origin.head (3) + y; z = origin.head (3) + z; // Create a vtkPoints object and store the points in it vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New(); pts->InsertNextPoint(origin.x (), origin.y (), origin.z ()); pts->InsertNextPoint(x.x (), x.y (), x.z ()); pts->InsertNextPoint(y.x (), y.y (), y.z ()); pts->InsertNextPoint(z.x (), z.y (), z.z ()); // Setup two colors - one for each line unsigned char red[3] = {255, 0, 0}; unsigned char green[3] = {0, 255, 0}; unsigned char blue[3] = {0, 0, 255}; // Setup the colors array vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New(); colors->SetNumberOfComponents(3); colors->SetName("Colors"); // Add the colors we created to the colors array colors->InsertNextTupleValue(red); colors->InsertNextTupleValue(green); colors->InsertNextTupleValue(blue); // Create the first line (between Origin and P0) vtkSmartPointer<vtkLine> line0 = vtkSmartPointer<vtkLine>::New(); line0->GetPointIds()->SetId(0,0); //the second 0 is the index of the Origin in the vtkPoints line0->GetPointIds()->SetId(1,1); //the second 1 is the index of P0 in the vtkPoints // Create the second line (between Origin and P1) vtkSmartPointer<vtkLine> line1 = vtkSmartPointer<vtkLine>::New(); line1->GetPointIds()->SetId(0,0); //the second 0 is the index of the Origin in the vtkPoints line1->GetPointIds()->SetId(1,2); //2 is the index of P1 in the vtkPoints // Create the second line (between Origin and P2) vtkSmartPointer<vtkLine> line2 = vtkSmartPointer<vtkLine>::New(); line2->GetPointIds()->SetId(0,0); //the third 0 is the index of the Origin in the vtkPoints line2->GetPointIds()->SetId(1,3); //3 is the index of P2 in the vtkPoints // Create a cell array to store the lines in and add the lines to it vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); lines->InsertNextCell(line0); lines->InsertNextCell(line1); lines->InsertNextCell(line2); // Create a polydata to store everything in vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New(); // Add the points to the dataset linesPolyData->SetPoints(pts); // Add the lines to the dataset linesPolyData->SetLines(lines); linesPolyData->GetCellData()->SetScalars(colors); // Visualize vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInput(linesPolyData); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); actor->GetProperty ()->SetLineWidth (5); coll->AddItem (actor); } void getPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll, float point_size = 4.0f) { vtkPolyData* points_poly; size_t i; vtkPoints *octreeLeafPoints = vtkPoints::New (); // add all points from octree to vtkPoint object for (i=0; i< cloud.points.size(); i++) { octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z); } points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints); vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (points_poly); pointsActor->SetMapper (mapper); pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0); pointsActor->GetProperty ()->SetPointSize (point_size); coll->AddItem (pointsActor); } void getVoxelActors (pcl::PointCloud<pcl::PointXYZ>& voxelCenters, double voxelSideLen, Eigen::Vector3f color, vtkSmartPointer<vtkActorCollection> coll) { vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New (); size_t i; double s = voxelSideLen/2.0; for (i = 0; i < voxelCenters.points.size (); i++) { double x = voxelCenters.points[i].x; double y = voxelCenters.points[i].y; double z = voxelCenters.points[i].z; treeWireframe->AddInput (getCuboid (x - s, x + s, y - s, y + s, z - s, z + s)); } vtkSmartPointer < vtkLODActor > treeActor = vtkSmartPointer<vtkLODActor>::New (); vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (treeWireframe->GetOutput ()); treeActor->SetMapper (mapper); treeActor->GetProperty ()->SetRepresentationToWireframe (); treeActor->GetProperty ()->SetColor (color[0], color[1], color[2]); treeActor->GetProperty ()->SetLineWidth (4); coll->AddItem (treeActor); } void displayBoundingBox (Eigen::Vector3f& min_b, Eigen::Vector3f& max_b, vtkSmartPointer<vtkActorCollection> coll) { vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New (); treeWireframe->AddInput (getCuboid (min_b[0], max_b[0], min_b[1], max_b[1], min_b[2], max_b[2])); vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (treeWireframe->GetOutput ()); treeActor->SetMapper (mapper); treeActor->GetProperty ()->SetRepresentationToWireframe (); treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0); treeActor->GetProperty ()->SetLineWidth (2); coll->AddItem (treeActor); } void printHelp (int, char **argv) { print_error ("Syntax is: %s input.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -leaf x,y,z = the VoxelGrid leaf size (default: "); print_value ("%f, %f, %f", default_leaf_size, default_leaf_size, default_leaf_size); print_info (")\n"); } int main (int argc, char** argv) { print_info ("Estimate occlusion using pcl::VoxelGridOcclusionEstimation. For more information, use: %s -h\n", argv[0]); if (argc < 2) { printHelp (argc, argv); return (-1); } // Command line parsing float leaf_x = default_leaf_size, leaf_y = default_leaf_size, leaf_z = default_leaf_size; std::vector<double> values; parse_x_arguments (argc, argv, "-leaf", values); if (values.size () == 1) { leaf_x = static_cast<float> (values[0]); leaf_y = static_cast<float> (values[0]); leaf_z = static_cast<float> (values[0]); } else if (values.size () == 3) { leaf_x = static_cast<float> (values[0]); leaf_y = static_cast<float> (values[1]); leaf_z = static_cast<float> (values[2]); } else { print_error ("Leaf size must be specified with either 1 or 3 numbers (%zu given).\n", values.size ()); } print_info ("Using a leaf size of: "); print_value ("%f, %f, %f\n", leaf_x, leaf_y, leaf_z); // input cloud CloudT::Ptr input_cloud (new CloudT); loadPCDFile (argv[1], *input_cloud); Eigen::Vector4f sensor_origin = input_cloud->sensor_origin_; Eigen::Quaternionf sensor_orientation = input_cloud->sensor_orientation_; vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New (); VoxelGridOcclusionEstimation<PointT> vg; vg.setInputCloud (input_cloud); vg.setLeafSize (leaf_x, leaf_y, leaf_z); vg.initializeVoxelGrid (); Eigen::Vector3f b_min, b_max; b_min = vg.getMinBoundCoordinates (); b_max = vg.getMaxBoundCoordinates (); TicToc tt; print_highlight ("Ray-Traversal "); tt.tic (); // estimate the occluded space std::vector <Eigen::Vector3i> occluded_voxels; vg.occlusionEstimationAll (occluded_voxels); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", (int)occluded_voxels.size ()); print_info (" occluded voxels]\n"); CloudT::Ptr occ_centroids (new CloudT); occ_centroids->width = static_cast<int> (occluded_voxels.size ()); occ_centroids->height = 1; occ_centroids->is_dense = false; for (size_t i = 0; i < occluded_voxels.size (); ++i) { Eigen::Vector4f xyz = vg.getCentroidCoordinate (occluded_voxels[i]); PointT point; point.x = xyz[0]; point.y = xyz[1]; point.z = xyz[2]; occ_centroids->points.push_back (point); } // visualization Eigen::Vector3f red (1.0, 0.0, 0.0); Eigen::Vector3f blue (0.0, 0.0, 1.0); // visualize axis getAxisActors (sensor_origin, sensor_orientation ,coll); // draw point cloud getPointActors ( *input_cloud, coll); // draw the bounding box of the voxel grid displayBoundingBox (b_min, b_max, coll); // draw the occluded voxels getVoxelActors (*occ_centroids, leaf_x, red, coll); // Create the RenderWindow, Renderer and RenderWindowInteractor vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer (renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow (renderWindow); // Add the actors to the renderer, set the background and size renderer->SetBackground (1.0, 1.0, 1.0); renderWindow->SetSize (640, 480); vtkActor* a; coll->InitTraversal (); a = coll->GetNextActor (); while(a!=0) { renderer->AddActor (a); a = coll->GetNextActor (); } renderWindow->Render (); renderWindowInteractor->Start (); return 0; } <commit_msg>* small modification<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011-2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author : Christian Potthast * Email : [email protected] * */ #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/common/transforms.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/filters/voxel_grid_occlusion_estimation.h> #include <vtkLine.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; typedef PointXYZ PointT; typedef PointCloud<PointT> CloudT; float default_leaf_size = 0.01f; vtkDataSet* createDataSetFromVTKPoints (vtkPoints *points) { vtkCellArray *verts = vtkCellArray::New (); vtkPolyData *data = vtkPolyData::New (); // Iterate through the points for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++) verts->InsertNextCell ((vtkIdType)1, &i); data->SetPoints (points); data->SetVerts (verts); return data; } vtkSmartPointer<vtkPolyData> getCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New (); cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ); return cube->GetOutput (); } void getVoxelActors (pcl::PointCloud<pcl::PointXYZ>& voxelCenters, double voxelSideLen, Eigen::Vector3f color, vtkSmartPointer<vtkActorCollection> coll) { vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New (); size_t i; double s = voxelSideLen/2.0; for (i = 0; i < voxelCenters.points.size (); i++) { double x = voxelCenters.points[i].x; double y = voxelCenters.points[i].y; double z = voxelCenters.points[i].z; treeWireframe->AddInput (getCuboid (x - s, x + s, y - s, y + s, z - s, z + s)); } vtkSmartPointer < vtkLODActor > treeActor = vtkSmartPointer<vtkLODActor>::New (); vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (treeWireframe->GetOutput ()); treeActor->SetMapper (mapper); treeActor->GetProperty ()->SetRepresentationToWireframe (); treeActor->GetProperty ()->SetColor (color[0], color[1], color[2]); treeActor->GetProperty ()->SetLineWidth (4); coll->AddItem (treeActor); } void displayBoundingBox (Eigen::Vector3f& min_b, Eigen::Vector3f& max_b, vtkSmartPointer<vtkActorCollection> coll) { vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New (); treeWireframe->AddInput (getCuboid (min_b[0], max_b[0], min_b[1], max_b[1], min_b[2], max_b[2])); vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (treeWireframe->GetOutput ()); treeActor->SetMapper (mapper); treeActor->GetProperty ()->SetRepresentationToWireframe (); treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0); treeActor->GetProperty ()->SetLineWidth (2); coll->AddItem (treeActor); } void printHelp (int, char **argv) { print_error ("Syntax is: %s input.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -leaf x,y,z = the VoxelGrid leaf size (default: "); print_value ("%f, %f, %f", default_leaf_size, default_leaf_size, default_leaf_size); print_info (")\n"); } int main (int argc, char** argv) { print_info ("Estimate occlusion using pcl::VoxelGridOcclusionEstimation. For more information, use: %s -h\n", argv[0]); if (argc < 2) { printHelp (argc, argv); return (-1); } // Command line parsing float leaf_x = default_leaf_size, leaf_y = default_leaf_size, leaf_z = default_leaf_size; std::vector<double> values; parse_x_arguments (argc, argv, "-leaf", values); if (values.size () == 1) { leaf_x = static_cast<float> (values[0]); leaf_y = static_cast<float> (values[0]); leaf_z = static_cast<float> (values[0]); } else if (values.size () == 3) { leaf_x = static_cast<float> (values[0]); leaf_y = static_cast<float> (values[1]); leaf_z = static_cast<float> (values[2]); } else { print_error ("Leaf size must be specified with either 1 or 3 numbers (%zu given).\n", values.size ()); } print_info ("Using a leaf size of: "); print_value ("%f, %f, %f\n", leaf_x, leaf_y, leaf_z); // input cloud CloudT::Ptr input_cloud (new CloudT); loadPCDFile (argv[1], *input_cloud); // VTK actors vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New (); // voxel grid VoxelGridOcclusionEstimation<PointT> vg; vg.setInputCloud (input_cloud); vg.setLeafSize (leaf_x, leaf_y, leaf_z); vg.initializeVoxelGrid (); Eigen::Vector3f b_min, b_max; b_min = vg.getMinBoundCoordinates (); b_max = vg.getMaxBoundCoordinates (); TicToc tt; print_highlight ("Ray-Traversal "); tt.tic (); // estimate the occluded space std::vector <Eigen::Vector3i> occluded_voxels; vg.occlusionEstimationAll (occluded_voxels); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", (int)occluded_voxels.size ()); print_info (" occluded voxels]\n"); CloudT::Ptr occ_centroids (new CloudT); occ_centroids->width = static_cast<int> (occluded_voxels.size ()); occ_centroids->height = 1; occ_centroids->is_dense = false; occ_centroids->points.resize (occluded_voxels.size ()); for (size_t i = 0; i < occluded_voxels.size (); ++i) { Eigen::Vector4f xyz = vg.getCentroidCoordinate (occluded_voxels[i]); PointT point; point.x = xyz[0]; point.y = xyz[1]; point.z = xyz[2]; occ_centroids->points[i] = point; } CloudT::Ptr cloud_centroids (new CloudT); cloud_centroids->width = static_cast<int> (input_cloud->points.size ()); cloud_centroids->height = 1; cloud_centroids->is_dense = false; cloud_centroids->points.resize (input_cloud->points.size ()); for (size_t i = 0; i < input_cloud->points.size (); ++i) { float x = input_cloud->points[i].x; float y = input_cloud->points[i].y; float z = input_cloud->points[i].z; Eigen::Vector3i c = vg.getGridCoordinates (x, y, z); Eigen::Vector4f xyz = vg.getCentroidCoordinate (c); PointT point; point.x = xyz[0]; point.y = xyz[1]; point.z = xyz[2]; cloud_centroids->points[i] = point; } // visualization Eigen::Vector3f red (1.0, 0.0, 0.0); Eigen::Vector3f blue (0.0, 0.0, 1.0); // draw point cloud voxels getVoxelActors (*cloud_centroids, leaf_x, red, coll); // draw the bounding box of the voxel grid displayBoundingBox (b_min, b_max, coll); // draw the occluded voxels getVoxelActors (*occ_centroids, leaf_x, blue, coll); // Create the RenderWindow, Renderer and RenderWindowInteractor vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer (renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow (renderWindow); // Add the actors to the renderer, set the background and size renderer->SetBackground (1.0, 1.0, 1.0); renderWindow->SetSize (640, 480); vtkActor* a; coll->InitTraversal (); a = coll->GetNextActor (); while(a!=0) { renderer->AddActor (a); a = coll->GetNextActor (); } renderWindow->Render (); renderWindowInteractor->Start (); return 0; } <|endoftext|>
<commit_before>#ifndef VEXCL_TYPES_HPP #define VEXCL_TYPES_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/types.hpp * \author Pascal Germroth <[email protected]> * \brief Support for using native C++ and OpenCL types in expressions. */ #include <string> #include <type_traits> #include <stdexcept> #include <iostream> #include <sstream> #ifndef __CL_ENABLE_EXCEPTIONS # define __CL_ENABLE_EXCEPTIONS #endif #include <CL/cl.hpp> typedef unsigned int uint; typedef unsigned char uchar; namespace vex { /// Get the corresponding scalar type for a CL vector (or scalar) type. /** \code cl_scalar_of<cl_float4>::type == cl_float \endcode */ template <class T> struct cl_scalar_of {}; /// Get the corresponding vector type for a CL scalar type. /** \code cl_vector_of<cl_float, 4>::type == cl_float4 \endcode */ template <class T, int dim> struct cl_vector_of {}; /// Get the number of values in a CL vector (or scalar) type. /** \code cl_vector_length<cl_float4>::value == 4 \endcode */ template <class T> struct cl_vector_length {}; } // namespace vex #define BIN_OP(base_type, len, op) \ inline cl_##base_type##len &operator op##= (cl_##base_type##len &a, const cl_##base_type##len &b) { \ for(size_t i = 0 ; i < len ; i++) a.s[i] op##= b.s[i]; \ return a; \ } \ inline cl_##base_type##len operator op(const cl_##base_type##len &a, const cl_##base_type##len &b) { \ cl_##base_type##len res = a; return res op##= b; \ } // `scalar OP vector` acts like `(vector_t)(scalar) OP vector` in OpenCl: // all components are set to the scalar value. #define BIN_SCALAR_OP(base_type, len, op) \ inline cl_##base_type##len &operator op##= (cl_##base_type##len &a, const cl_##base_type &b) { \ for(size_t i = 0 ; i < len ; i++) a.s[i] op##= b; \ return a; \ } \ inline cl_##base_type##len operator op(const cl_##base_type##len &a, const cl_##base_type &b) { \ cl_##base_type##len res = a; return res op##= b; \ } \ inline cl_##base_type##len operator op(const cl_##base_type &a, const cl_##base_type##len &b) { \ cl_##base_type##len res = b; return res op##= a; \ } #define CL_VEC_TYPE(base_type, len) \ BIN_OP(base_type, len, +) \ BIN_OP(base_type, len, -) \ BIN_OP(base_type, len, *) \ BIN_OP(base_type, len, /) \ BIN_SCALAR_OP(base_type, len, +) \ BIN_SCALAR_OP(base_type, len, -) \ BIN_SCALAR_OP(base_type, len, *) \ BIN_SCALAR_OP(base_type, len, /) \ inline cl_##base_type##len operator -(const cl_##base_type##len &a) { \ cl_##base_type##len res; \ for(size_t i = 0 ; i < len ; i++) res.s[i] = -a.s[i]; \ return res; \ } \ inline std::ostream &operator<<(std::ostream &os, const cl_##base_type##len &value) { \ os << "(" #base_type #len ")("; \ for(std::size_t i = 0 ; i < len ; i++) { \ if(i != 0) os << ','; \ os << value.s[i]; \ } \ return os << ')'; \ } \ namespace vex { \ template <> struct cl_scalar_of<cl_##base_type##len> { typedef cl_##base_type type; }; \ template <> struct cl_vector_of<cl_##base_type, len> { typedef cl_##base_type##len type; }; \ template <> struct cl_vector_length<cl_##base_type##len> : std::integral_constant<unsigned, len>{ }; \ } #define CL_TYPES(base_type) \ CL_VEC_TYPE(base_type, 2) \ CL_VEC_TYPE(base_type, 4) \ CL_VEC_TYPE(base_type, 8) \ CL_VEC_TYPE(base_type, 16) \ namespace vex { \ template <> struct cl_scalar_of<cl_##base_type> { typedef cl_##base_type type; }; \ template <> struct cl_vector_of<cl_##base_type, 1> { typedef cl_##base_type type; }; \ template <> struct cl_vector_length<cl_##base_type> : std::integral_constant<unsigned, 1> { }; \ } #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4146) #endif CL_TYPES(float) CL_TYPES(double) CL_TYPES(char) CL_TYPES(uchar) CL_TYPES(short) CL_TYPES(ushort) CL_TYPES(int) CL_TYPES(uint) CL_TYPES(long) CL_TYPES(ulong) #ifdef _MSC_VER # pragma warning(pop) #endif #undef BIN_OP #undef CL_VEC_TYPE #undef CL_TYPES namespace vex { /// Convert each element of the vector to another type. template<class To, class From> inline To cl_convert(const From &val) { const size_t n = cl_vector_length<To>::value; static_assert(n == cl_vector_length<From>::value, "Vectors must be same length."); To out; for(size_t i = 0 ; i != n ; i++) out.s[i] = val.s[i]; return out; } /// Declares a type as CL native, allows using it as a literal. template <class T> struct is_cl_native : std::false_type {}; /// Convert typename to string. template <class T> inline typename std::enable_if<!std::is_pointer<T>::value, std::string>::type type_name() { throw std::logic_error("Trying to use an undefined type in a kernel."); } template<typename T> inline typename std::enable_if<std::is_pointer<T>::value, std::string>::type type_name() { std::ostringstream s; s << "global " << type_name<typename std::remove_pointer<T>::type>() << " * "; return s.str(); } #define STRINGIFY(type) \ template <> inline std::string type_name<cl_##type>() { return #type; } \ template <> struct is_cl_native<cl_##type> : std::true_type {}; // enable use of OpenCL vector types as literals #define CL_VEC_TYPE(type, len) \ template <> inline std::string type_name<cl_##type##len>() { return #type #len; } \ template <> struct is_cl_native<cl_##type##len> : std::true_type {}; #define CL_TYPES(type) \ STRINGIFY(type) \ CL_VEC_TYPE(type, 2) \ CL_VEC_TYPE(type, 4) \ CL_VEC_TYPE(type, 8) \ CL_VEC_TYPE(type, 16) CL_TYPES(float) CL_TYPES(double) CL_TYPES(char) CL_TYPES(uchar) CL_TYPES(short) CL_TYPES(ushort) CL_TYPES(int) CL_TYPES(uint) CL_TYPES(long) CL_TYPES(ulong) #undef CL_TYPES #undef CL_VEC_TYPE #undef STRINGIFY // char and cl_char are different types. Hence, special handling is required: template <> inline std::string type_name<char>() { return "char"; } template <> struct is_cl_native<char> : std::true_type {}; template <> struct cl_vector_length<char> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<char> { typedef char type; }; // One can not pass bool to the kernel, but the overload is needed for type // deduction: template <> inline std::string type_name<bool>() { return "bool"; } #if defined(__APPLE__) template <> inline std::string type_name<size_t>() { return sizeof(std::size_t) == sizeof(uint) ? "uint" : "ulong"; } template <> inline std::string type_name<ptrdiff_t>() { return sizeof(std::size_t) == sizeof(uint) ? "int" : "long"; } template <> struct is_cl_native<size_t> : std::true_type {}; template <> struct is_cl_native<ptrdiff_t> : std::true_type {}; template <> struct cl_vector_length<size_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_vector_length<ptrdiff_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<size_t> { typedef size_t type; }; template <> struct cl_vector_of<size_t, 1> { typedef size_t type; }; template <> struct cl_scalar_of<ptrdiff_t> { typedef ptrdiff_t type; }; template <> struct cl_vector_of<ptrdiff_t, 1> { typedef ptrdiff_t type; }; #endif template <class T> struct is_cl_scalar : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value == 1) > {}; template <class T> struct is_cl_vector : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value > 1) > {}; } #endif <commit_msg>Removed unnecessary space from generated strings<commit_after>#ifndef VEXCL_TYPES_HPP #define VEXCL_TYPES_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/types.hpp * \author Pascal Germroth <[email protected]> * \brief Support for using native C++ and OpenCL types in expressions. */ #include <string> #include <type_traits> #include <stdexcept> #include <iostream> #include <sstream> #ifndef __CL_ENABLE_EXCEPTIONS # define __CL_ENABLE_EXCEPTIONS #endif #include <CL/cl.hpp> typedef unsigned int uint; typedef unsigned char uchar; namespace vex { /// Get the corresponding scalar type for a CL vector (or scalar) type. /** \code cl_scalar_of<cl_float4>::type == cl_float \endcode */ template <class T> struct cl_scalar_of {}; /// Get the corresponding vector type for a CL scalar type. /** \code cl_vector_of<cl_float, 4>::type == cl_float4 \endcode */ template <class T, int dim> struct cl_vector_of {}; /// Get the number of values in a CL vector (or scalar) type. /** \code cl_vector_length<cl_float4>::value == 4 \endcode */ template <class T> struct cl_vector_length {}; } // namespace vex #define BIN_OP(base_type, len, op) \ inline cl_##base_type##len &operator op##= (cl_##base_type##len &a, const cl_##base_type##len &b) { \ for(size_t i = 0 ; i < len ; i++) a.s[i] op##= b.s[i]; \ return a; \ } \ inline cl_##base_type##len operator op(const cl_##base_type##len &a, const cl_##base_type##len &b) { \ cl_##base_type##len res = a; return res op##= b; \ } // `scalar OP vector` acts like `(vector_t)(scalar) OP vector` in OpenCl: // all components are set to the scalar value. #define BIN_SCALAR_OP(base_type, len, op) \ inline cl_##base_type##len &operator op##= (cl_##base_type##len &a, const cl_##base_type &b) { \ for(size_t i = 0 ; i < len ; i++) a.s[i] op##= b; \ return a; \ } \ inline cl_##base_type##len operator op(const cl_##base_type##len &a, const cl_##base_type &b) { \ cl_##base_type##len res = a; return res op##= b; \ } \ inline cl_##base_type##len operator op(const cl_##base_type &a, const cl_##base_type##len &b) { \ cl_##base_type##len res = b; return res op##= a; \ } #define CL_VEC_TYPE(base_type, len) \ BIN_OP(base_type, len, +) \ BIN_OP(base_type, len, -) \ BIN_OP(base_type, len, *) \ BIN_OP(base_type, len, /) \ BIN_SCALAR_OP(base_type, len, +) \ BIN_SCALAR_OP(base_type, len, -) \ BIN_SCALAR_OP(base_type, len, *) \ BIN_SCALAR_OP(base_type, len, /) \ inline cl_##base_type##len operator -(const cl_##base_type##len &a) { \ cl_##base_type##len res; \ for(size_t i = 0 ; i < len ; i++) res.s[i] = -a.s[i]; \ return res; \ } \ inline std::ostream &operator<<(std::ostream &os, const cl_##base_type##len &value) { \ os << "(" #base_type #len ")("; \ for(std::size_t i = 0 ; i < len ; i++) { \ if(i != 0) os << ','; \ os << value.s[i]; \ } \ return os << ')'; \ } \ namespace vex { \ template <> struct cl_scalar_of<cl_##base_type##len> { typedef cl_##base_type type; }; \ template <> struct cl_vector_of<cl_##base_type, len> { typedef cl_##base_type##len type; }; \ template <> struct cl_vector_length<cl_##base_type##len> : std::integral_constant<unsigned, len>{ }; \ } #define CL_TYPES(base_type) \ CL_VEC_TYPE(base_type, 2) \ CL_VEC_TYPE(base_type, 4) \ CL_VEC_TYPE(base_type, 8) \ CL_VEC_TYPE(base_type, 16) \ namespace vex { \ template <> struct cl_scalar_of<cl_##base_type> { typedef cl_##base_type type; }; \ template <> struct cl_vector_of<cl_##base_type, 1> { typedef cl_##base_type type; }; \ template <> struct cl_vector_length<cl_##base_type> : std::integral_constant<unsigned, 1> { }; \ } #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4146) #endif CL_TYPES(float) CL_TYPES(double) CL_TYPES(char) CL_TYPES(uchar) CL_TYPES(short) CL_TYPES(ushort) CL_TYPES(int) CL_TYPES(uint) CL_TYPES(long) CL_TYPES(ulong) #ifdef _MSC_VER # pragma warning(pop) #endif #undef BIN_OP #undef CL_VEC_TYPE #undef CL_TYPES namespace vex { /// Convert each element of the vector to another type. template<class To, class From> inline To cl_convert(const From &val) { const size_t n = cl_vector_length<To>::value; static_assert(n == cl_vector_length<From>::value, "Vectors must be same length."); To out; for(size_t i = 0 ; i != n ; i++) out.s[i] = val.s[i]; return out; } /// Declares a type as CL native, allows using it as a literal. template <class T> struct is_cl_native : std::false_type {}; /// Convert typename to string. template <class T> inline typename std::enable_if<!std::is_pointer<T>::value, std::string>::type type_name() { throw std::logic_error("Trying to use an undefined type in a kernel."); } template<typename T> inline typename std::enable_if<std::is_pointer<T>::value, std::string>::type type_name() { std::ostringstream s; s << "global " << type_name<typename std::remove_pointer<T>::type>() << " *"; return s.str(); } #define STRINGIFY(type) \ template <> inline std::string type_name<cl_##type>() { return #type; } \ template <> struct is_cl_native<cl_##type> : std::true_type {}; // enable use of OpenCL vector types as literals #define CL_VEC_TYPE(type, len) \ template <> inline std::string type_name<cl_##type##len>() { return #type #len; } \ template <> struct is_cl_native<cl_##type##len> : std::true_type {}; #define CL_TYPES(type) \ STRINGIFY(type) \ CL_VEC_TYPE(type, 2) \ CL_VEC_TYPE(type, 4) \ CL_VEC_TYPE(type, 8) \ CL_VEC_TYPE(type, 16) CL_TYPES(float) CL_TYPES(double) CL_TYPES(char) CL_TYPES(uchar) CL_TYPES(short) CL_TYPES(ushort) CL_TYPES(int) CL_TYPES(uint) CL_TYPES(long) CL_TYPES(ulong) #undef CL_TYPES #undef CL_VEC_TYPE #undef STRINGIFY // char and cl_char are different types. Hence, special handling is required: template <> inline std::string type_name<char>() { return "char"; } template <> struct is_cl_native<char> : std::true_type {}; template <> struct cl_vector_length<char> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<char> { typedef char type; }; // One can not pass bool to the kernel, but the overload is needed for type // deduction: template <> inline std::string type_name<bool>() { return "bool"; } #if defined(__APPLE__) template <> inline std::string type_name<size_t>() { return sizeof(std::size_t) == sizeof(uint) ? "uint" : "ulong"; } template <> inline std::string type_name<ptrdiff_t>() { return sizeof(std::size_t) == sizeof(uint) ? "int" : "long"; } template <> struct is_cl_native<size_t> : std::true_type {}; template <> struct is_cl_native<ptrdiff_t> : std::true_type {}; template <> struct cl_vector_length<size_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_vector_length<ptrdiff_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<size_t> { typedef size_t type; }; template <> struct cl_vector_of<size_t, 1> { typedef size_t type; }; template <> struct cl_scalar_of<ptrdiff_t> { typedef ptrdiff_t type; }; template <> struct cl_vector_of<ptrdiff_t, 1> { typedef ptrdiff_t type; }; #endif template <class T> struct is_cl_scalar : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value == 1) > {}; template <class T> struct is_cl_vector : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value > 1) > {}; } #endif <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * 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 "jstreamsconfig.h" #include "indexer.h" #include "filelister.h" #include "filereader.h" #include "filtermanager.h" using namespace std; Indexer *Indexer::workingIndexer; Indexer::Indexer(const char *indexdir, jstreams::IndexerConfiguration& ic) : m_indexdir(indexdir), m_manager(indexdir), m_indexer(*m_manager.getIndexWriter(), ic) { m_lister = new FileLister(ic); } Indexer::~Indexer() { delete m_lister; } void Indexer::index(const char *dir) { workingIndexer = this; m_lister->setFileCallbackFunction(&Indexer::addFileCallback); bool exceptions = true; if (exceptions) { try { m_lister->listFiles(dir); } catch(...) { printf("Unknown error"); } } else { m_lister->listFiles(dir); } } bool Indexer::addFileCallback(const char* path, uint dirlen, uint len, time_t mtime) { workingIndexer->doFile(path); return true; } void Indexer::doFile(const std::string &filepath) { m_indexer.indexFile(filepath.c_str()); } <commit_msg>Fix sqlite build.<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * 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 "jstreamsconfig.h" #include "indexer.h" #include "filelister.h" #include "filereader.h" using namespace std; Indexer *Indexer::workingIndexer; Indexer::Indexer(const char *indexdir, jstreams::IndexerConfiguration& ic) : m_indexdir(indexdir), m_manager(indexdir), m_indexer(*m_manager.getIndexWriter(), ic) { m_lister = new FileLister(ic); } Indexer::~Indexer() { delete m_lister; } void Indexer::index(const char *dir) { workingIndexer = this; m_lister->setFileCallbackFunction(&Indexer::addFileCallback); bool exceptions = true; if (exceptions) { try { m_lister->listFiles(dir); } catch(...) { printf("Unknown error"); } } else { m_lister->listFiles(dir); } } bool Indexer::addFileCallback(const char* path, uint dirlen, uint len, time_t mtime) { workingIndexer->doFile(path); return true; } void Indexer::doFile(const std::string &filepath) { m_indexer.indexFile(filepath.c_str()); } <|endoftext|>
<commit_before>#include <QApplication> #include <QWebSettings> #include "KVMainWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QCoreApplication::setApplicationName("KCTViewer"); QCoreApplication::setApplicationVersion("0.0.1a"); QCoreApplication::setOrganizationName("MacaroniCode"); QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); KVMainWindow win; win.show(); app.exec(); } <commit_msg>Version Bump<commit_after>#include <QApplication> #include <QWebSettings> #include "KVMainWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QCoreApplication::setApplicationName("KCTViewer"); QCoreApplication::setApplicationVersion("0.0.2a"); QCoreApplication::setOrganizationName("MacaroniCode"); QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); KVMainWindow win; win.show(); app.exec(); } <|endoftext|>
<commit_before>#include "montecarlohost.hpp" // optional: bool MonteCarloHost::acceptance(const double Eold, const double Enew, const double temperature) { #ifndef NDEBUG double random = enhance::random_double(0.0, 1.0); double condition = std::exp(-(Enew-Eold)/temperature); Logger::getInstance().debug_new_line("[mc]", "random = ", random, ", exp(-(energy_new-energy_old)/temperature) = ", condition); return random < condition ? true : false; #endif return enhance::random_double(0.0, 1.0) < std::exp(-(Enew-Eold)/temperature) ? true : false; } void MonteCarloHost::run(const unsigned long& steps, const bool EQUILMODE) { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(parameters); /* Aufgabe 1.6: * * input: steps: Anzahl MC Steps die durchgeführt werden sollen, * EQUILMODE: Modus des Runs * return: / * Funktion: Durchführung der MC Schritte, Akzeptanz/Rückweisung der * Schritte nach dem Metropoliskriterium. * Bei EQUILMODE = false: Speichern der aktuellen Werte von * Hamiltonian und Magnetisierung nach Durchführung der Schritte * durch anhängen an die Membervariablen energies und magnetisations. * Optional: Auslagern des Akzeptanz-Checks in zusätzliche Funktion * */ double energy_old; double energy_new; for(unsigned int t=0; t<steps; ++t) { // flip spin: energy_old = spinsystem.getHamiltonian(); spinsystem.flip(); energy_new = spinsystem.getHamiltonian(); // check metropolis criterion: if( ! acceptance(energy_old, energy_new, parameters->getTemperature()) ) { spinsystem.flip_back(); #ifndef NDEBUG Logger::getInstance().debug_new_line("[mc]", "move rejected, new H would have been: ", energy_new); } else { Logger::getInstance().debug_new_line("[mc]", "move accepted, new H: ", energy_new); Logger::getInstance().debug_new_line(spinsystem.str()); #endif } } if( !EQUILMODE ) { energies.push_back(spinsystem.getHamiltonian()); magnetisations.push_back(spinsystem.getMagnetisation()); } } /* * DER HIER FOLGENDE TEIL DER KLASSE IST NICHT RELEVANT FUER * DIE IMPLEMENTIERUNGSAUFGABEN UND KANN IGNORIERT WERDEN ! */ MonteCarloHost::MonteCarloHost() { qDebug() << __PRETTY_FUNCTION__; } MonteCarloHost::~MonteCarloHost() { qDebug() << __PRETTY_FUNCTION__; } const Spinsystem& MonteCarloHost::getSpinsystem() const { qDebug() << __PRETTY_FUNCTION__; return spinsystem; } void MonteCarloHost::setParameters(BaseParametersWidget* prms) { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(prms); parameters = prms; Q_CHECK_PTR(parameters); } void MonteCarloHost::setup() { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(parameters); spinsystem.setParameters(parameters); spinsystem.setup(); clearRecords(); } void MonteCarloHost::resetSpins() { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(parameters); if( parameters->getWavelengthPattern() ) { spinsystem.resetSpinsCosinus(parameters->getWavelength()); } else { spinsystem.resetSpins(); } } void MonteCarloHost::clearRecords() { qDebug() << __PRETTY_FUNCTION__; energies.clear(); magnetisations.clear(); spinsystem.resetParameters(); } void MonteCarloHost::print_data() const { // save to file: step J T B H M qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving data ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".data"); std::ofstream FILE; FILE.open(filekey); // print header line FILE << std::setw(14) << "# step" << std::setw(8) << "J" << std::setw(8) << "T" << std::setw(8) << "B" << std::setw(14) << "H" << std::setw(14) << "M" << '\n'; assert(energies.size() == magnetisations.size()); for(unsigned int i=0; i<energies.size(); ++i) { FILE << std::setw(14) << std::fixed << std::setprecision(0)<< (i+1)*parameters->getPrintFreq() << std::setw(8) << std::fixed << std::setprecision(2)<< parameters->getInteraction() << std::setw(8) << std::fixed << std::setprecision(2)<< parameters->getTemperature() << std::setw(8) << std::fixed << std::setprecision(2)<< parameters->getMagnetic() << std::setw(14) << std::fixed << std::setprecision(2) << energies[i] << std::setw(14) << std::fixed << std::setprecision(6) << magnetisations[i]; FILE << '\n'; } FILE.close(); } void MonteCarloHost::print_averages() const { // compute averages and save to file: <energy> <magnetisation> <susceptibility> <heat capacity> qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving averaged data ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".averaged_data"); std::ofstream FILE; if( ! enhance::fileExists(filekey) ) { // print header line FILE.open(filekey); FILE << std::setw(8) << "J" << std::setw(8) << "T" << std::setw(8) << "B" << std::setw(14) << "<H>" << std::setw(14) << "<M>" << std::setw(18) << "<chi>" << std::setw(18) << "<Cv>" << std::setw(14) << "# of samples" << '\n'; } else { FILE.open(filekey, std::ios::app); } double averageEnergies = std::accumulate(std::begin(energies), std::end(energies), 0.0) / energies.size(); double averageEnergiesSquared = std::accumulate(std::begin(energies), std::end(energies), 0.0, [](auto lhs, auto rhs){ return lhs + rhs*rhs; }) / energies.size(); double averageMagnetisations = std::accumulate(std::begin(magnetisations), std::end(magnetisations), 0.0) / magnetisations.size(); double averageMagnetisationsSquared = std::accumulate(std::begin(magnetisations), std::end(magnetisations), 0.0, [](auto lhs, auto rhs){ return lhs + rhs*rhs; }) / magnetisations.size(); double denominator = std::pow(parameters->getTemperature(),2) * std::pow(parameters->getWidth()*parameters->getHeight(),2); FILE << std::setw(8) << std::fixed << std::setprecision(2) << parameters->getInteraction() << std::setw(8) << std::fixed << std::setprecision(2) << parameters->getTemperature() << std::setw(8) << std::fixed << std::setprecision(2) << parameters->getMagnetic() << std::setw(14) << std::fixed << std::setprecision(2) << averageEnergies << std::setw(14) << std::fixed << std::setprecision(6) << averageMagnetisations << std::setw(18) << std::fixed << std::setprecision(10) << (averageMagnetisationsSquared - averageMagnetisations*averageMagnetisations) / parameters->getTemperature() << std::setw(18) << std::fixed << std::setprecision(10) << (averageEnergiesSquared - averageEnergies*averageEnergies) / denominator << std::setw(14) << energies.size() << '\n'; FILE.close(); } void MonteCarloHost::print_correlation(Histogram<double>& correlation) const { // save correlation of current state in file qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving correlation function G(r) ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".correlation"); std::ofstream FILE(filekey); FILE << "# correlation G(r) = <S(0) S(r)> - <S>^2\n"; FILE << correlation.formatted_string(); FILE.close(); } void MonteCarloHost::print_structureFunction(Histogram<double>& structureFunction) const { // save structure Function of current state in file qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving structure function S(k) ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".structureFunction"); std::ofstream FILE(filekey); FILE << "# structure function S(k) = FT( G(r) )\n"; FILE << structureFunction.formatted_string(); FILE.close(); } <commit_msg>now also compiling in debug mode<commit_after>#include "montecarlohost.hpp" // optional: bool MonteCarloHost::acceptance(const double Eold, const double Enew, const double temperature) { #ifndef NDEBUG double random = enhance::random_double(0.0, 1.0); double condition = std::exp(-(Enew-Eold)/temperature); Logger::getInstance().debug_new_line("[mc]", "random = ", random, ", exp(-(energy_new-energy_old)/temperature) = ", condition); return random < condition ? true : false; #endif return enhance::random_double(0.0, 1.0) < std::exp(-(Enew-Eold)/temperature) ? true : false; } void MonteCarloHost::run(const unsigned long& steps, const bool EQUILMODE) { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(parameters); /* Aufgabe 1.6: * * input: steps: Anzahl MC Steps die durchgeführt werden sollen, * EQUILMODE: Modus des Runs * return: / * Funktion: Durchführung der MC Schritte, Akzeptanz/Rückweisung der * Schritte nach dem Metropoliskriterium. * Bei EQUILMODE = false: Speichern der aktuellen Werte von * Hamiltonian und Magnetisierung nach Durchführung der Schritte * durch anhängen an die Membervariablen energies und magnetisations. * Optional: Auslagern des Akzeptanz-Checks in zusätzliche Funktion * */ double energy_old; double energy_new; for(unsigned int t=0; t<steps; ++t) { // flip spin: energy_old = spinsystem.getHamiltonian(); spinsystem.flip(); energy_new = spinsystem.getHamiltonian(); // check metropolis criterion: if( ! acceptance(energy_old, energy_new, parameters->getTemperature()) ) { spinsystem.flip_back(); #ifndef NDEBUG Logger::getInstance().debug_new_line("[mc]", "move rejected, new H would have been: ", energy_new); } else { Logger::getInstance().debug_new_line("[mc]", "move accepted, new H: ", energy_new); Logger::getInstance().debug_new_line(spinsystem.getStringOfSystem()); #endif } } if( !EQUILMODE ) { energies.push_back(spinsystem.getHamiltonian()); magnetisations.push_back(spinsystem.getMagnetisation()); } } /* * DER HIER FOLGENDE TEIL DER KLASSE IST NICHT RELEVANT FUER * DIE IMPLEMENTIERUNGSAUFGABEN UND KANN IGNORIERT WERDEN ! */ MonteCarloHost::MonteCarloHost() { qDebug() << __PRETTY_FUNCTION__; } MonteCarloHost::~MonteCarloHost() { qDebug() << __PRETTY_FUNCTION__; } const Spinsystem& MonteCarloHost::getSpinsystem() const { qDebug() << __PRETTY_FUNCTION__; return spinsystem; } void MonteCarloHost::setParameters(BaseParametersWidget* prms) { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(prms); parameters = prms; Q_CHECK_PTR(parameters); } void MonteCarloHost::setup() { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(parameters); spinsystem.setParameters(parameters); spinsystem.setup(); clearRecords(); } void MonteCarloHost::resetSpins() { qDebug() << __PRETTY_FUNCTION__; Q_CHECK_PTR(parameters); if( parameters->getWavelengthPattern() ) { spinsystem.resetSpinsCosinus(parameters->getWavelength()); } else { spinsystem.resetSpins(); } } void MonteCarloHost::clearRecords() { qDebug() << __PRETTY_FUNCTION__; energies.clear(); magnetisations.clear(); spinsystem.resetParameters(); } void MonteCarloHost::print_data() const { // save to file: step J T B H M qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving data ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".data"); std::ofstream FILE; FILE.open(filekey); // print header line FILE << std::setw(14) << "# step" << std::setw(8) << "J" << std::setw(8) << "T" << std::setw(8) << "B" << std::setw(14) << "H" << std::setw(14) << "M" << '\n'; assert(energies.size() == magnetisations.size()); for(unsigned int i=0; i<energies.size(); ++i) { FILE << std::setw(14) << std::fixed << std::setprecision(0)<< (i+1)*parameters->getPrintFreq() << std::setw(8) << std::fixed << std::setprecision(2)<< parameters->getInteraction() << std::setw(8) << std::fixed << std::setprecision(2)<< parameters->getTemperature() << std::setw(8) << std::fixed << std::setprecision(2)<< parameters->getMagnetic() << std::setw(14) << std::fixed << std::setprecision(2) << energies[i] << std::setw(14) << std::fixed << std::setprecision(6) << magnetisations[i]; FILE << '\n'; } FILE.close(); } void MonteCarloHost::print_averages() const { // compute averages and save to file: <energy> <magnetisation> <susceptibility> <heat capacity> qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving averaged data ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".averaged_data"); std::ofstream FILE; if( ! enhance::fileExists(filekey) ) { // print header line FILE.open(filekey); FILE << std::setw(8) << "J" << std::setw(8) << "T" << std::setw(8) << "B" << std::setw(14) << "<H>" << std::setw(14) << "<M>" << std::setw(18) << "<chi>" << std::setw(18) << "<Cv>" << std::setw(14) << "# of samples" << '\n'; } else { FILE.open(filekey, std::ios::app); } double averageEnergies = std::accumulate(std::begin(energies), std::end(energies), 0.0) / energies.size(); double averageEnergiesSquared = std::accumulate(std::begin(energies), std::end(energies), 0.0, [](auto lhs, auto rhs){ return lhs + rhs*rhs; }) / energies.size(); double averageMagnetisations = std::accumulate(std::begin(magnetisations), std::end(magnetisations), 0.0) / magnetisations.size(); double averageMagnetisationsSquared = std::accumulate(std::begin(magnetisations), std::end(magnetisations), 0.0, [](auto lhs, auto rhs){ return lhs + rhs*rhs; }) / magnetisations.size(); double denominator = std::pow(parameters->getTemperature(),2) * std::pow(parameters->getWidth()*parameters->getHeight(),2); FILE << std::setw(8) << std::fixed << std::setprecision(2) << parameters->getInteraction() << std::setw(8) << std::fixed << std::setprecision(2) << parameters->getTemperature() << std::setw(8) << std::fixed << std::setprecision(2) << parameters->getMagnetic() << std::setw(14) << std::fixed << std::setprecision(2) << averageEnergies << std::setw(14) << std::fixed << std::setprecision(6) << averageMagnetisations << std::setw(18) << std::fixed << std::setprecision(10) << (averageMagnetisationsSquared - averageMagnetisations*averageMagnetisations) / parameters->getTemperature() << std::setw(18) << std::fixed << std::setprecision(10) << (averageEnergiesSquared - averageEnergies*averageEnergies) / denominator << std::setw(14) << energies.size() << '\n'; FILE.close(); } void MonteCarloHost::print_correlation(Histogram<double>& correlation) const { // save correlation of current state in file qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving correlation function G(r) ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".correlation"); std::ofstream FILE(filekey); FILE << "# correlation G(r) = <S(0) S(r)> - <S>^2\n"; FILE << correlation.formatted_string(); FILE.close(); } void MonteCarloHost::print_structureFunction(Histogram<double>& structureFunction) const { // save structure Function of current state in file qDebug() << __PRETTY_FUNCTION__; Logger::getInstance().debug_new_line("[mc]", "saving structure function S(k) ..."); Q_CHECK_PTR(parameters); std::string filekeystring = parameters->getFileKey(); std::string filekey = filekeystring.substr( 0, filekeystring.find_first_of(" ") ); filekey.append(".structureFunction"); std::ofstream FILE(filekey); FILE << "# structure function S(k) = FT( G(r) )\n"; FILE << structureFunction.formatted_string(); FILE.close(); } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdint> #include <vector> #include <stack> #include <functional> #define ZFLAG(loc, exp) loc.zf=((exp)==0) enum e_opcode : uint8_t { mov = 0x00, or = 0x01, xor = 0x02, and = 0x03, not = 0x04, add = 0x05, sub = 0x06, mul = 0x07, shl = 0x08, shr = 0x09, inc = 0x0a, dec = 0x0b, push = 0x0c, pop = 0x0d, cmp = 0x0e, jnz = 0x0f, jz = 0x10 }; enum e_reg : uint8_t { r0 = 0, r1 = 1, r2 = 2, r3 = 3 }; enum e_mod : uint8_t { imm = 0, reg = 1, reg_imm = 2, reg_reg = 3 }; char* disasm_opcode[] { "mov ", "or ", "xor ", "and ", "not ", "add ", "sub ", "mul ", "shl ", "shr ", "inc ", "dec ", "push", "pop ", "cmp ", "jnz ", "jz " }; char* disasm_mod[0x04] { "imm ", "reg ", "reg-imm", "reg-reg" }; char* disasm_reg[0x04] { "r0", "r1", "r2", "r3" }; struct instruction_minimal { e_opcode code : 8; e_mod mod : 4; e_reg dst_reg : 2; e_reg src_reg : 2; }; struct instruction { typedef std::vector<instruction> list; instruction_minimal base; uint16_t imm = 0; instruction(uint16_t* bytes) : base(*reinterpret_cast<instruction_minimal*>(bytes)) { } }; static struct { std::stack<uint16_t> stack; bool zf; uint16_t pc; uint16_t registers[4]; } cpu; std::function<void(uint16_t* dst, const uint16_t value)> ops[0x11] = { [](auto dst, auto value) { *dst = value; }, // mov [](auto dst, auto value) { ZFLAG(cpu, *dst |= value); }, // or [](auto dst, auto value) { ZFLAG(cpu, *dst ^= value); }, // xor [](auto dst, auto value) { ZFLAG(cpu, *dst &= value); }, // and [](auto dst, auto value) { ZFLAG(cpu, *dst = ~*dst); }, // neg [](auto dst, auto value) { ZFLAG(cpu, *dst += value); }, // add [](auto dst, auto value) { ZFLAG(cpu, *dst -= value); }, // sub [](auto dst, auto value) { ZFLAG(cpu, *dst *= value); }, // mul [](auto dst, auto value) { ZFLAG(cpu, *dst <<= value); }, // shl [](auto dst, auto value) { ZFLAG(cpu, *dst >>= value); }, // shr [](auto dst, auto value) { ZFLAG(cpu, ++*dst); }, // inc [](auto dst, auto value) { ZFLAG(cpu, --*dst); }, // dec [](auto dst, auto value) { cpu.stack.push(value); }, // push [](auto dst, auto value) { *dst = cpu.stack.top(); cpu.stack.pop(); }, // pop [](auto dst, auto value) { ZFLAG(cpu, *dst - value); }, // cmp [](auto dst, auto value) { if (!cpu.zf) cpu.pc = value; }, // jnz [](auto dst, auto value) { if (cpu.zf) cpu.pc = value; } // jz }; bool load(const char* path, instruction::list& output) { FILE* file = ::fopen(path, "rb"); uint16_t buf; bool new_instruction = true; if (!file) return false; while (::fread(&buf, sizeof(uint16_t), 1, file) == 1) { size_t ipc = output.size() - 1; if (new_instruction) { output.push_back(&buf); ++ipc; if (output[ipc].base.mod == reg_imm || output[ipc].base.mod == imm) { new_instruction = false; } } else { output[ipc].imm = buf; new_instruction = true; } } ::fclose(file); return new_instruction == true; // if reached EOF before new instruction then instruction is incomplete and code is corrupted } void trace(const instruction& instr) { switch (instr.base.mod) { case imm: ::printf("%s %x\n", disasm_opcode[instr.base.code], instr.imm); break; case reg: ::printf("%s %s\n", disasm_opcode[instr.base.code], disasm_reg[instr.base.dst_reg]); break; case reg_imm: ::printf("%s %s, %x\n", disasm_opcode[instr.base.code], disasm_reg[instr.base.dst_reg], instr.imm); break; case reg_reg: ::printf("%s %s, %s\n", disasm_opcode[instr.base.code], disasm_reg[instr.base.dst_reg], disasm_reg[instr.base.src_reg]); break; } } void disasm(const instruction::list& bytecode) { ::puts("Static disassembly: \n"); for (size_t i = 0; i < bytecode.size(); ++i) { switch (bytecode[i].base.mod) { case imm: ::printf("[%02x] %s %x\n", i, disasm_opcode[bytecode[i].base.code], bytecode[i].imm); break; case reg: ::printf("[%02x] %s %s\n", i, disasm_opcode[bytecode[i].base.code], disasm_reg[bytecode[i].base.dst_reg]); break; case reg_imm: ::printf("[%02x] %s %s, %x\n", i, disasm_opcode[bytecode[i].base.code], disasm_reg[bytecode[i].base.dst_reg], bytecode[i].imm); break; case reg_reg: ::printf("[%02x] %s %s, %s\n", i, disasm_opcode[bytecode[i].base.code], disasm_reg[bytecode[i].base.dst_reg], disasm_reg[bytecode[i].base.src_reg]); break; } } ::puts("\n"); } static void exec(const instruction::list& bytecode) { cpu.pc = cpu.zf = 0; cpu.registers[0] = cpu.registers[1] = cpu.registers[2] = cpu.registers[3] = 0; cpu.stack = std::stack<uint16_t>(); while (cpu.pc != bytecode.size()) { uint16_t* ptr = nullptr; uint16_t value = 0; const size_t pc_current = cpu.pc++; if (bytecode[pc_current].base.mod == imm) { value = bytecode[pc_current].imm; } else if (bytecode[pc_current].base.mod == reg) { ptr = &cpu.registers[bytecode[pc_current].base.dst_reg]; } else if (bytecode[pc_current].base.mod == reg_imm) { ptr = &cpu.registers[bytecode[pc_current].base.dst_reg]; value = bytecode[pc_current].imm; } else if (bytecode[pc_current].base.mod == reg_reg) { ptr = &cpu.registers[bytecode[pc_current].base.dst_reg]; value = cpu.registers[bytecode[pc_current].base.src_reg]; } #ifdef _DEBUG trace(bytecode[pc_current]); #endif ops[bytecode[pc_current].base.code](ptr, value); } ::printf("reg0=%04x&reg1=%04x&reg2=%04x&reg3=%04x", cpu.registers[0], cpu.registers[1], cpu.registers[2], cpu.registers[3]); } int main(int argc, char* argv[]) { instruction::list bytecode; static_assert(sizeof(instruction) == sizeof(uint16_t) * 2, "Size of instruction isn't 32 bits!"); if (argc < 2) { ::fprintf(stderr, "No file specified."); } else if (load(argv[1], bytecode)) { #ifdef _DEBUG disasm(bytecode); #endif exec(bytecode); } else { ::fprintf(stderr, "Assembly is corrupted."); } return 0; } <commit_msg>Fixed array size error<commit_after>#include <cstdio> #include <cstdint> #include <vector> #include <stack> #include <functional> #define ZFLAG(loc, exp) loc.zf=((exp)==0) enum e_opcode : uint8_t { mov = 0x00, or = 0x01, xor = 0x02, and = 0x03, not = 0x04, add = 0x05, sub = 0x06, mul = 0x07, shl = 0x08, shr = 0x09, inc = 0x0a, dec = 0x0b, push = 0x0c, pop = 0x0d, cmp = 0x0e, jnz = 0x0f, jz = 0x10 }; enum e_reg : uint8_t { r0 = 0, r1 = 1, r2 = 2, r3 = 3 }; enum e_mod : uint8_t { imm = 0, reg = 1, reg_imm = 2, reg_reg = 3 }; char* disasm_opcode[] { "mov ", "or ", "xor ", "and ", "not ", "add ", "sub ", "mul ", "shl ", "shr ", "inc ", "dec ", "push", "pop ", "cmp ", "jnz ", "jz " }; char* disasm_mod[] { "imm ", "reg ", "reg-imm", "reg-reg" }; char* disasm_reg[] { "r0", "r1", "r2", "r3" }; struct instruction_minimal { e_opcode code : 8; e_mod mod : 4; e_reg dst_reg : 2; e_reg src_reg : 2; }; struct instruction { typedef std::vector<instruction> list; instruction_minimal base; uint16_t imm = 0; instruction(uint16_t* bytes) : base(*reinterpret_cast<instruction_minimal*>(bytes)) { } }; static struct { std::stack<uint16_t> stack; bool zf; uint16_t pc; uint16_t registers[4]; } cpu; std::function<void(uint16_t* dst, const uint16_t value)> ops[0x11] = { [](auto dst, auto value) { *dst = value; }, // mov [](auto dst, auto value) { ZFLAG(cpu, *dst |= value); }, // or [](auto dst, auto value) { ZFLAG(cpu, *dst ^= value); }, // xor [](auto dst, auto value) { ZFLAG(cpu, *dst &= value); }, // and [](auto dst, auto value) { ZFLAG(cpu, *dst = ~*dst); }, // neg [](auto dst, auto value) { ZFLAG(cpu, *dst += value); }, // add [](auto dst, auto value) { ZFLAG(cpu, *dst -= value); }, // sub [](auto dst, auto value) { ZFLAG(cpu, *dst *= value); }, // mul [](auto dst, auto value) { ZFLAG(cpu, *dst <<= value); }, // shl [](auto dst, auto value) { ZFLAG(cpu, *dst >>= value); }, // shr [](auto dst, auto value) { ZFLAG(cpu, ++*dst); }, // inc [](auto dst, auto value) { ZFLAG(cpu, --*dst); }, // dec [](auto dst, auto value) { cpu.stack.push(value); }, // push [](auto dst, auto value) { *dst = cpu.stack.top(); cpu.stack.pop(); }, // pop [](auto dst, auto value) { ZFLAG(cpu, *dst - value); }, // cmp [](auto dst, auto value) { if (!cpu.zf) cpu.pc = value; }, // jnz [](auto dst, auto value) { if (cpu.zf) cpu.pc = value; } // jz }; bool load(const char* path, instruction::list& output) { FILE* file = ::fopen(path, "rb"); uint16_t buf; bool new_instruction = true; if (!file) return false; while (::fread(&buf, sizeof(uint16_t), 1, file) == 1) { size_t ipc = output.size() - 1; if (new_instruction) { output.push_back(&buf); ++ipc; if (output[ipc].base.mod == reg_imm || output[ipc].base.mod == imm) { new_instruction = false; } } else { output[ipc].imm = buf; new_instruction = true; } } ::fclose(file); return new_instruction == true; // if reached EOF before new instruction then instruction is incomplete and code is corrupted } void trace(const instruction& instr) { switch (instr.base.mod) { case imm: ::printf("%s %x\n", disasm_opcode[instr.base.code], instr.imm); break; case reg: ::printf("%s %s\n", disasm_opcode[instr.base.code], disasm_reg[instr.base.dst_reg]); break; case reg_imm: ::printf("%s %s, %x\n", disasm_opcode[instr.base.code], disasm_reg[instr.base.dst_reg], instr.imm); break; case reg_reg: ::printf("%s %s, %s\n", disasm_opcode[instr.base.code], disasm_reg[instr.base.dst_reg], disasm_reg[instr.base.src_reg]); break; } } void disasm(const instruction::list& bytecode) { ::puts("Static disassembly: \n"); for (size_t i = 0; i < bytecode.size(); ++i) { switch (bytecode[i].base.mod) { case imm: ::printf("[%02x] %s %x\n", i, disasm_opcode[bytecode[i].base.code], bytecode[i].imm); break; case reg: ::printf("[%02x] %s %s\n", i, disasm_opcode[bytecode[i].base.code], disasm_reg[bytecode[i].base.dst_reg]); break; case reg_imm: ::printf("[%02x] %s %s, %x\n", i, disasm_opcode[bytecode[i].base.code], disasm_reg[bytecode[i].base.dst_reg], bytecode[i].imm); break; case reg_reg: ::printf("[%02x] %s %s, %s\n", i, disasm_opcode[bytecode[i].base.code], disasm_reg[bytecode[i].base.dst_reg], disasm_reg[bytecode[i].base.src_reg]); break; } } ::puts("\n"); } static void exec(const instruction::list& bytecode) { cpu.pc = cpu.zf = 0; cpu.registers[0] = cpu.registers[1] = cpu.registers[2] = cpu.registers[3] = 0; cpu.stack = std::stack<uint16_t>(); while (cpu.pc != bytecode.size()) { uint16_t* ptr = nullptr; uint16_t value = 0; const size_t pc_current = cpu.pc++; if (bytecode[pc_current].base.mod == imm) { value = bytecode[pc_current].imm; } else if (bytecode[pc_current].base.mod == reg) { ptr = &cpu.registers[bytecode[pc_current].base.dst_reg]; } else if (bytecode[pc_current].base.mod == reg_imm) { ptr = &cpu.registers[bytecode[pc_current].base.dst_reg]; value = bytecode[pc_current].imm; } else if (bytecode[pc_current].base.mod == reg_reg) { ptr = &cpu.registers[bytecode[pc_current].base.dst_reg]; value = cpu.registers[bytecode[pc_current].base.src_reg]; } #ifdef _DEBUG trace(bytecode[pc_current]); #endif ops[bytecode[pc_current].base.code](ptr, value); } ::printf("reg0=%04x&reg1=%04x&reg2=%04x&reg3=%04x", cpu.registers[0], cpu.registers[1], cpu.registers[2], cpu.registers[3]); } int main(int argc, char* argv[]) { instruction::list bytecode; static_assert(sizeof(instruction) == sizeof(uint16_t) * 2, "Size of instruction isn't 32 bits!"); if (argc < 2) { ::fprintf(stderr, "No file specified."); } else if (load(argv[1], bytecode)) { #ifdef _DEBUG disasm(bytecode); #endif exec(bytecode); } else { ::fprintf(stderr, "Assembly is corrupted."); } return 0; } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * 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 "BLERoles.h" #if BLE_FEATURE_SECURITY #include "FileSecurityDb.h" namespace ble { namespace generic { const uint16_t DB_VERSION = 1; #define DB_STORE_OFFSET_FLAGS (0) #define DB_STORE_OFFSET_LOCAL_KEYS (DB_STORE_OFFSET_FLAGS + sizeof(SecurityDistributionFlags_t)) #define DB_STORE_OFFSET_PEER_KEYS (DB_STORE_OFFSET_LOCAL_KEYS + sizeof(SecurityEntryKeys_t)) #define DB_STORE_OFFSET_PEER_IDENTITY (DB_STORE_OFFSET_PEER_KEYS + sizeof(SecurityEntryKeys_t)) #define DB_STORE_OFFSET_PEER_SIGNING (DB_STORE_OFFSET_PEER_IDENTITY + sizeof(SecurityEntryIdentity_t)) #define DB_STORE_OFFSET_LOCAL_KEYS_LTK (DB_STORE_OFFSET_LOCAL_KEYS) #define DB_STORE_OFFSET_LOCAL_KEYS_EDIV (DB_STORE_OFFSET_LOCAL_KEYS_LTK + sizeof(ltk_t)) #define DB_STORE_OFFSET_LOCAL_KEYS_RAND (DB_STORE_OFFSET_LOCAL_KEYS_EDIV + sizeof(ediv_t)) #define DB_STORE_OFFSET_PEER_KEYS_LTK (DB_STORE_OFFSET_PEER_KEYS) #define DB_STORE_OFFSET_PEER_KEYS_EDIV (DB_STORE_OFFSET_PEER_KEYS_LTK + sizeof(ltk_t)) #define DB_STORE_OFFSET_PEER_KEYS_RAND (DB_STORE_OFFSET_PEER_KEYS_EDIV + sizeof(ediv_t)) #define DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS (DB_STORE_OFFSET_PEER_IDENTITY) #define DB_STORE_OFFSET_PEER_IDENTITY_IRK (DB_STORE_OFFSET_PEER_IDENTITY + sizeof(address_t)) #define DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS_IS_PUBLIC (DB_STORE_OFFSET_PEER_IDENTITY_IRK + sizeof(irk_t)) #define DB_STORE_OFFSET_PEER_SIGNING_COUNT (DB_STORE_OFFSET_PEER_SIGNING + sizeof(csrk_t)) /* make size multiple of 4 */ #define PAD4(value) ((((value - 1) / 4) * 4) + 4) #define DB_SIZE_STORE \ PAD4( \ sizeof(SecurityDistributionFlags_t) + \ sizeof(SecurityEntryKeys_t) + \ sizeof(SecurityEntryKeys_t) + \ sizeof(SecurityEntryIdentity_t) + \ sizeof(SecurityEntrySigning_t) \ ) #define DB_SIZE_STORES \ (FileSecurityDb::MAX_ENTRIES * DB_SIZE_STORE) #define DB_OFFSET_VERSION (0) #define DB_OFFSET_RESTORE (DB_OFFSET_VERSION + sizeof(DB_VERSION)) #define DB_OFFSET_LOCAL_IDENTITY (DB_OFFSET_RESTORE + sizeof(bool)) #define DB_OFFSET_LOCAL_CSRK (DB_OFFSET_LOCAL_IDENTITY + sizeof(SecurityEntryIdentity_t)) #define DB_OFFSET_LOCAL_SIGN_COUNT (DB_OFFSET_LOCAL_CSRK + sizeof(csrk_t)) #define DB_OFFSET_STORES (DB_OFFSET_LOCAL_SIGN_COUNT + sizeof(sign_count_t)) #define DB_OFFSET_MAX (DB_OFFSET_STORES + DB_SIZE_STORES) #define DB_SIZE PAD4(DB_OFFSET_MAX) typedef SecurityDb::entry_handle_t entry_handle_t; FileSecurityDb::FileSecurityDb(FILE *db_file) : SecurityDb(), _db_file(db_file) { /* init the offset in entries so they point to file positions */ for (size_t i = 0; i < get_entry_count(); i++) { _entries[i].file_offset = DB_OFFSET_STORES + i * DB_SIZE_STORE; } } FileSecurityDb::~FileSecurityDb() { fclose(_db_file); } FILE* FileSecurityDb::open_db_file(const char *db_path) { if (!db_path) { return NULL; } /* try to open an existing file */ FILE *db_file = fopen(db_path, "rb+"); if (!db_file) { /* file doesn't exist, create it */ db_file = fopen(db_path, "wb+"); } if (!db_file) { /* failed to create a file, abort */ return NULL; } /* we will check the db file and if the version or size doesn't match * what we expect we will blank it */ bool init = false; uint16_t version; fseek(db_file, DB_OFFSET_VERSION, SEEK_SET); if ((fread(&version, sizeof(version), 1, db_file) == 1) && (version == DB_VERSION)) { /* if file size differs from database size init the file */ fseek(db_file, 0, SEEK_END); if (ftell(db_file) != DB_SIZE) { init = true; } } else { init = true; } if (init) { return erase_db_file(db_file); } return db_file; } FILE* FileSecurityDb::erase_db_file(FILE* db_file) { fseek(db_file, 0, SEEK_SET); /* zero the file */ const uint32_t zero = 0; size_t count = DB_SIZE / 4; while (count--) { if (fwrite(&zero, sizeof(zero), 1, db_file) != 1) { fclose(db_file); return NULL; } } if (fflush(db_file)) { fclose(db_file); return NULL; } return db_file; } SecurityDistributionFlags_t* FileSecurityDb::get_distribution_flags( entry_handle_t db_handle ) { return reinterpret_cast<SecurityDistributionFlags_t*>(db_handle); } /* local keys */ /* set */ void FileSecurityDb::set_entry_local_ltk( entry_handle_t db_handle, const ltk_t &ltk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.ltk_sent = true; db_write(&ltk, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS_LTK); } void FileSecurityDb::set_entry_local_ediv_rand( entry_handle_t db_handle, const ediv_t &ediv, const rand_t &rand ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&ediv, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS_EDIV); db_write(&rand, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS_RAND); } /* peer's keys */ /* set */ void FileSecurityDb::set_entry_peer_ltk( entry_handle_t db_handle, const ltk_t &ltk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.ltk_stored = true; db_write(&ltk, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS_LTK); } void FileSecurityDb::set_entry_peer_ediv_rand( entry_handle_t db_handle, const ediv_t &ediv, const rand_t &rand ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&ediv, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS_EDIV); db_write(&rand, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS_RAND); } void FileSecurityDb::set_entry_peer_irk( entry_handle_t db_handle, const irk_t &irk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.irk_stored = true; db_write(&irk, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY_IRK); } void FileSecurityDb::set_entry_peer_bdaddr( entry_handle_t db_handle, bool address_is_public, const address_t &peer_address ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&peer_address, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS); db_write(&address_is_public, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS_IS_PUBLIC); } void FileSecurityDb::set_entry_peer_csrk( entry_handle_t db_handle, const csrk_t &csrk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.csrk_stored = true; db_write(&csrk, entry->file_offset + DB_STORE_OFFSET_PEER_SIGNING); } void FileSecurityDb::set_entry_peer_sign_counter( entry_handle_t db_handle, sign_count_t sign_counter ) { entry_t *entry = as_entry(db_handle); if (entry) { entry->peer_sign_counter = sign_counter; } } /* saving and loading from nvm */ void FileSecurityDb::restore() { /* restore if requested */ bool restore_toggle = false; db_read(&restore_toggle, DB_OFFSET_RESTORE); if (!restore_toggle) { erase_db_file(_db_file); db_write(&DB_VERSION, DB_OFFSET_VERSION); return; } db_read(&_local_identity, DB_OFFSET_LOCAL_IDENTITY); db_read(&_local_csrk, DB_OFFSET_LOCAL_CSRK); db_read(&_local_sign_counter, DB_OFFSET_LOCAL_SIGN_COUNT); /* read flags and sign counters */ for (size_t i = 0; i < get_entry_count(); i++) { db_read(&_entries[i].flags, _entries[i].file_offset + DB_STORE_OFFSET_FLAGS); db_read(&_entries[i].peer_sign_counter, _entries[i].file_offset + DB_STORE_OFFSET_PEER_SIGNING_COUNT); } } void FileSecurityDb::sync(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&entry->peer_sign_counter, entry->file_offset + DB_STORE_OFFSET_PEER_SIGNING_COUNT); db_write(&entry->flags, entry->file_offset + DB_STORE_OFFSET_FLAGS); } void FileSecurityDb::set_restore(bool reload) { db_write(&reload, DB_OFFSET_RESTORE); } /* helper functions */ uint8_t FileSecurityDb::get_entry_count() { return MAX_ENTRIES; } SecurityDistributionFlags_t* FileSecurityDb::get_entry_handle_by_index(uint8_t index) { if (index < MAX_ENTRIES) { return &_entries[index].flags; } else { return NULL; } } void FileSecurityDb::reset_entry(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return; } fseek(_db_file, entry->file_offset, SEEK_SET); const uint32_t zero = 0; size_t count = DB_SIZE_STORE / 4; while (count--) { fwrite(&zero, sizeof(zero), 1, _db_file); } entry->flags = SecurityDistributionFlags_t(); entry->peer_sign_counter = 0; } SecurityEntryIdentity_t* FileSecurityDb::read_in_entry_peer_identity(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } SecurityEntryIdentity_t* identity = reinterpret_cast<SecurityEntryIdentity_t*>(_buffer); db_read(identity, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY); return identity; }; SecurityEntryKeys_t* FileSecurityDb::read_in_entry_peer_keys(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer); db_read(keys, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS); return keys; }; SecurityEntryKeys_t* FileSecurityDb::read_in_entry_local_keys(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer); db_read(keys, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS); return keys; }; SecurityEntrySigning_t* FileSecurityDb::read_in_entry_peer_signing(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } /* only read in the csrk */ csrk_t* csrk = reinterpret_cast<csrk_t*>(_buffer); db_read(csrk, entry->file_offset + DB_STORE_OFFSET_PEER_SIGNING); /* use the counter held in memory */ SecurityEntrySigning_t* signing = reinterpret_cast<SecurityEntrySigning_t*>(_buffer); signing->counter = entry->peer_sign_counter; return signing; }; } /* namespace pal */ } /* namespace ble */ #endif // BLE_FEATURE_SECURITY <commit_msg>BLE - Remove conditional compilation of FileSecurityDb<commit_after>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * 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 "FileSecurityDb.h" namespace ble { namespace generic { const uint16_t DB_VERSION = 1; #define DB_STORE_OFFSET_FLAGS (0) #define DB_STORE_OFFSET_LOCAL_KEYS (DB_STORE_OFFSET_FLAGS + sizeof(SecurityDistributionFlags_t)) #define DB_STORE_OFFSET_PEER_KEYS (DB_STORE_OFFSET_LOCAL_KEYS + sizeof(SecurityEntryKeys_t)) #define DB_STORE_OFFSET_PEER_IDENTITY (DB_STORE_OFFSET_PEER_KEYS + sizeof(SecurityEntryKeys_t)) #define DB_STORE_OFFSET_PEER_SIGNING (DB_STORE_OFFSET_PEER_IDENTITY + sizeof(SecurityEntryIdentity_t)) #define DB_STORE_OFFSET_LOCAL_KEYS_LTK (DB_STORE_OFFSET_LOCAL_KEYS) #define DB_STORE_OFFSET_LOCAL_KEYS_EDIV (DB_STORE_OFFSET_LOCAL_KEYS_LTK + sizeof(ltk_t)) #define DB_STORE_OFFSET_LOCAL_KEYS_RAND (DB_STORE_OFFSET_LOCAL_KEYS_EDIV + sizeof(ediv_t)) #define DB_STORE_OFFSET_PEER_KEYS_LTK (DB_STORE_OFFSET_PEER_KEYS) #define DB_STORE_OFFSET_PEER_KEYS_EDIV (DB_STORE_OFFSET_PEER_KEYS_LTK + sizeof(ltk_t)) #define DB_STORE_OFFSET_PEER_KEYS_RAND (DB_STORE_OFFSET_PEER_KEYS_EDIV + sizeof(ediv_t)) #define DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS (DB_STORE_OFFSET_PEER_IDENTITY) #define DB_STORE_OFFSET_PEER_IDENTITY_IRK (DB_STORE_OFFSET_PEER_IDENTITY + sizeof(address_t)) #define DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS_IS_PUBLIC (DB_STORE_OFFSET_PEER_IDENTITY_IRK + sizeof(irk_t)) #define DB_STORE_OFFSET_PEER_SIGNING_COUNT (DB_STORE_OFFSET_PEER_SIGNING + sizeof(csrk_t)) /* make size multiple of 4 */ #define PAD4(value) ((((value - 1) / 4) * 4) + 4) #define DB_SIZE_STORE \ PAD4( \ sizeof(SecurityDistributionFlags_t) + \ sizeof(SecurityEntryKeys_t) + \ sizeof(SecurityEntryKeys_t) + \ sizeof(SecurityEntryIdentity_t) + \ sizeof(SecurityEntrySigning_t) \ ) #define DB_SIZE_STORES \ (FileSecurityDb::MAX_ENTRIES * DB_SIZE_STORE) #define DB_OFFSET_VERSION (0) #define DB_OFFSET_RESTORE (DB_OFFSET_VERSION + sizeof(DB_VERSION)) #define DB_OFFSET_LOCAL_IDENTITY (DB_OFFSET_RESTORE + sizeof(bool)) #define DB_OFFSET_LOCAL_CSRK (DB_OFFSET_LOCAL_IDENTITY + sizeof(SecurityEntryIdentity_t)) #define DB_OFFSET_LOCAL_SIGN_COUNT (DB_OFFSET_LOCAL_CSRK + sizeof(csrk_t)) #define DB_OFFSET_STORES (DB_OFFSET_LOCAL_SIGN_COUNT + sizeof(sign_count_t)) #define DB_OFFSET_MAX (DB_OFFSET_STORES + DB_SIZE_STORES) #define DB_SIZE PAD4(DB_OFFSET_MAX) typedef SecurityDb::entry_handle_t entry_handle_t; FileSecurityDb::FileSecurityDb(FILE *db_file) : SecurityDb(), _db_file(db_file) { /* init the offset in entries so they point to file positions */ for (size_t i = 0; i < get_entry_count(); i++) { _entries[i].file_offset = DB_OFFSET_STORES + i * DB_SIZE_STORE; } } FileSecurityDb::~FileSecurityDb() { fclose(_db_file); } FILE* FileSecurityDb::open_db_file(const char *db_path) { if (!db_path) { return NULL; } /* try to open an existing file */ FILE *db_file = fopen(db_path, "rb+"); if (!db_file) { /* file doesn't exist, create it */ db_file = fopen(db_path, "wb+"); } if (!db_file) { /* failed to create a file, abort */ return NULL; } /* we will check the db file and if the version or size doesn't match * what we expect we will blank it */ bool init = false; uint16_t version; fseek(db_file, DB_OFFSET_VERSION, SEEK_SET); if ((fread(&version, sizeof(version), 1, db_file) == 1) && (version == DB_VERSION)) { /* if file size differs from database size init the file */ fseek(db_file, 0, SEEK_END); if (ftell(db_file) != DB_SIZE) { init = true; } } else { init = true; } if (init) { return erase_db_file(db_file); } return db_file; } FILE* FileSecurityDb::erase_db_file(FILE* db_file) { fseek(db_file, 0, SEEK_SET); /* zero the file */ const uint32_t zero = 0; size_t count = DB_SIZE / 4; while (count--) { if (fwrite(&zero, sizeof(zero), 1, db_file) != 1) { fclose(db_file); return NULL; } } if (fflush(db_file)) { fclose(db_file); return NULL; } return db_file; } SecurityDistributionFlags_t* FileSecurityDb::get_distribution_flags( entry_handle_t db_handle ) { return reinterpret_cast<SecurityDistributionFlags_t*>(db_handle); } /* local keys */ /* set */ void FileSecurityDb::set_entry_local_ltk( entry_handle_t db_handle, const ltk_t &ltk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.ltk_sent = true; db_write(&ltk, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS_LTK); } void FileSecurityDb::set_entry_local_ediv_rand( entry_handle_t db_handle, const ediv_t &ediv, const rand_t &rand ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&ediv, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS_EDIV); db_write(&rand, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS_RAND); } /* peer's keys */ /* set */ void FileSecurityDb::set_entry_peer_ltk( entry_handle_t db_handle, const ltk_t &ltk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.ltk_stored = true; db_write(&ltk, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS_LTK); } void FileSecurityDb::set_entry_peer_ediv_rand( entry_handle_t db_handle, const ediv_t &ediv, const rand_t &rand ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&ediv, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS_EDIV); db_write(&rand, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS_RAND); } void FileSecurityDb::set_entry_peer_irk( entry_handle_t db_handle, const irk_t &irk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.irk_stored = true; db_write(&irk, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY_IRK); } void FileSecurityDb::set_entry_peer_bdaddr( entry_handle_t db_handle, bool address_is_public, const address_t &peer_address ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&peer_address, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS); db_write(&address_is_public, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY_ADDRESS_IS_PUBLIC); } void FileSecurityDb::set_entry_peer_csrk( entry_handle_t db_handle, const csrk_t &csrk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.csrk_stored = true; db_write(&csrk, entry->file_offset + DB_STORE_OFFSET_PEER_SIGNING); } void FileSecurityDb::set_entry_peer_sign_counter( entry_handle_t db_handle, sign_count_t sign_counter ) { entry_t *entry = as_entry(db_handle); if (entry) { entry->peer_sign_counter = sign_counter; } } /* saving and loading from nvm */ void FileSecurityDb::restore() { /* restore if requested */ bool restore_toggle = false; db_read(&restore_toggle, DB_OFFSET_RESTORE); if (!restore_toggle) { erase_db_file(_db_file); db_write(&DB_VERSION, DB_OFFSET_VERSION); return; } db_read(&_local_identity, DB_OFFSET_LOCAL_IDENTITY); db_read(&_local_csrk, DB_OFFSET_LOCAL_CSRK); db_read(&_local_sign_counter, DB_OFFSET_LOCAL_SIGN_COUNT); /* read flags and sign counters */ for (size_t i = 0; i < get_entry_count(); i++) { db_read(&_entries[i].flags, _entries[i].file_offset + DB_STORE_OFFSET_FLAGS); db_read(&_entries[i].peer_sign_counter, _entries[i].file_offset + DB_STORE_OFFSET_PEER_SIGNING_COUNT); } } void FileSecurityDb::sync(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } db_write(&entry->peer_sign_counter, entry->file_offset + DB_STORE_OFFSET_PEER_SIGNING_COUNT); db_write(&entry->flags, entry->file_offset + DB_STORE_OFFSET_FLAGS); } void FileSecurityDb::set_restore(bool reload) { db_write(&reload, DB_OFFSET_RESTORE); } /* helper functions */ uint8_t FileSecurityDb::get_entry_count() { return MAX_ENTRIES; } SecurityDistributionFlags_t* FileSecurityDb::get_entry_handle_by_index(uint8_t index) { if (index < MAX_ENTRIES) { return &_entries[index].flags; } else { return NULL; } } void FileSecurityDb::reset_entry(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return; } fseek(_db_file, entry->file_offset, SEEK_SET); const uint32_t zero = 0; size_t count = DB_SIZE_STORE / 4; while (count--) { fwrite(&zero, sizeof(zero), 1, _db_file); } entry->flags = SecurityDistributionFlags_t(); entry->peer_sign_counter = 0; } SecurityEntryIdentity_t* FileSecurityDb::read_in_entry_peer_identity(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } SecurityEntryIdentity_t* identity = reinterpret_cast<SecurityEntryIdentity_t*>(_buffer); db_read(identity, entry->file_offset + DB_STORE_OFFSET_PEER_IDENTITY); return identity; }; SecurityEntryKeys_t* FileSecurityDb::read_in_entry_peer_keys(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer); db_read(keys, entry->file_offset + DB_STORE_OFFSET_PEER_KEYS); return keys; }; SecurityEntryKeys_t* FileSecurityDb::read_in_entry_local_keys(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer); db_read(keys, entry->file_offset + DB_STORE_OFFSET_LOCAL_KEYS); return keys; }; SecurityEntrySigning_t* FileSecurityDb::read_in_entry_peer_signing(entry_handle_t db_entry) { entry_t *entry = as_entry(db_entry); if (!entry) { return NULL; } /* only read in the csrk */ csrk_t* csrk = reinterpret_cast<csrk_t*>(_buffer); db_read(csrk, entry->file_offset + DB_STORE_OFFSET_PEER_SIGNING); /* use the counter held in memory */ SecurityEntrySigning_t* signing = reinterpret_cast<SecurityEntrySigning_t*>(_buffer); signing->counter = entry->peer_sign_counter; return signing; }; } /* namespace pal */ } /* namespace ble */<|endoftext|>
<commit_before>#include "../utils/image.hpp" #include <vector> struct Point { static double distance(const Point &p0, const Point &p1) { double dx = p1.x - p0.x, dy = p1.y - p0.y; return sqrt(dx * dx + dy * dy); } Point(void) { } Point(double _x, double _y) : x(_x), y(_y) { } double x, y; }; struct Line { static Point intersection(const Line&, const Line&); Line(double x0, double y0, double x1, double y1) : p0(x0, y0), p1(x1, y1) { init(x0, y0, x1, y1); } Line(const Point &a, const Point &b) : p0(a), p1(b) { init(a.x, a.y, b.x, b.y); } bool above(const Point &p) const { return above(p.x, p.y); } bool above(double x, double y) const { double liney = m * x + b; return liney < y; } double length(void) const { return Point::distance(p0, p1); } bool contains(const Point &pt) const { return pt.x >= minx && pt.x <= maxx && pt.y >= miny && pt.y <= maxy; }; Point p0, p1; double minx, maxx, miny, maxy; double m, b; double theta; // angle from p0 to p1 private: void init(double x0, double y0, double x1, double y1); }; class Poly { public: Poly(unsigned int nverts, ...); Poly(unsigned int nverts, va_list); Poly(std::vector<Point> &_verts) : verts(_verts) { } static Poly random(unsigned int n, double xc, double yc, double r); static Poly triangle(double x, double y, double radius); static Poly square(double x, double y, double height); // If the width is <0 then the polygon is filled. void draw(Image&, Color, double width=1, bool number = false) const; bool willhit(const Line&) const; double minhit(const Line&) const; private: std::vector<Point> verts; }; <commit_msg>Reorder fields so that it looks prettier.<commit_after>#include "../utils/image.hpp" #include <vector> struct Point { static double distance(const Point &p0, const Point &p1) { double dx = p1.x - p0.x, dy = p1.y - p0.y; return sqrt(dx * dx + dy * dy); } Point(void) { } Point(double _x, double _y) : x(_x), y(_y) { } double x, y; }; struct Line { static Point intersection(const Line&, const Line&); Line(double x0, double y0, double x1, double y1) : p0(x0, y0), p1(x1, y1) { init(x0, y0, x1, y1); } Line(const Point &a, const Point &b) : p0(a), p1(b) { init(a.x, a.y, b.x, b.y); } bool above(const Point &p) const { return above(p.x, p.y); } bool above(double x, double y) const { double liney = m * x + b; return liney < y; } double length(void) const { return Point::distance(p0, p1); } bool contains(const Point &pt) const { return pt.x >= minx && pt.x <= maxx && pt.y >= miny && pt.y <= maxy; }; Point p0, p1; double m, b; double theta; // angle from p0 to p1 double minx, maxx, miny, maxy; private: void init(double x0, double y0, double x1, double y1); }; class Poly { public: Poly(unsigned int nverts, ...); Poly(unsigned int nverts, va_list); Poly(std::vector<Point> &_verts) : verts(_verts) { } static Poly random(unsigned int n, double xc, double yc, double r); static Poly triangle(double x, double y, double radius); static Poly square(double x, double y, double height); // If the width is <0 then the polygon is filled. void draw(Image&, Color, double width=1, bool number = false) const; bool willhit(const Line&) const; double minhit(const Line&) const; private: std::vector<Point> verts; }; <|endoftext|>
<commit_before>#include "console.h" #include <iostream> #include <string> #include <vector> #include "person.h" #include <algorithm> #include "data.h" #include <cctype> #include <ctype.h> using namespace std; Console::Console() { } bool Console::validYear(string s) { for (unsigned int i = 0; i < s.size(); i++) if (!isdigit(s[i])) return 0; return 1; } void Console::getInfo() { _pers = _dat.readData(); string command; char anotherOne; do { menu(command); if ((command == "Add") || (command == "add")) { add(anotherOne); } else if ((command == "View") || (command == "view")) { _pers = _dat.readData(); display(); } else if ((command == "Search") || (command == "search")) { } else if ((command == "Sort") || (command == "sort")) { int sortType = getSort(); displaySort(sortType); } }while((command != "Exit") && (command != "exit")); } int Console::getSort() { int sort; string sortInput; do { cout << endl; cout << "Please enter one of the following commands: " << endl; cout << "-------------------------------------------" << endl; cout << "1 - sort by alphabetical order" << endl; cout << "2 - sort by year of birth" << endl; cin >> sortInput; if(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2) cout << "Invalid input" << endl; }while(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2); sort = atoi(sortInput.c_str()); return sort; } void Console::displaySort(int& sort) { if(sort == 1) { _dom.alphabeticSort(_pers); display(); } else if (sort == 2) { _dom.ageSorting(_pers); display(); } } void Console::display() { cout << "Name" << "\t\t\t\t" << "Gender" << "\t" << "Born" << "\t" << "Died" << endl; for(unsigned int i = 0; i < _pers.size(); i++) { cout << _pers[i].getName() << "\t\t\t"; cout << _pers[i].getGender() << "\t"; cout <<_pers[i].getBirth() << "\t"; if(_pers[i].getDeath() == 0) { cout << "N/A" << endl; } else { cout << _pers[i].getDeath() << endl; cout << endl; } } } void Console::menu(string& command) { cout << "--------------------------------------------" << endl; cout << "Please enter one of the following commands: " << endl; cout << "Add - for adding scientist to the list" << endl; cout << "View - for viewing the whole list" << endl; cout << "Search - for searching for names in the list" << endl; cout << "Sort - for sorting" << endl; cout << "Exit - quits" << endl; cout << "--------------------------------------------" << endl; cin >> command; } void Console::add(char& anotherOne) { do{ std::string name; char gender; int birth = 0; int death = 0; addName(name); addGender(gender); addBirth(birth); addDeath(death, birth); addAnother(anotherOne); Person newData(name, gender, birth, death); _dat.writeData(newData); }while(anotherOne == 'y' || anotherOne == 'Y'); } void Console::addName(std::string& name) { cout << "Enter name of scientist: "; cin.ignore(); std::getline(std::cin, name); } void Console::addGender(char& gender) { do { cout << "Gender (f/m): "; cin >> gender; if(!(gender == 'm') && !(gender == 'f')) cout << "Invalid input!" <<endl; }while((gender != 'f') && (gender != 'm')); } void Console::addBirth(int& birth) { string birthInput; do{ cout << "Enter year of birth: "; cin >> birthInput; if(!validYear(birthInput)) { cout << "Invalid input!" <<endl; } } while(!validYear(birthInput)); birth = atoi(birthInput.c_str()); } void Console::addDeath(int& death, int& birth) { string deathInput; char status; cout << "Is the person alive? (Y/N): "; cin >> status; if(status == 'N' || status == 'n') { do{ cout << "Enter year of death : "; cin >> deathInput; if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth)) { cout << "Invalid input!" <<endl; } } while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth)); death = atoi(deathInput.c_str()); } cout << endl; } void Console::addAnother(char& anotherOne) { cout << "Add another? (Y/N): "; cin >> anotherOne; } string Console::searchName() { string chosenName; cout << "Who would you like to seach for? "; cin >> chosenName; return chosenName; } <commit_msg>´lagfæring á byrjunar útliti<commit_after>#include "console.h" #include <iostream> #include <string> #include <vector> #include "person.h" #include <algorithm> #include "data.h" #include <cctype> #include <ctype.h> using namespace std; Console::Console() { } bool Console::validYear(string s) { for (unsigned int i = 0; i < s.size(); i++) if (!isdigit(s[i])) return 0; return 1; } void Console::getInfo() { _pers = _dat.readData(); string command; char anotherOne; do { menu(command); if ((command == "Add") || (command == "add")) { add(anotherOne); } else if ((command == "View") || (command == "view")) { _pers = _dat.readData(); display(); } else if ((command == "Search") || (command == "search")) { } else if ((command == "Sort") || (command == "sort")) { int sortType = getSort(); displaySort(sortType); } }while((command != "Exit") && (command != "exit")); } int Console::getSort() { int sort; string sortInput; do { cout << endl; cout << "Please enter one of the following commands: " << endl; cout << "-------------------------------------------" << endl; cout << "1 - sort by alphabetical order" << endl; cout << "2 - sort by year of birth" << endl; cin >> sortInput; if(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2) cout << "Invalid input" << endl; }while(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2); sort = atoi(sortInput.c_str()); return sort; } void Console::displaySort(int& sort) { if(sort == 1) { _dom.alphabeticSort(_pers); display(); } else if (sort == 2) { _dom.ageSorting(_pers); display(); } } void Console::display() { cout << "Name" << "\t\t\t\t" << "Gender" << "\t" << "Born" << "\t" << "Died" << endl; for(unsigned int i = 0; i < _pers.size(); i++) { cout << _pers[i].getName() << "\t\t\t"; cout << _pers[i].getGender() << "\t"; cout <<_pers[i].getBirth() << "\t"; if(_pers[i].getDeath() == 0) { cout << "N/A" << endl; } else { cout << _pers[i].getDeath() << endl; cout << endl; } } } void Console::menu(string& command) { cout << endl << "--------------------------------------------" << endl; cout << "Please enter one of the following commands: " << endl << endl; cout << "Add - for adding scientist to the list" << endl; cout << "View - for viewing the whole list" << endl; cout << "Search - for searching for names in the list" << endl; cout << "Sort - for sorting" << endl; cout << "Exit - quits" << endl; cout << "--------------------------------------------" << endl << endl; cin >> command; } void Console::add(char& anotherOne) { do{ std::string name; char gender; int birth = 0; int death = 0; addName(name); addGender(gender); addBirth(birth); addDeath(death, birth); addAnother(anotherOne); Person newData(name, gender, birth, death); _dat.writeData(newData); }while(anotherOne == 'y' || anotherOne == 'Y'); } void Console::addName(std::string& name) { cout << endl << "Enter name of scientist: "; cin.ignore(); std::getline(std::cin, name); } void Console::addGender(char& gender) { do { cout << "Gender (f/m): "; cin >> gender; if(!(gender == 'm') && !(gender == 'f')) cout << "Invalid input!" <<endl; }while((gender != 'f') && (gender != 'm')); } void Console::addBirth(int& birth) { string birthInput; do{ cout << "Enter year of birth: "; cin >> birthInput; if(!validYear(birthInput)) { cout << "Invalid input!" <<endl; } } while(!validYear(birthInput)); birth = atoi(birthInput.c_str()); } void Console::addDeath(int& death, int& birth) { string deathInput; char status; cout << "Is the person alive? (Y/N): "; cin >> status; if(status == 'N' || status == 'n') { do{ cout << "Enter year of death : "; cin >> deathInput; if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth)) { cout << "Invalid input!" <<endl; } } while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth)); death = atoi(deathInput.c_str()); } cout << endl; } void Console::addAnother(char& anotherOne) { cout << "Add another? (Y/N): "; cin >> anotherOne; } string Console::searchName() { string chosenName; cout << "Who would you like to seach for? "; cin >> chosenName; return chosenName; } <|endoftext|>
<commit_before>/* nobleNote, a note taking application * Copyright (C) 2012 Christian Metscher <[email protected]>, Fabian Deuchler <[email protected]> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'. */ #include "textformattingtoolbar.h" #include <QAction> #include <QApplication> #include <QColorDialog> #include <QInputDialog> TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) : QToolBar(parent), textEdit_(textEdit) { setWindowTitle(tr("Format actions")); setObjectName(tr("Formattoolbar")); actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(":bold")), tr("&Bold"), this); actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); actionTextBold->setPriority(QAction::LowPriority); QFont bold; bold.setBold(true); actionTextBold->setFont(bold); connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText())); addAction(actionTextBold); actionTextBold->setCheckable(true); actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(":italic")), tr("&Italic"), this); actionTextItalic->setPriority(QAction::LowPriority); actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); QFont italic; italic.setItalic(true); actionTextItalic->setFont(italic); connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText())); addAction(actionTextItalic); actionTextItalic->setCheckable(true); actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(":underlined")), tr("&Underline"), this); actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); actionTextUnderline->setPriority(QAction::LowPriority); QFont underline; underline.setUnderline(true); actionTextUnderline->setFont(underline); connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText())); addAction(actionTextUnderline); actionTextUnderline->setCheckable(true); actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough", QIcon(":strikedout")), tr("&Strike Out"), this); actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S); actionTextStrikeOut->setPriority(QAction::LowPriority); QFont strikeOut; strikeOut.setStrikeOut(true); actionTextStrikeOut->setFont(strikeOut); connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText())); addAction(actionTextStrikeOut); actionTextStrikeOut->setCheckable(true); actionInsertHyperlink = new QAction(QIcon::fromTheme("hyperlink",QIcon(":hyperlink")),tr("&Hyperlink"),this); actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut actionInsertHyperlink->setPriority(QAction::LowPriority); connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink())); addAction(actionInsertHyperlink); QPixmap textPix(16, 16); textPix.fill(Qt::black); actionTextColor = new QAction(textPix, tr("&Text color..."), this); connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText())); addAction(actionTextColor); QPixmap bPix(16, 16); bPix.fill(Qt::white); actionTextBColor = new QAction(bPix, tr("&Background color..."), this); connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText())); addAction(actionTextBColor); fontComboBox = new QFontComboBox(this); fontComboBox->setFocusPolicy(Qt::TabFocus); addWidget(fontComboBox); connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString))); comboSize = new QComboBox(this); comboSize->setObjectName("comboSize"); addWidget(comboSize); comboSize->setEditable(true); connect(comboSize, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString))); QFontDatabase db; foreach(int size, db.standardSizes()) comboSize->addItem(QString::number(size)); comboSize->setCurrentIndex(comboSize->findText(QString::number( QApplication::font().pointSize()))); connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(getFontAndPointSizeOfText(QTextCharFormat))); } void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){ QTextCursor cursor = textEdit_->textCursor(); if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd()) cursor.select(QTextCursor::WordUnderCursor); cursor.mergeCharFormat(format); textEdit_->mergeCurrentCharFormat(format); } void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){ QFont f = format.font(); fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family())); comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); actionTextBold->setChecked(f.bold()); actionTextItalic->setChecked(f.italic()); actionTextUnderline->setChecked(f.underline()); actionTextStrikeOut->setChecked(f.strikeOut()); QPixmap textPix(16,16); textPix.fill(format.foreground().color()); actionTextColor->setIcon(textPix); QPixmap bPix(16,16); bPix.fill(format.background().color()); actionTextBColor->setIcon(bPix); } void TextFormattingToolbar::boldText(){ QTextCharFormat fmt; fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::italicText(){ QTextCharFormat fmt; fmt.setFontItalic(actionTextItalic->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::underlinedText(){ QTextCharFormat fmt; fmt.setFontUnderline(actionTextUnderline->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::strikedOutText(){ QTextCharFormat fmt; fmt.setFontStrikeOut(actionTextStrikeOut->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::coloredText(){ QColor col = QColorDialog::getColor(textEdit_->textColor(), this); if(!col.isValid()) return; QTextCharFormat fmt; fmt.setForeground(col); mergeFormatOnWordOrSelection(fmt); QPixmap pix(16, 16); pix.fill(col); actionTextColor->setIcon(pix); } void TextFormattingToolbar::markedText(){ QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this); if(!col.isValid()) return; QTextCharFormat fmt; fmt.setBackground(col); mergeFormatOnWordOrSelection(fmt); QPixmap pix(16, 16); pix.fill(col); actionTextColor->setIcon(pix); } void TextFormattingToolbar::insertHyperlink() { QTextCursor cursor = textEdit_->textCursor(); QString selectedText = cursor.selectedText(); bool ok; QString link = QInputDialog::getText(textEdit_,tr("Insert Hyperlink"),tr("Addr&ess:"),QLineEdit::Normal,selectedText,&ok); if(!ok) return; /*TODO: de-formatting if(link.isEmpty){ resetFonts()//or something like that return; }*/ /*TODO: check if link/e-mail is valid with the following regexps QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive) QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive) */ if(selectedText.isEmpty()) selectedText = link; if(link.contains("@")) cursor.insertHtml("<a href=mailto:"+link+"\">"+selectedText+"</a>"); else cursor.insertHtml("<a href=\""+link+"\">"+selectedText+"</a>"); } void TextFormattingToolbar::fontOfText(const QString &f){ QTextCharFormat fmt; fmt.setFontFamily(f); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::pointSizeOfText(const QString &p){ qreal pointSize = p.toFloat(); if(p.toFloat() > 0){ QTextCharFormat fmt; fmt.setFontPointSize(pointSize); mergeFormatOnWordOrSelection(fmt); } } <commit_msg>minor fix<commit_after>/* nobleNote, a note taking application * Copyright (C) 2012 Christian Metscher <[email protected]>, Fabian Deuchler <[email protected]> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'. */ #include "textformattingtoolbar.h" #include <QAction> #include <QApplication> #include <QColorDialog> #include <QInputDialog> TextFormattingToolbar::TextFormattingToolbar(QTextEdit * textEdit, QWidget *parent) : QToolBar(parent), textEdit_(textEdit) { setWindowTitle(tr("Format actions")); setObjectName(tr("Formattoolbar")); actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(":bold")), tr("&Bold"), this); actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); actionTextBold->setPriority(QAction::LowPriority); QFont bold; bold.setBold(true); actionTextBold->setFont(bold); connect(actionTextBold, SIGNAL(triggered()), this, SLOT(boldText())); addAction(actionTextBold); actionTextBold->setCheckable(true); actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(":italic")), tr("&Italic"), this); actionTextItalic->setPriority(QAction::LowPriority); actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); QFont italic; italic.setItalic(true); actionTextItalic->setFont(italic); connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(italicText())); addAction(actionTextItalic); actionTextItalic->setCheckable(true); actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(":underlined")), tr("&Underline"), this); actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); actionTextUnderline->setPriority(QAction::LowPriority); QFont underline; underline.setUnderline(true); actionTextUnderline->setFont(underline); connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(underlinedText())); addAction(actionTextUnderline); actionTextUnderline->setCheckable(true); actionTextStrikeOut = new QAction(QIcon::fromTheme("format-text-strikethrough", QIcon(":strikedout")), tr("&Strike Out"), this); actionTextStrikeOut->setShortcut(Qt::CTRL + Qt::Key_S); actionTextStrikeOut->setPriority(QAction::LowPriority); QFont strikeOut; strikeOut.setStrikeOut(true); actionTextStrikeOut->setFont(strikeOut); connect(actionTextStrikeOut, SIGNAL(triggered()), this, SLOT(strikedOutText())); addAction(actionTextStrikeOut); actionTextStrikeOut->setCheckable(true); actionInsertHyperlink = new QAction(QIcon::fromTheme("emblem-web",QIcon(":hyperlink")),tr("&Hyperlink"),this); actionInsertHyperlink->setShortcut(Qt::CTRL + Qt::Key_K); // word shortcut actionInsertHyperlink->setPriority(QAction::LowPriority); connect(actionInsertHyperlink,SIGNAL(triggered()),this,SLOT(insertHyperlink())); addAction(actionInsertHyperlink); QPixmap textPix(16, 16); textPix.fill(Qt::black); actionTextColor = new QAction(textPix, tr("&Text color..."), this); connect(actionTextColor, SIGNAL(triggered()), this, SLOT(coloredText())); addAction(actionTextColor); QPixmap bPix(16, 16); bPix.fill(Qt::white); actionTextBColor = new QAction(bPix, tr("&Background color..."), this); connect(actionTextBColor, SIGNAL(triggered()), this, SLOT(markedText())); addAction(actionTextBColor); fontComboBox = new QFontComboBox(this); fontComboBox->setFocusPolicy(Qt::TabFocus); addWidget(fontComboBox); connect(fontComboBox, SIGNAL(activated(QString)), this, SLOT(fontOfText(QString))); comboSize = new QComboBox(this); comboSize->setObjectName("comboSize"); addWidget(comboSize); comboSize->setEditable(true); connect(comboSize, SIGNAL(activated(QString)), this, SLOT(pointSizeOfText(QString))); QFontDatabase db; foreach(int size, db.standardSizes()) comboSize->addItem(QString::number(size)); comboSize->setCurrentIndex(comboSize->findText(QString::number( QApplication::font().pointSize()))); connect(textEdit_, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(getFontAndPointSizeOfText(QTextCharFormat))); } void TextFormattingToolbar::mergeFormatOnWordOrSelection(const QTextCharFormat &format){ QTextCursor cursor = textEdit_->textCursor(); if(!cursor.hasSelection() && !cursor.atBlockStart() && !cursor.atBlockEnd()) cursor.select(QTextCursor::WordUnderCursor); cursor.mergeCharFormat(format); textEdit_->mergeCurrentCharFormat(format); } void TextFormattingToolbar::getFontAndPointSizeOfText(const QTextCharFormat &format){ QFont f = format.font(); fontComboBox->setCurrentIndex(fontComboBox->findText(QFontInfo(f).family())); comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); actionTextBold->setChecked(f.bold()); actionTextItalic->setChecked(f.italic()); actionTextUnderline->setChecked(f.underline()); actionTextStrikeOut->setChecked(f.strikeOut()); QPixmap textPix(16,16); textPix.fill(format.foreground().color()); actionTextColor->setIcon(textPix); QPixmap bPix(16,16); bPix.fill(format.background().color()); actionTextBColor->setIcon(bPix); } void TextFormattingToolbar::boldText(){ QTextCharFormat fmt; fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::italicText(){ QTextCharFormat fmt; fmt.setFontItalic(actionTextItalic->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::underlinedText(){ QTextCharFormat fmt; fmt.setFontUnderline(actionTextUnderline->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::strikedOutText(){ QTextCharFormat fmt; fmt.setFontStrikeOut(actionTextStrikeOut->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::coloredText(){ QColor col = QColorDialog::getColor(textEdit_->textColor(), this); if(!col.isValid()) return; QTextCharFormat fmt; fmt.setForeground(col); mergeFormatOnWordOrSelection(fmt); QPixmap pix(16, 16); pix.fill(col); actionTextColor->setIcon(pix); } void TextFormattingToolbar::markedText(){ QColor col = QColorDialog::getColor(textEdit_->textBackgroundColor(), this); if(!col.isValid()) return; QTextCharFormat fmt; fmt.setBackground(col); mergeFormatOnWordOrSelection(fmt); QPixmap pix(16, 16); pix.fill(col); actionTextColor->setIcon(pix); } void TextFormattingToolbar::insertHyperlink() { QTextCursor cursor = textEdit_->textCursor(); QString selectedText = cursor.selectedText(); bool ok; QString link = QInputDialog::getText(textEdit_,tr("Insert Hyperlink"),tr("Addr&ess:"),QLineEdit::Normal,selectedText,&ok); if(!ok) return; /*TODO: de-formatting if(link.isEmpty){ resetFonts()//or something like that return; }*/ /*TODO: check if link/e-mail is valid with the following regexps QRegExp(">\\b((((https?|ftp)://)|(www\\.))[a-zA-Z0-9_\\.\\-\\?]+)\\b(<?)" , Qt::CaseInsensitive) QRegExp(">\\b([a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9_\\.\\-]+)\\b(<?)", Qt::CaseInsensitive) */ if(selectedText.isEmpty()) selectedText = link; if(link.contains("@")) cursor.insertHtml("<a href=mailto:"+link+"\">"+selectedText+"</a>"); else cursor.insertHtml("<a href=\""+link+"\">"+selectedText+"</a>"); } void TextFormattingToolbar::fontOfText(const QString &f){ QTextCharFormat fmt; fmt.setFontFamily(f); mergeFormatOnWordOrSelection(fmt); } void TextFormattingToolbar::pointSizeOfText(const QString &p){ qreal pointSize = p.toFloat(); if(p.toFloat() > 0){ QTextCharFormat fmt; fmt.setFontPointSize(pointSize); mergeFormatOnWordOrSelection(fmt); } } <|endoftext|>
<commit_before>#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/Storage.c" #else #include "EasyCL.h" #include "util/StatefulTimer.h" #include <stdexcept> #include <string> using namespace std; #define EXCEPT_TO_THERROR(method) \ try { \ method; \ } catch(exception &e) { \ THError("Something went wrong: %s", e.what()); \ } static int torch_Storage_(new)(lua_State *L) { StatefulTimer::timeCheck("storage new START"); THClState *state = cltorch_getstate(L); THStorage *storage; if(lua_type(L, 1) == LUA_TSTRING) { const char *fileName = luaL_checkstring(L, 1); int isShared = luaT_optboolean(L, 2, 0); long size = luaL_optlong(L, 3, 0); storage = THStorage_(newWithMapping)(state, state->currentDevice, fileName, size, isShared); } else if(lua_type(L, 1) == LUA_TTABLE) { long size = lua_objlen(L, 1); long i; THFloatStorage *storage = THFloatStorage_newWithSize(size); for(i = 1; i <= size; i++) { lua_rawgeti(L, 1, i); if(!lua_isnumber(L, -1)) { THFloatStorage_free(storage); luaL_error(L, "element at index %d is not a number", i); } THFloatStorage_set(storage, i-1, (real)lua_tonumber(L, -1)); lua_pop(L, 1); } THStorage *storagecl = THStorage_(newWithSize)(state, state->currentDevice, size); THStorage_(copyFloat)(state, storagecl, storage); THFloatStorage_free(storage); luaT_pushudata(L, storagecl, "torch.ClStorage"); StatefulTimer::timeCheck("storage new END"); return 1; // THError("Please create like this: torch.Tensor(mytable):cl()"); // long size = lua_objlen(L, 1); // long i; // storage = THStorage_(newWithSize)(state, size); // for(i = 1; i <= size; i++) // { // lua_rawgeti(L, 1, i); // if(!lua_isnumber(L, -1)) // { // THStorage_(free)(state, storage); // luaL_error(L, "element at index %d is not a number", i); // } // THStorage_(set)(state, storage, i-1, (real)lua_tonumber(L, -1)); // lua_pop(L, 1); // } } else if(lua_type(L, 1) == LUA_TUSERDATA) { THStorage *src = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); real *ptr = src->data; long offset = luaL_optlong(L, 2, 1) - 1; if (offset < 0 || offset >= src->size) { luaL_error(L, "offset out of bounds"); } long size = luaL_optlong(L, 3, src->size - offset); if (size < 1 || size > (src->size - offset)) { luaL_error(L, "size out of bounds"); } storage = THStorage_(newWithData)(state, state->currentDevice, ptr + offset, size); storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_VIEW; storage->view = src; THStorage_(retain)(state, storage->view); } else if(lua_type(L, 2) == LUA_TNUMBER) { long size = luaL_optlong(L, 1, 0); real *ptr = (real *)luaL_optlong(L, 2, 0); EXCEPT_TO_THERROR(storage = THStorage_(newWithData)(state, state->currentDevice, ptr, size)); storage->flag = TH_STORAGE_REFCOUNTED; } else { long size = luaL_optlong(L, 1, 0); EXCEPT_TO_THERROR(storage = THStorage_(newWithSize)(state, state->currentDevice, size)); } luaT_pushudata(L, storage, torch_Storage); StatefulTimer::timeCheck("storage new END"); return 1; } static int torch_Storage_(retain)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); THStorage_(retain)(cltorch_getstate(L), storage); return 0; } static int torch_Storage_(free)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); EXCEPT_TO_THERROR(THStorage_(free)(cltorch_getstate(L), storage)); return 0; } static int torch_Storage_(resize)(lua_State *L) { THStorage *storage = static_cast< THStorage * >(luaT_checkudata(L, 1, torch_Storage)); long size = luaL_checklong(L, 2); /* int keepContent = luaT_optboolean(L, 3, 0); */ EXCEPT_TO_THERROR(THStorage_(resize)(cltorch_getstate(L), storage, size));/*, keepContent); */ lua_settop(L, 1); return 1; } static int torch_Storage_(copy)(lua_State *L) { THClState *state = cltorch_getstate(L); THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); void *src; if( (src = luaT_toudata(L, 2, torch_Storage)) ) THStorage_(copy)(state, storage, static_cast<THClStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.ByteStorage")) ) THStorage_(copyByte)(state, storage, static_cast<THByteStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.CharStorage")) ) THStorage_(copyChar)(state, storage, static_cast<THCharStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.ShortStorage")) ) THStorage_(copyShort)(state, storage, static_cast<THShortStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.IntStorage")) ) THStorage_(copyInt)(state, storage, static_cast<THIntStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.LongStorage")) ) THStorage_(copyLong)(state, storage, static_cast<THLongStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.FloatStorage")) ) THStorage_(copyFloat)(state, storage, static_cast<THFloatStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.DoubleStorage")) ) THStorage_(copyDouble)(state, storage, static_cast<THDoubleStorage *>(src)); else luaL_typerror(L, 2, "torch.*Storage"); lua_settop(L, 1); return 1; } static int torch_Storage_(fill)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); double value = luaL_checknumber(L, 2); EXCEPT_TO_THERROR(THStorage_(fill)(cltorch_getstate(L), storage, (real)value)); lua_settop(L, 1); return 1; } static int torch_Storage_(__len__)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); lua_pushnumber(L, storage->size); return 1; } static int torch_Storage_(__newindex__)(lua_State *L) { if(lua_isnumber(L, 2)) { THError("Please convert to FloatTensor, then update, then copy back"); lua_pushboolean(L, 0); // THStorage *storage = luaT_checkudata(L, 1, torch_Storage); // long index = luaL_checklong(L, 2) - 1; // double number = luaL_checknumber(L, 3); // THStorage_(set)(cltorch_getstate(L), storage, index, (real)number); // lua_pushboolean(L, 1); } else lua_pushboolean(L, 0); return 1; } static int torch_Storage_(__index__)(lua_State *L) { if(lua_isnumber(L, 2)) { THError("Please convert to FloatStorage, then read the value"); // THStorage *storage = luaT_checkudata(L, 1, torch_Storage); // long index = luaL_checklong(L, 2) - 1; // lua_pushnumber(L, THStorage_(get)(cltorch_getstate(L), storage, index)); // lua_pushboolean(L, 1); // return 2; lua_pushboolean(L, 0); return 1; } else { lua_pushboolean(L, 0); return 1; } } #if defined(TH_REAL_IS_CHAR) || defined(TH_REAL_IS_BYTE) static int torch_Storage_(string)(lua_State *L) { printf("torch_Storage_(string)\n"); THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); if(lua_isstring(L, -1)) { size_t len = 0; const char *str = lua_tolstring(L, -1, &len); EXCEPT_TO_THERROR(THStorage_(resize)(cltorch_getstate(L), storage, len)); memmove(storage->data, str, len); lua_settop(L, 1); } else lua_pushlstring(L, (char*)storage->data, storage->size); return 1; /* either storage or string */ } #endif static int torch_Storage_(totable)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); long i; lua_newtable(L); for(i = 0; i < storage->size; i++) { lua_pushnumber(L, (lua_Number)storage->data[i]); lua_rawseti(L, -2, i+1); } return 1; } static int torch_Storage_(factory)(lua_State *L) { THClState *state = cltorch_getstate(L); THStorage *storage = 0; EXCEPT_TO_THERROR(storage = static_cast<THStorage *>(THStorage_(newv2)(cltorch_getstate(L), state->currentDevice))); luaT_pushudata(L, storage, torch_Storage); return 1; } static int torch_Storage_(write)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); THFile *file = static_cast<THFile *>(luaT_checkudata(L, 2, "torch.File")); // THClState *state = cltorch_getstate(L); THFile_writeLongScalar(file, storage->size); storage->wrapper->copyToHost(); storage->cl->finish(); EXCEPT_TO_THERROR(THFile_writeFloatRaw(file, storage->data, storage->size)); return 0; } static int torch_Storage_(read)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); THFile *file = static_cast<THFile *>(luaT_checkudata(L, 2, "torch.File")); long size = THFile_readLongScalar(file); // THClState *state = cltorch_getstate(L); EXCEPT_TO_THERROR(THStorage_(resize)(cltorch_getstate(L), storage, size)); EXCEPT_TO_THERROR(THFile_readFloatRaw(file, storage->data, storage->size)); storage->wrapper->copyToDevice(); storage->cl->finish(); return 0; } static const struct luaL_Reg torch_Storage_(_) [] = { {"retain", torch_Storage_(retain)}, {"free", torch_Storage_(free)}, {"size", torch_Storage_(__len__)}, {"__len__", torch_Storage_(__len__)}, {"__newindex__", torch_Storage_(__newindex__)}, {"__index__", torch_Storage_(__index__)}, {"resize", torch_Storage_(resize)}, {"fill", torch_Storage_(fill)}, {"copy", torch_Storage_(copy)}, {"totable", torch_Storage_(totable)}, {"write", torch_Storage_(write)}, {"read", torch_Storage_(read)}, #if defined(TH_REAL_IS_CHAR) || defined(TH_REAL_IS_BYTE) {"string", torch_Storage_(string)}, #endif {NULL, NULL} }; void torch_Storage_(init)(lua_State *L) { luaT_newmetatable(L, torch_Storage, NULL, torch_Storage_(new), torch_Storage_(free), torch_Storage_(factory)); luaL_setfuncs(L, torch_Storage_(_), 0); lua_pop(L, 1); } #endif <commit_msg>wrap a couple more storage methods with catch exception => convert to THError<commit_after>#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/Storage.c" #else #include "EasyCL.h" #include "util/StatefulTimer.h" #include <stdexcept> #include <string> using namespace std; #define EXCEPT_TO_THERROR(method) \ try { \ method; \ } catch(exception &e) { \ THError("Something went wrong: %s", e.what()); \ } static int torch_Storage_(new)(lua_State *L) { StatefulTimer::timeCheck("storage new START"); THClState *state = cltorch_getstate(L); THStorage *storage; if(lua_type(L, 1) == LUA_TSTRING) { const char *fileName = luaL_checkstring(L, 1); int isShared = luaT_optboolean(L, 2, 0); long size = luaL_optlong(L, 3, 0); EXCEPT_TO_THERROR(storage = THStorage_(newWithMapping)(state, state->currentDevice, fileName, size, isShared)); } else if(lua_type(L, 1) == LUA_TTABLE) { long size = lua_objlen(L, 1); long i; THFloatStorage *storage = 0; EXCEPT_TO_THERROR(storage = THFloatStorage_newWithSize(size)); for(i = 1; i <= size; i++) { lua_rawgeti(L, 1, i); if(!lua_isnumber(L, -1)) { THFloatStorage_free(storage); luaL_error(L, "element at index %d is not a number", i); } THFloatStorage_set(storage, i-1, (real)lua_tonumber(L, -1)); lua_pop(L, 1); } THStorage *storagecl = 0; EXCEPT_TO_THERROR(storagecl = THStorage_(newWithSize)(state, state->currentDevice, size)); EXCEPT_TO_THERROR(THStorage_(copyFloat)(state, storagecl, storage)); EXCEPT_TO_THERROR(THFloatStorage_free(storage)); luaT_pushudata(L, storagecl, "torch.ClStorage"); StatefulTimer::timeCheck("storage new END"); return 1; // THError("Please create like this: torch.Tensor(mytable):cl()"); // long size = lua_objlen(L, 1); // long i; // storage = THStorage_(newWithSize)(state, size); // for(i = 1; i <= size; i++) // { // lua_rawgeti(L, 1, i); // if(!lua_isnumber(L, -1)) // { // THStorage_(free)(state, storage); // luaL_error(L, "element at index %d is not a number", i); // } // THStorage_(set)(state, storage, i-1, (real)lua_tonumber(L, -1)); // lua_pop(L, 1); // } } else if(lua_type(L, 1) == LUA_TUSERDATA) { THStorage *src = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); real *ptr = src->data; long offset = luaL_optlong(L, 2, 1) - 1; if (offset < 0 || offset >= src->size) { luaL_error(L, "offset out of bounds"); } long size = luaL_optlong(L, 3, src->size - offset); if (size < 1 || size > (src->size - offset)) { luaL_error(L, "size out of bounds"); } EXCEPT_TO_THERROR(storage = THStorage_(newWithData)(state, state->currentDevice, ptr + offset, size)); storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_VIEW; storage->view = src; THStorage_(retain)(state, storage->view); } else if(lua_type(L, 2) == LUA_TNUMBER) { long size = luaL_optlong(L, 1, 0); real *ptr = (real *)luaL_optlong(L, 2, 0); EXCEPT_TO_THERROR(storage = THStorage_(newWithData)(state, state->currentDevice, ptr, size)); storage->flag = TH_STORAGE_REFCOUNTED; } else { long size = luaL_optlong(L, 1, 0); EXCEPT_TO_THERROR(storage = THStorage_(newWithSize)(state, state->currentDevice, size)); } luaT_pushudata(L, storage, torch_Storage); StatefulTimer::timeCheck("storage new END"); return 1; } static int torch_Storage_(retain)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); THStorage_(retain)(cltorch_getstate(L), storage); return 0; } static int torch_Storage_(free)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); EXCEPT_TO_THERROR(THStorage_(free)(cltorch_getstate(L), storage)); return 0; } static int torch_Storage_(resize)(lua_State *L) { THStorage *storage = static_cast< THStorage * >(luaT_checkudata(L, 1, torch_Storage)); long size = luaL_checklong(L, 2); /* int keepContent = luaT_optboolean(L, 3, 0); */ EXCEPT_TO_THERROR(THStorage_(resize)(cltorch_getstate(L), storage, size));/*, keepContent); */ lua_settop(L, 1); return 1; } static int torch_Storage_(copy)(lua_State *L) { THClState *state = cltorch_getstate(L); THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); void *src; if( (src = luaT_toudata(L, 2, torch_Storage)) ) THStorage_(copy)(state, storage, static_cast<THClStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.ByteStorage")) ) THStorage_(copyByte)(state, storage, static_cast<THByteStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.CharStorage")) ) THStorage_(copyChar)(state, storage, static_cast<THCharStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.ShortStorage")) ) THStorage_(copyShort)(state, storage, static_cast<THShortStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.IntStorage")) ) THStorage_(copyInt)(state, storage, static_cast<THIntStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.LongStorage")) ) THStorage_(copyLong)(state, storage, static_cast<THLongStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.FloatStorage")) ) THStorage_(copyFloat)(state, storage, static_cast<THFloatStorage *>(src)); else if( (src = luaT_toudata(L, 2, "torch.DoubleStorage")) ) THStorage_(copyDouble)(state, storage, static_cast<THDoubleStorage *>(src)); else luaL_typerror(L, 2, "torch.*Storage"); lua_settop(L, 1); return 1; } static int torch_Storage_(fill)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); double value = luaL_checknumber(L, 2); EXCEPT_TO_THERROR(THStorage_(fill)(cltorch_getstate(L), storage, (real)value)); lua_settop(L, 1); return 1; } static int torch_Storage_(__len__)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); lua_pushnumber(L, storage->size); return 1; } static int torch_Storage_(__newindex__)(lua_State *L) { if(lua_isnumber(L, 2)) { THError("Please convert to FloatTensor, then update, then copy back"); lua_pushboolean(L, 0); // THStorage *storage = luaT_checkudata(L, 1, torch_Storage); // long index = luaL_checklong(L, 2) - 1; // double number = luaL_checknumber(L, 3); // THStorage_(set)(cltorch_getstate(L), storage, index, (real)number); // lua_pushboolean(L, 1); } else lua_pushboolean(L, 0); return 1; } static int torch_Storage_(__index__)(lua_State *L) { if(lua_isnumber(L, 2)) { THError("Please convert to FloatStorage, then read the value"); // THStorage *storage = luaT_checkudata(L, 1, torch_Storage); // long index = luaL_checklong(L, 2) - 1; // lua_pushnumber(L, THStorage_(get)(cltorch_getstate(L), storage, index)); // lua_pushboolean(L, 1); // return 2; lua_pushboolean(L, 0); return 1; } else { lua_pushboolean(L, 0); return 1; } } #if defined(TH_REAL_IS_CHAR) || defined(TH_REAL_IS_BYTE) static int torch_Storage_(string)(lua_State *L) { printf("torch_Storage_(string)\n"); THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); if(lua_isstring(L, -1)) { size_t len = 0; const char *str = lua_tolstring(L, -1, &len); EXCEPT_TO_THERROR(THStorage_(resize)(cltorch_getstate(L), storage, len)); memmove(storage->data, str, len); lua_settop(L, 1); } else lua_pushlstring(L, (char*)storage->data, storage->size); return 1; /* either storage or string */ } #endif static int torch_Storage_(totable)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); long i; lua_newtable(L); for(i = 0; i < storage->size; i++) { lua_pushnumber(L, (lua_Number)storage->data[i]); lua_rawseti(L, -2, i+1); } return 1; } static int torch_Storage_(factory)(lua_State *L) { THClState *state = cltorch_getstate(L); THStorage *storage = 0; EXCEPT_TO_THERROR(storage = static_cast<THStorage *>(THStorage_(newv2)(cltorch_getstate(L), state->currentDevice))); luaT_pushudata(L, storage, torch_Storage); return 1; } static int torch_Storage_(write)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); THFile *file = static_cast<THFile *>(luaT_checkudata(L, 2, "torch.File")); // THClState *state = cltorch_getstate(L); THFile_writeLongScalar(file, storage->size); storage->wrapper->copyToHost(); storage->cl->finish(); EXCEPT_TO_THERROR(THFile_writeFloatRaw(file, storage->data, storage->size)); return 0; } static int torch_Storage_(read)(lua_State *L) { THStorage *storage = static_cast<THStorage *>(luaT_checkudata(L, 1, torch_Storage)); THFile *file = static_cast<THFile *>(luaT_checkudata(L, 2, "torch.File")); long size = THFile_readLongScalar(file); // THClState *state = cltorch_getstate(L); EXCEPT_TO_THERROR(THStorage_(resize)(cltorch_getstate(L), storage, size)); EXCEPT_TO_THERROR(THFile_readFloatRaw(file, storage->data, storage->size)); storage->wrapper->copyToDevice(); storage->cl->finish(); return 0; } static const struct luaL_Reg torch_Storage_(_) [] = { {"retain", torch_Storage_(retain)}, {"free", torch_Storage_(free)}, {"size", torch_Storage_(__len__)}, {"__len__", torch_Storage_(__len__)}, {"__newindex__", torch_Storage_(__newindex__)}, {"__index__", torch_Storage_(__index__)}, {"resize", torch_Storage_(resize)}, {"fill", torch_Storage_(fill)}, {"copy", torch_Storage_(copy)}, {"totable", torch_Storage_(totable)}, {"write", torch_Storage_(write)}, {"read", torch_Storage_(read)}, #if defined(TH_REAL_IS_CHAR) || defined(TH_REAL_IS_BYTE) {"string", torch_Storage_(string)}, #endif {NULL, NULL} }; void torch_Storage_(init)(lua_State *L) { luaT_newmetatable(L, torch_Storage, NULL, torch_Storage_(new), torch_Storage_(free), torch_Storage_(factory)); luaL_setfuncs(L, torch_Storage_(_), 0); lua_pop(L, 1); } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: BYUWrite.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "BYUWrite.hh" // Description: // Create object so that it writes displacement, scalar, and texture files // (if data is available). vlBYUWriter::vlBYUWriter() { this->GeometryFilename = NULL; this->DisplacementFilename = NULL; this->ScalarFilename = NULL; this->TextureFilename = NULL; this->WriteDisplacement = 1; this->WriteScalar = 1; this->WriteTexture = 1; } vlBYUWriter::~vlBYUWriter() { if ( this->GeometryFilename ) delete [] this->GeometryFilename; if ( this->DisplacementFilename ) delete [] this->DisplacementFilename; if ( this->ScalarFilename ) delete [] this->ScalarFilename; if ( this->TextureFilename ) delete [] this->TextureFilename; } // Description: // Write out data in MOVIE.BYU format. void vlBYUWriter::Write() { FILE *geomFp; int numPts=this->Input->GetNumberOfPoints(); this->Input->Update(); if ( numPts < 1 ) { vlErrorMacro(<<"No data to write!"); return; } if ((geomFp = fopen(this->GeometryFilename, "w")) == NULL) { vlErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFilename); return; } else { this->WriteGeometryFile(geomFp,numPts); } this->WriteDisplacementFile(numPts); this->WriteScalarFile(numPts); this->WriteTextureFile(numPts); } void vlBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts) { int numPolys, numEdges; int i; float *x; int npts, *pts; vlPoints *inPts; vlCellArray *inPolys; // // Write header (not using fixed format! - potential problem in some files.) // numPolys = this->Input->GetPolys()->GetNumberOfCells(); for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { numEdges += npts; } fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges); fprintf (geomFile, "%d %d", 1, numPolys); // // Write data // // write point coordinates for (i=0; i < numPts; i++) { x = inPts->GetPoint(i); fprintf(geomFile, "%e %e %e", x[0], x[1], x[2]); if ( (i % 2) ) fprintf(geomFile, "\n"); } if ( (numPts % 2) ) fprintf(geomFile, "\n"); // write poly data. Remember 1-offset. for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { // write this polygon for (i=0; i < (npts-1); i++) fprintf (geomFile, "%d ", pts[i]+1); fprintf (geomFile, "%d\n", -(pts[npts-1]+1)); } vlDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons"); } void vlBYUWriter::WriteDisplacementFile(int numPts) { FILE *dispFp; int i; float *v; vlVectors *inVectors; if ( this->WriteDisplacement && this->DisplacementFilename && (inVectors = this->Input->GetPointData()->GetVectors()) != NULL ) { if ( !(dispFp = fopen(this->DisplacementFilename, "r")) ) { vlErrorMacro (<<"Couldn't open displacement file"); return; } } else return; // // Write data // for (i=0; i < numPts; i++) { v = inVectors->GetVector(i); fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]); if ( (i % 2) ) fprintf (dispFp, "\n"); } vlDebugMacro(<<"Wrote " << numPts << " displacements"); } void vlBYUWriter::WriteScalarFile(int numPts) { FILE *scalarFp; int i; float s; vlScalars *inScalars; if ( this->WriteScalar && this->ScalarFilename && (inScalars = this->Input->GetPointData()->GetScalars()) != NULL ) { if ( !(scalarFp = fopen(this->ScalarFilename, "r")) ) { vlErrorMacro (<<"Couldn't open scalar file"); return; } } else return; // // Write data // for (i=0; i < numPts; i++) { s = inScalars->GetScalar(i); fprintf(scalarFp, "%e", s); if ( i != 0 && !(i % 6) ) fprintf (scalarFp, "\n"); } vlDebugMacro(<<"Wrote " << numPts << " scalars"); } void vlBYUWriter::WriteTextureFile(int numPts) { FILE *textureFp; int i; float *t; vlTCoords *inTCoords; if ( this->WriteTexture && this->TextureFilename && (inTCoords = this->Input->GetPointData()->GetTCoords()) != NULL ) { if ( !(textureFp = fopen(this->TextureFilename, "r")) ) { vlErrorMacro (<<"Couldn't open texture file"); return; } } else return; // // Write data // for (i=0; i < numPts; i++) { if ( i != 0 && !(i % 3) ) fprintf (textureFp, "\n"); t = inTCoords->GetTCoord(i); fprintf(textureFp, "%e %e", t[0], t[1]); } vlDebugMacro(<<"Wrote " << numPts << " texture coordinates"); } void vlBYUWriter::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlBYUWriter::GetClassName())) { this->PrintWatchOn(); // watch for multiple inheritance vlPolyFilter::PrintSelf(os,indent); vlWriter::PrintSelf(os,indent); os << indent << "Geometry Filename: " << this->GeometryFilename << "\n"; os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n"); os << indent << "Displacement Filename: " << this->DisplacementFilename << "\n"; os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n"); os << indent << "Scalar Filename: " << this->ScalarFilename << "\n"; os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n"); os << indent << "Texture Filename: " << this->TextureFilename << "\n"; this->PrintWatchOff(); // stop worrying about it now } } <commit_msg>ERR: Chack input properly.<commit_after>/*========================================================================= Program: Visualization Library Module: BYUWrite.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "BYUWrite.hh" // Description: // Create object so that it writes displacement, scalar, and texture files // (if data is available). vlBYUWriter::vlBYUWriter() { this->GeometryFilename = NULL; this->DisplacementFilename = NULL; this->ScalarFilename = NULL; this->TextureFilename = NULL; this->WriteDisplacement = 1; this->WriteScalar = 1; this->WriteTexture = 1; } vlBYUWriter::~vlBYUWriter() { if ( this->GeometryFilename ) delete [] this->GeometryFilename; if ( this->DisplacementFilename ) delete [] this->DisplacementFilename; if ( this->ScalarFilename ) delete [] this->ScalarFilename; if ( this->TextureFilename ) delete [] this->TextureFilename; } // Description: // Write out data in MOVIE.BYU format. void vlBYUWriter::Write() { FILE *geomFp; int numPts=this->Input->GetNumberOfPoints(); this->Input->Update(); if ( numPts < 1 ) { vlErrorMacro(<<"No data to write!"); return; } if ((geomFp = fopen(this->GeometryFilename, "w")) == NULL) { vlErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFilename); return; } else { this->WriteGeometryFile(geomFp,numPts); } this->WriteDisplacementFile(numPts); this->WriteScalarFile(numPts); this->WriteTextureFile(numPts); } void vlBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts) { int numPolys, numEdges; int i; float *x; int npts, *pts; vlPoints *inPts; vlCellArray *inPolys; // // Check input // if ( (inPts=this->Input->GetPoints()) == NULL || (inPolys=this->Input->GetPolys()) == NULL ) { vlErrorMacro(<<"No data to write!"); return; } // // Write header (not using fixed format! - potential problem in some files.) // numPolys = this->Input->GetPolys()->GetNumberOfCells(); for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { numEdges += npts; } fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges); fprintf (geomFile, "%d %d", 1, numPolys); // // Write data // // write point coordinates for (i=0; i < numPts; i++) { x = inPts->GetPoint(i); fprintf(geomFile, "%e %e %e", x[0], x[1], x[2]); if ( (i % 2) ) fprintf(geomFile, "\n"); } if ( (numPts % 2) ) fprintf(geomFile, "\n"); // write poly data. Remember 1-offset. for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { // write this polygon for (i=0; i < (npts-1); i++) fprintf (geomFile, "%d ", pts[i]+1); fprintf (geomFile, "%d\n", -(pts[npts-1]+1)); } vlDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons"); } void vlBYUWriter::WriteDisplacementFile(int numPts) { FILE *dispFp; int i; float *v; vlVectors *inVectors; if ( this->WriteDisplacement && this->DisplacementFilename && (inVectors = this->Input->GetPointData()->GetVectors()) != NULL ) { if ( !(dispFp = fopen(this->DisplacementFilename, "r")) ) { vlErrorMacro (<<"Couldn't open displacement file"); return; } } else return; // // Write data // for (i=0; i < numPts; i++) { v = inVectors->GetVector(i); fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]); if ( (i % 2) ) fprintf (dispFp, "\n"); } vlDebugMacro(<<"Wrote " << numPts << " displacements"); } void vlBYUWriter::WriteScalarFile(int numPts) { FILE *scalarFp; int i; float s; vlScalars *inScalars; if ( this->WriteScalar && this->ScalarFilename && (inScalars = this->Input->GetPointData()->GetScalars()) != NULL ) { if ( !(scalarFp = fopen(this->ScalarFilename, "r")) ) { vlErrorMacro (<<"Couldn't open scalar file"); return; } } else return; // // Write data // for (i=0; i < numPts; i++) { s = inScalars->GetScalar(i); fprintf(scalarFp, "%e", s); if ( i != 0 && !(i % 6) ) fprintf (scalarFp, "\n"); } vlDebugMacro(<<"Wrote " << numPts << " scalars"); } void vlBYUWriter::WriteTextureFile(int numPts) { FILE *textureFp; int i; float *t; vlTCoords *inTCoords; if ( this->WriteTexture && this->TextureFilename && (inTCoords = this->Input->GetPointData()->GetTCoords()) != NULL ) { if ( !(textureFp = fopen(this->TextureFilename, "r")) ) { vlErrorMacro (<<"Couldn't open texture file"); return; } } else return; // // Write data // for (i=0; i < numPts; i++) { if ( i != 0 && !(i % 3) ) fprintf (textureFp, "\n"); t = inTCoords->GetTCoord(i); fprintf(textureFp, "%e %e", t[0], t[1]); } vlDebugMacro(<<"Wrote " << numPts << " texture coordinates"); } void vlBYUWriter::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlBYUWriter::GetClassName())) { this->PrintWatchOn(); // watch for multiple inheritance vlPolyFilter::PrintSelf(os,indent); vlWriter::PrintSelf(os,indent); os << indent << "Geometry Filename: " << this->GeometryFilename << "\n"; os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n"); os << indent << "Displacement Filename: " << this->DisplacementFilename << "\n"; os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n"); os << indent << "Scalar Filename: " << this->ScalarFilename << "\n"; os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n"); os << indent << "Texture Filename: " << this->TextureFilename << "\n"; this->PrintWatchOff(); // stop worrying about it now } } <|endoftext|>
<commit_before>// definition of necessary units static const double cm=1; static const double cm3=cm*cm*cm; static const double volt=1; static const double C=1; // Coulomb static const double Qe=-1.6e-19*C; // eletron charge static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity // https://link.springer.com/chapter/10.1007/10832182_519 static const double epsilonGe=15.8; // Ge dielectric constant //______________________________________________________________________________ // V"(x)=a, https://www.wolframalpha.com/input/?i=V%27%27(x)%3Da double V(double *coordinates, double *parameters) { double x = coordinates[0]; // there is no y and z dependence double x0= 0*cm; // lower electrode double x1= parameters[0]; // upper electrode double v0= 0*volt; // lower voltage double v1= parameters[1]; // upper voltage double rho=parameters[2]*Qe;// space charge density [C/cm3] double a =-rho/epsilon0/epsilonGe; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); double c1= (v0*x1-v1*x0)/(x1-x0) + a/2*x0*x1; return a*x*x/2 + c2*x + c1; } //______________________________________________________________________________ // search for depletion voltage of a planar detector given impurity & thickness double GetVdep(double impurity, double thickness) { if (impurity==0) return 0; // nothing to deplete TF1 *det=new TF1("det", V, 0, thickness, 3); // potential distr. double bias, vlower=0*volt, vupper=2e4*volt; // range of search while (vupper-vlower>1e-3*volt) { // binary search bias=(vupper+vlower)/2; // bias voltage det->SetParameters(thickness, bias, impurity); if (det->Derivative(0)*det->Derivative(thickness)<0) vlower=bias; else vupper=bias; } return bias; } //______________________________________________________________________________ // draw results void getVd(double thickness=1*cm) { const int n=10; // number of points double impurity[n]={-1e9/cm3, -2e9/cm3, -4e9/cm3, -8e9/cm3, -1e10/cm3, -2e10/cm3, -4e10/cm3, -8e10/cm3, -1e11/cm3, -1.2e11/cm3}; // n-type double absi[n], vdep[n]; for (int i=0; i<n; i++) { vdep[i] = GetVdep(impurity[i], thickness); absi[i] = abs(impurity[i]); } gROOT->SetStyle("GeFiCa"); gStyle->SetTitleOffset(1.1,"XY"); gStyle->SetPadRightMargin(0.01); gStyle->SetPadLeftMargin(0.11); gStyle->SetPadTopMargin(0.01); gStyle->SetPadBottomMargin(0.12); // Vdep VS impurity TGraph *g = new TGraph(n,absi,vdep); g->SetTitle(";Net Impurity [cm^{-3}];Depletion Voltage [V]"); g->Draw("apc"); TText *t1 = new TText(2e9, 6000, Form( "%.0f cm thick planar detector", thickness/cm)); t1->Draw(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy(); gPad->Print("depleted.png"); // voltage VS thickness TCanvas *c = new TCanvas; double bias = 1000*volt; // over depleted TF1 *fvo=new TF1("fvo", V, 0, thickness, 3); fvo->SetParameters(thickness, vdep[6]+bias, impurity[6]); fvo->SetTitle(";Thickness [cm]; Voltage [V]"); fvo->SetLineColor(kMagenta); fvo->SetLineStyle(2); fvo->GetXaxis()->SetTitleOffset(1.1); fvo->Draw(); // depleted TF1 *fvd=new TF1("fvd", V, 0, thickness, 3); fvd->SetParameters(thickness, vdep[6], impurity[6]); fvd->Draw("same"); // undepleted TF1 *fvu=new TF1("fvu", V, 0, thickness, 3); fvu->SetParameters(thickness, bias, impurity[6]); fvu->SetLineColor(kRed); fvu->SetLineStyle(3); fvu->Draw("same"); // potential due to bias alone TF1 *fvb=new TF1("fvb", V, 0, thickness, 3); fvb->SetParameters(thickness, bias, 0/cm3); fvb->SetLineColor(kBlue); fvb->SetLineStyle(4); fvb->Draw("same"); // potential due to space charges alone TF1 *fvc=new TF1("fvc", V, 0, thickness, 3); fvc->SetParameters(thickness, 0*volt, impurity[6]); fvc->SetLineColor(kGreen); fvc->SetLineStyle(5); fvc->Draw("same"); // draw lines and texts TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->Draw(); TText *t5 = new TText(0.5, 2800, "over depleted"); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.8, 2310, "just depleted"); t6->Draw(); TText *t7 = new TText(0.65, 1250, "undepleted"); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.65, 800, "bias alone"); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.55, 200, "space charges alone"); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.1, 2700, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->Draw(); c->Print("undepleted.png"); } <commit_msg>changed polarity<commit_after>// definition of necessary units static const double cm=1; static const double cm3=cm*cm*cm; static const double volt=1; static const double C=1; // Coulomb static const double Qe=-1.6e-19*C; // eletron charge static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity // https://link.springer.com/chapter/10.1007/10832182_519 static const double epsilonGe=15.8; // Ge dielectric constant //______________________________________________________________________________ // V"(x)=a, https://www.wolframalpha.com/input/?i=V%27%27(x)%3Da double V(double *coordinates, double *parameters) { double x = coordinates[0]; // there is no y and z dependence double x0= 0*cm; // lower electrode double x1= parameters[0]; // upper electrode double v0= 0*volt; // lower voltage double v1= parameters[1]; // upper voltage double rho=parameters[2]*Qe;// space charge density [C/cm3] double a =-rho/epsilon0/epsilonGe; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); double c1= (v0*x1-v1*x0)/(x1-x0) + a/2*x0*x1; return a*x*x/2 + c2*x + c1; } //______________________________________________________________________________ // search for depletion voltage of a planar detector given impurity & thickness double GetVdep(double impurity, double thickness, double vupper) { if (impurity==0) return 0; // nothing to deplete TF1 *det=new TF1("det", V, 0, thickness, 3); // potential distr. double bias, vlower=0*volt; // range of search while (abs(vupper-vlower)>1e-3*volt) { // binary search bias=(vupper+vlower)/2; // bias voltage det->SetParameters(thickness, bias, impurity); if (det->Derivative(0)*det->Derivative(thickness)<0) vlower=bias; else vupper=bias; } return bias; } //______________________________________________________________________________ // draw results void getVd(int type=1, double thickness=1*cm) { const int n=10; // number of points double impurity[n]={1e9/cm3, 2e9/cm3, 4e9/cm3, 8e9/cm3, 1e10/cm3, 2e10/cm3, 4e10/cm3, 8e10/cm3, 1e11/cm3, 1.2e11/cm3}; // p-type if (type==-1) for (int i=0; i<n; i++) impurity[i]*=type; // n-type double absi[n], vdep[n]; for (int i=0; i<n; i++) { vdep[i] = GetVdep(impurity[i], thickness, type*-2e4*volt); absi[i] = abs(impurity[i]); } gROOT->SetStyle("Plain"); // pick up a good default drawing style // modify the default style gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XY"); gStyle->SetTitleFont(132,"XY"); gStyle->SetLabelSize(0.05,"XY"); gStyle->SetTitleSize(0.05,"XY"); gStyle->SetTitleOffset(1.1,"XY"); gStyle->SetPadRightMargin(0.01); gStyle->SetPadLeftMargin(0.11); gStyle->SetPadTopMargin(0.01); gStyle->SetPadBottomMargin(0.12); // Vdep VS impurity TGraph *g = new TGraph(n,absi,vdep); g->SetTitle(";Net Impurity [cm^{-3}];Depletion Voltage [V]"); g->Draw("apc"); TText *t1 = new TText(2e9, 6000, Form( "%.0f cm thick planar detector", thickness/cm)); t1->Draw(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy(); gPad->Print("depleted.png"); // voltage VS thickness TCanvas *c = new TCanvas; double bias = -1000*volt; // p-type if(type==-1) bias = 1000*volt; // n-type // over depleted TF1 *fvo=new TF1("fvo", V, 0, thickness, 3); fvo->SetParameters(thickness, vdep[6]+bias, impurity[6]); fvo->SetTitle(";Thickness [cm]; Voltage [V]"); fvo->SetLineColor(kMagenta); fvo->SetLineStyle(2); fvo->GetXaxis()->SetTitleOffset(1.1); fvo->Draw(); // depleted TF1 *fvd=new TF1("fvd", V, 0, thickness, 3); fvd->SetParameters(thickness, vdep[6], impurity[6]); fvd->Draw("same"); // undepleted TF1 *fvu=new TF1("fvu", V, 0, thickness, 3); fvu->SetParameters(thickness, bias, impurity[6]); fvu->SetLineColor(kRed); fvu->SetLineStyle(3); fvu->Draw("same"); // potential due to bias alone TF1 *fvb=new TF1("fvb", V, 0, thickness, 3); fvb->SetParameters(thickness, bias, 0/cm3); fvb->SetLineColor(kBlue); fvb->SetLineStyle(4); fvb->Draw("same"); // potential due to space charges alone TF1 *fvc=new TF1("fvc", V, 0, thickness, 3); fvc->SetParameters(thickness, 0*volt, impurity[6]); fvc->SetLineColor(kGreen); fvc->SetLineStyle(5); fvc->Draw("same"); if (type==-1) { // draw lines and texts for n-type TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->SetTextFont(132); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->SetTextFont(132); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->Draw(); TText *t5 = new TText(0.5, 2800, "over depleted"); t5->SetTextFont(132); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.8, 2310, "just depleted"); t6->SetTextFont(132); t6->Draw(); TText *t7 = new TText(0.65, 1250, "undepleted"); t7->SetTextFont(132); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.65, 800, "bias alone"); t8->SetTextFont(132); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.55, 200, "space charges alone"); t9->SetTextFont(132); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.1, 2700, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->SetTextFont(132); t10->Draw(); c->Print("undepleted.png"); } else { // draw lines and texts for p-type TLine *l0 = new TLine(0,0,thickness/cm,0); l0->SetLineStyle(kDashed); l0->Draw(); TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->SetTextFont(132); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->SetTextFont(132); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->SetTextFont(132); t4->Draw(); TText *t5 = new TText(0.5, -3100, "over depleted"); t5->SetTextFont(132); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.76, -2500, "just depleted"); t6->SetTextFont(132); t6->Draw(); TText *t7 = new TText(0.65, -1400, "undepleted"); t7->SetTextFont(132); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.6, -900, "bias alone"); t8->SetTextFont(132); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.5, -200, "space charges alone"); t9->SetTextFont(132); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.1, -2700, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->SetTextFont(132); t10->Draw(); } } <|endoftext|>
<commit_before>#include "df_font.h" #include "df_window.h" #include <math.h> #include <stdlib.h> struct Point { float x, y, z; }; #define NUM_POINTS 1000000 Point g_points[NUM_POINTS]; Point g_cameraPos = { 0.0f, 0.0f, -100.0f }; float g_rotationX = 0.0f; static void CreateSierpinski3D() { float size = 20.0f; Point corners[5] = { { 0, 0, size }, { size, size, -size }, { size, -size, -size }, { -size, size, -size }, { -size, -size, -size } }; Point p = corners[0]; for (unsigned i = 0; i < NUM_POINTS; i++) { Point p2 = corners[rand() % 5]; p.x = (p.x + p2.x) / 2; p.y = (p.y + p2.y) / 2; p.z = (p.z + p2.z) / 2; g_points[i] = p; } } static void Render() { float scale = 1.0f * g_window->bmp->width; float halfWidth = g_window->bmp->width / 2; float halfHeight = g_window->bmp->height / 2; float cosRotX = cos(g_rotationX); float sinRotX = sin(g_rotationX); for (int i = 0; i < NUM_POINTS; i++) { Point p = g_points[i]; // Spin in model-view space float tmp = p.x; p.x = cosRotX * p.x + sinRotX * p.y; p.y = -sinRotX * tmp + cosRotX * p.y; // Move into view space p.y -= g_cameraPos.z; tmp = scale / p.y; unsigned x = p.x * tmp + halfWidth; unsigned y = -p.z * tmp + halfHeight; if (x < g_window->bmp->width && y < g_window->bmp->height) { unsigned brightness = 15; unsigned char invA = 255 - brightness; DfColour *pixel = g_window->bmp->lines[y] + x; pixel->r = (pixel->r * invA + 255 * brightness) >> 8; pixel->g = pixel->r; pixel->b = pixel->r; } } } void Sierpinski3DMain() { CreateWin(800, 600, WT_WINDOWED, "Sierpinski Gasket Example"); DfFont *font = DfCreateFont("Courier New", 12, 4); CreateSierpinski3D(); while (!g_window->windowClosed && !g_input.keys[KEY_ESC]) { ClearBitmap(g_window->bmp, g_colourBlack); InputManagerAdvance(); if (g_input.keys[KEY_UP]) g_cameraPos.z += 20.0f * g_window->advanceTime; if (g_input.keys[KEY_DOWN]) g_cameraPos.z -= 20.0f * g_window->advanceTime; if (g_input.keys[KEY_LEFT]) g_rotationX += 0.9f * g_window->advanceTime; if (g_input.keys[KEY_RIGHT]) g_rotationX -= 0.9f * g_window->advanceTime; Render(); // Draw frames per second counter DrawTextRight(font, g_colourWhite, g_window->bmp, g_window->bmp->width - 5, 0, "FPS:%i", g_window->fps); UpdateWin(); // DfSleepMillisec(10); } } <commit_msg>Made the Sierpinski Gasket example not miss keypresses when you are trying to quit.<commit_after>#include "df_font.h" #include "df_window.h" #include <math.h> #include <stdlib.h> struct Point { float x, y, z; }; #define NUM_POINTS 1000000 Point g_points[NUM_POINTS]; Point g_cameraPos = { 0.0f, 0.0f, -100.0f }; float g_rotationX = 0.0f; static void CreateSierpinski3D() { float size = 20.0f; Point corners[5] = { { 0, 0, size }, { size, size, -size }, { size, -size, -size }, { -size, size, -size }, { -size, -size, -size } }; Point p = corners[0]; for (unsigned i = 0; i < NUM_POINTS; i++) { Point p2 = corners[rand() % 5]; p.x = (p.x + p2.x) / 2; p.y = (p.y + p2.y) / 2; p.z = (p.z + p2.z) / 2; g_points[i] = p; } } static void Render() { float scale = 1.0f * g_window->bmp->width; float halfWidth = g_window->bmp->width / 2; float halfHeight = g_window->bmp->height / 2; float cosRotX = cos(g_rotationX); float sinRotX = sin(g_rotationX); for (int i = 0; i < NUM_POINTS; i++) { Point p = g_points[i]; // Spin in model-view space float tmp = p.x; p.x = cosRotX * p.x + sinRotX * p.y; p.y = -sinRotX * tmp + cosRotX * p.y; // Move into view space p.y -= g_cameraPos.z; tmp = scale / p.y; unsigned x = p.x * tmp + halfWidth; unsigned y = -p.z * tmp + halfHeight; if (x < g_window->bmp->width && y < g_window->bmp->height) { unsigned brightness = 15; unsigned char invA = 255 - brightness; DfColour *pixel = g_window->bmp->lines[y] + x; pixel->r = (pixel->r * invA + 255 * brightness) >> 8; pixel->g = pixel->r; pixel->b = pixel->r; } } } void Sierpinski3DMain() { CreateWin(800, 600, WT_WINDOWED, "Sierpinski Gasket Example"); DfFont *font = DfCreateFont("Courier New", 12, 4); CreateSierpinski3D(); while (!g_window->windowClosed && !g_input.keyDowns[KEY_ESC]) { ClearBitmap(g_window->bmp, g_colourBlack); InputManagerAdvance(); if (g_input.keys[KEY_UP]) g_cameraPos.z += 20.0f * g_window->advanceTime; if (g_input.keys[KEY_DOWN]) g_cameraPos.z -= 20.0f * g_window->advanceTime; if (g_input.keys[KEY_LEFT]) g_rotationX += 0.9f * g_window->advanceTime; if (g_input.keys[KEY_RIGHT]) g_rotationX -= 0.9f * g_window->advanceTime; Render(); // Draw frames per second counter DrawTextRight(font, g_colourWhite, g_window->bmp, g_window->bmp->width - 5, 0, "FPS:%i", g_window->fps); UpdateWin(); // DfSleepMillisec(10); } } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $ $Revision: 1.63 $ $Name: $ $Author: shoops $ $Date: 2006/06/20 13:19:52 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CScanTask class. * * This class implements a scan task which is comprised of a * of a problem and a method. * */ #include "copasi.h" #include "CScanTask.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "utilities/CReadConfig.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "model/CModel.h" #include "model/CState.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "utilities/COutputHandler.h" #include "utilities/CProcessReport.h" #include "CopasiDataModel/CCopasiDataModel.h" CScanTask::CScanTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::scan, pParent) { mpProblem = new CScanProblem(this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::CScanTask(const CScanTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent) { mpProblem = new CScanProblem(* (CScanProblem *) src.mpProblem, this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::~CScanTask() {cleanup();} void CScanTask::cleanup() {} bool CScanTask::initialize(const OutputFlag & of, std::ostream * pOstream) { assert(mpProblem && mpMethod); bool success = true; if (!CCopasiTask::initialize(of, pOstream)) success = false; return success; } void CScanTask::load(CReadConfig & C_UNUSED(configBuffer)) { CScanProblem* pProblem = dynamic_cast<CScanProblem *>(mpProblem); assert(pProblem); //pProblem->load(configBuffer); } bool CScanTask::process(const bool & /* useInitialValues */) { if (!mpProblem) fatalError(); if (!mpMethod) fatalError(); mpMethod->isValidProblem(mpProblem); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod); if (!pMethod) fatalError(); bool success = true; initSubtask(); pMethod->setProblem(pProblem); //TODO: reports //initialize the method (parsing the ScanItems) if (!pMethod->init()) return false; //init progress bar mProgress = 0; if (mpCallBack) { mpCallBack->setName("performing parameter scan..."); unsigned C_INT32 totalSteps = pMethod->getTotalNumberOfSteps(); mpCallBack->addItem("Number of Steps", CCopasiParameter::UINT, &mProgress, &totalSteps); } //init output handler (plotting) output(COutputInterface::BEFORE); //calling the scanner, output is done in the callback if (!pMethod->scan()) success = false; //finishing progress bar and output if (mpCallBack) mpCallBack->finish(); //if (mpOutputHandler) mpOutputHandler->finish(); output(COutputInterface::AFTER); return success; } bool CScanTask::processCallback() { mpSubtask->process(!mAdjustInitialConditions); //do output if (!mOutputInSubtask) output(COutputInterface::DURING); //do progress bar ++mProgress; if (mpCallBack) return mpCallBack->progress(); return true; } bool CScanTask::outputSeparatorCallback(bool isLast) { if ((!isLast) || mOutputInSubtask) separate(COutputInterface::DURING); return true; } bool CScanTask::initSubtask() { if (!mpProblem) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); //get the parameters from the problem CCopasiTask::Type type = *(CCopasiTask::Type*) pProblem->getValue("Subtask").pUINT; switch (type) { case CCopasiTask::steadyState: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Steady-State"]); break; case CCopasiTask::timeCourse: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Time-Course"]); break; case CCopasiTask::mca: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Metabolic Control Analysis"]); break; case CCopasiTask::lyap: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Lyapunov Exponents"]); break; default: mpSubtask = NULL; } /* if (type == CCopasiTask::steadyState) { mpSubtask=const_cast<CCopasiTask*> (dynamic_cast<const CCopasiTask*> (CCopasiContainer::Root->getObject(CCopasiObjectName("Task=Steady-State")))); } else {mpSubtask=NULL;}*/ mOutputInSubtask = * pProblem->getValue("Output in subtask").pBOOL; //if (type != CCopasiTask::timeCourse) // mOutputInSubtask = false; mAdjustInitialConditions = * pProblem->getValue("Adjust initial conditions").pBOOL; if (!mpSubtask) return false; mpSubtask->getProblem()->setModel(CCopasiDataModel::Global->getModel()); mpSubtask->setCallBack(NULL); if (mOutputInSubtask) mpSubtask->initialize(OUTPUT, NULL); else mpSubtask->initialize(NO_OUTPUT, NULL); return true; } <commit_msg>use nested progress bar for subtasks<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $ $Revision: 1.64 $ $Name: $ $Author: ssahle $ $Date: 2007/01/11 09:33:15 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CScanTask class. * * This class implements a scan task which is comprised of a * of a problem and a method. * */ #include "copasi.h" #include "CScanTask.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "utilities/CReadConfig.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "model/CModel.h" #include "model/CState.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "utilities/COutputHandler.h" #include "utilities/CProcessReport.h" #include "CopasiDataModel/CCopasiDataModel.h" CScanTask::CScanTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::scan, pParent) { mpProblem = new CScanProblem(this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::CScanTask(const CScanTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent) { mpProblem = new CScanProblem(* (CScanProblem *) src.mpProblem, this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::~CScanTask() {cleanup();} void CScanTask::cleanup() {} bool CScanTask::initialize(const OutputFlag & of, std::ostream * pOstream) { assert(mpProblem && mpMethod); bool success = true; if (!CCopasiTask::initialize(of, pOstream)) success = false; return success; } void CScanTask::load(CReadConfig & C_UNUSED(configBuffer)) { CScanProblem* pProblem = dynamic_cast<CScanProblem *>(mpProblem); assert(pProblem); //pProblem->load(configBuffer); } bool CScanTask::process(const bool & /* useInitialValues */) { if (!mpProblem) fatalError(); if (!mpMethod) fatalError(); mpMethod->isValidProblem(mpProblem); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod); if (!pMethod) fatalError(); bool success = true; initSubtask(); pMethod->setProblem(pProblem); //TODO: reports //initialize the method (parsing the ScanItems) if (!pMethod->init()) return false; //init progress bar mProgress = 0; if (mpCallBack) { mpCallBack->setName("performing parameter scan..."); unsigned C_INT32 totalSteps = pMethod->getTotalNumberOfSteps(); mpCallBack->addItem("Number of Steps", CCopasiParameter::UINT, &mProgress, &totalSteps); if (mpSubtask) mpSubtask->setCallBack(mpCallBack); } //init output handler (plotting) output(COutputInterface::BEFORE); //calling the scanner, output is done in the callback if (!pMethod->scan()) success = false; //finishing progress bar and output if (mpCallBack) mpCallBack->finish(); //if (mpOutputHandler) mpOutputHandler->finish(); output(COutputInterface::AFTER); return success; } bool CScanTask::processCallback() { mpSubtask->process(!mAdjustInitialConditions); //do output if (!mOutputInSubtask) output(COutputInterface::DURING); //do progress bar ++mProgress; if (mpCallBack) return mpCallBack->progress(); return true; } bool CScanTask::outputSeparatorCallback(bool isLast) { if ((!isLast) || mOutputInSubtask) separate(COutputInterface::DURING); return true; } bool CScanTask::initSubtask() { if (!mpProblem) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); //get the parameters from the problem CCopasiTask::Type type = *(CCopasiTask::Type*) pProblem->getValue("Subtask").pUINT; switch (type) { case CCopasiTask::steadyState: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Steady-State"]); break; case CCopasiTask::timeCourse: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Time-Course"]); break; case CCopasiTask::mca: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Metabolic Control Analysis"]); break; case CCopasiTask::lyap: mpSubtask = dynamic_cast<CCopasiTask*> ((*CCopasiDataModel::Global->getTaskList())["Lyapunov Exponents"]); break; default: mpSubtask = NULL; } /* if (type == CCopasiTask::steadyState) { mpSubtask=const_cast<CCopasiTask*> (dynamic_cast<const CCopasiTask*> (CCopasiContainer::Root->getObject(CCopasiObjectName("Task=Steady-State")))); } else {mpSubtask=NULL;}*/ mOutputInSubtask = * pProblem->getValue("Output in subtask").pBOOL; //if (type != CCopasiTask::timeCourse) // mOutputInSubtask = false; mAdjustInitialConditions = * pProblem->getValue("Adjust initial conditions").pBOOL; if (!mpSubtask) return false; mpSubtask->getProblem()->setModel(CCopasiDataModel::Global->getModel()); mpSubtask->setCallBack(NULL); if (mOutputInSubtask) mpSubtask->initialize(OUTPUT, NULL); else mpSubtask->initialize(NO_OUTPUT, NULL); return true; } <|endoftext|>
<commit_before>/* This code is provided under the BSD license. Copyright (c) 2014, Emlid Limited. All rights reserved. Written by Igor Vereninov and Mikhail Avkhimenia twitter.com/emlidtech || www.emlid.com || [email protected] Application: Mahory AHRS algorithm supplied with data from MPU9250. Outputs roll, pitch and yaw in the console and sends quaternion over the network - it can be used with 3D IMU visualizer located in Navio/Applications/3D IMU visualizer. To run this app navigate to the directory containing it and run following commands: make sudo ./AHRS If you want to visualize IMU data on another machine pass it's address and port sudo ./AHRS ipaddress portnumber To achieve stable loop you need to run this application with a high priority on a linux kernel with real-time patch. Raspbian distribution with real-time kernel is available at emlid.com and priority can be set with chrt command: chrt -f -p 99 PID */ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdint.h> #include <unistd.h> #include <sys/time.h> #include "Navio/MPU9250.h" #include "AHRS.hpp" // Objects MPU9250 imu; // MPU9250 AHRS ahrs; // Mahony AHRS // Sensor data float ax, ay, az; float gx, gy, gz; float mx, my, mz; // Orientation data float roll, pitch, yaw; // Timing data float offset[3]; struct timeval tv; float dt, maxdt; float mindt = 0.01; unsigned long previoustime, currenttime; float dtsumm = 0; int isFirst = 1; // Network data int sockfd; struct sockaddr_in servaddr = {0}; char sendline[80]; //============================= Initial setup ================================= void imuSetup() { //----------------------- MPU initialization ------------------------------ imu.initialize(); //------------------------------------------------------------------------- printf("Beginning Gyro calibration...\n"); for(int i = 0; i<100; i++) { imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); offset[0] += (-gx*0.0175); offset[1] += (-gy*0.0175); offset[2] += (-gz*0.0175); usleep(10000); } offset[0]/=100.0; offset[1]/=100.0; offset[2]/=100.0; printf("Offsets are: %f %f %f\n", offset[0], offset[1], offset[2]); ahrs.setGyroOffset(offset[0], offset[1], offset[2]); } //============================== Main loop ==================================== void imuLoop() { //----------------------- Calculate delta time ---------------------------- gettimeofday(&tv,NULL); previoustime = currenttime; currenttime = 1000000 * tv.tv_sec + tv.tv_usec; dt = (currenttime - previoustime) / 1000000.0; if(dt < 1/1300.0) usleep((1/1300.0-dt)*1000000); gettimeofday(&tv,NULL); currenttime = 1000000 * tv.tv_sec + tv.tv_usec; dt = (currenttime - previoustime) / 1000000.0; //-------- Read raw measurements from the MPU and update AHRS -------------- imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); ahrs.updateIMU(ax, ay, az, gx*0.0175, gy*0.0175, gz*0.0175, dt); // FIXME In order to use magnetometer it's orientation has to be fixed // according to MPU9250 datasheet. Also, soft and hard iron calibration // would be required. // imu.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz); // ahrs.update(ax, ay, az, gx/0.0175, gy/0.0175, gz/0.0175, mx, my, mz, dt); //------------------------ Read Euler angles ------------------------------ ahrs.getEuler(&roll, &pitch, &yaw); //------------------- Discard the time of the first cycle ----------------- if (!isFirst) { if (dt > maxdt) maxdt = dt; if (dt < mindt) mindt = dt; } isFirst = 0; //------------- Console and network output with a lowered rate ------------ dtsumm += dt; if(dtsumm > 0.05) { // Console output printf("ROLL: %+05.2f PITCH: %+05.2f YAW: %+05.2f PERIOD %.4fs RATE %dHz \n", roll, pitch, yaw * -1, dt, int(1/dt)); // Network output sprintf(sendline,"%10f %10f %10f %10f %dHz\n", ahrs.getW(), ahrs.getX(), ahrs.getY(), ahrs.getZ(), int(1/dt)); sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); dtsumm = 0; } } //============================================================================= int main(int argc, char *argv[]) { //--------------------------- Network setup ------------------------------- sockfd = socket(AF_INET,SOCK_DGRAM,0); servaddr.sin_family = AF_INET; if (argc == 3) { servaddr.sin_addr.s_addr = inet_addr(argv[1]); servaddr.sin_port = htons(atoi(argv[2])); } else { servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(7000); } //-------------------- IMU setup and main loop ---------------------------- imuSetup(); while(1) imuLoop(); } <commit_msg>Update AHRS.cpp<commit_after>/* This code is provided under the BSD license. Copyright (c) 2014, Emlid Limited. All rights reserved. Written by Igor Vereninov and Mikhail Avkhimenia twitter.com/emlidtech || www.emlid.com || [email protected] Application: Mahory AHRS algorithm supplied with data from MPU9250. Outputs roll, pitch and yaw in the console and sends quaternion over the network - it can be used with 3D IMU visualizer located in Navio/Applications/3D IMU visualizer. To run this app navigate to the directory containing it and run following commands: make sudo ./AHRS If you want to visualize IMU data on another machine pass it's address and port sudo ./AHRS ipaddress portnumber To achieve stable loop you need to run this application with a high priority on a linux kernel with real-time patch. Raspbian distribution with real-time kernel is available at emlid.com and priority can be set with chrt command: chrt -f -p 99 PID */ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdint.h> #include <unistd.h> #include <sys/time.h> #include "Navio/MPU9250.h" #include "AHRS.hpp" // Objects MPU9250 imu; // MPU9250 AHRS ahrs; // Mahony AHRS // Sensor data float ax, ay, az; float gx, gy, gz; float mx, my, mz; // Orientation data float roll, pitch, yaw; // Timing data float offset[3]; struct timeval tv; float dt, maxdt; float mindt = 0.01; unsigned long previoustime, currenttime; float dtsumm = 0; int isFirst = 1; // Network data int sockfd; struct sockaddr_in servaddr = {0}; char sendline[80]; //============================= Initial setup ================================= void imuSetup() { //----------------------- MPU initialization ------------------------------ imu.initialize(); //------------------------------------------------------------------------- printf("Beginning Gyro calibration...\n"); for(int i = 0; i<100; i++) { imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); offset[0] += (-gx*0.0175); offset[1] += (-gy*0.0175); offset[2] += (-gz*0.0175); usleep(10000); } offset[0]/=100.0; offset[1]/=100.0; offset[2]/=100.0; printf("Offsets are: %f %f %f\n", offset[0], offset[1], offset[2]); ahrs.setGyroOffset(offset[0], offset[1], offset[2]); } //============================== Main loop ==================================== void imuLoop() { //----------------------- Calculate delta time ---------------------------- gettimeofday(&tv,NULL); previoustime = currenttime; currenttime = 1000000 * tv.tv_sec + tv.tv_usec; dt = (currenttime - previoustime) / 1000000.0; if(dt < 1/1300.0) usleep((1/1300.0-dt)*1000000); gettimeofday(&tv,NULL); currenttime = 1000000 * tv.tv_sec + tv.tv_usec; dt = (currenttime - previoustime) / 1000000.0; //-------- Read raw measurements from the MPU and update AHRS -------------- imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); ahrs.updateIMU(ax, ay, az, gx*0.0175, gy*0.0175, gz*0.0175, dt); // Soft and hard iron calibration required for proper function. // imu.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz); // ahrs.update(ax, ay, az, gx*0.0175, gy*0.0175, gz*0.0175, my, mx, -mz, dt); //------------------------ Read Euler angles ------------------------------ ahrs.getEuler(&roll, &pitch, &yaw); //------------------- Discard the time of the first cycle ----------------- if (!isFirst) { if (dt > maxdt) maxdt = dt; if (dt < mindt) mindt = dt; } isFirst = 0; //------------- Console and network output with a lowered rate ------------ dtsumm += dt; if(dtsumm > 0.05) { // Console output printf("ROLL: %+05.2f PITCH: %+05.2f YAW: %+05.2f PERIOD %.4fs RATE %dHz \n", roll, pitch, yaw * -1, dt, int(1/dt)); // Network output sprintf(sendline,"%10f %10f %10f %10f %dHz\n", ahrs.getW(), ahrs.getX(), ahrs.getY(), ahrs.getZ(), int(1/dt)); sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); dtsumm = 0; } } //============================================================================= int main(int argc, char *argv[]) { //--------------------------- Network setup ------------------------------- sockfd = socket(AF_INET,SOCK_DGRAM,0); servaddr.sin_family = AF_INET; if (argc == 3) { servaddr.sin_addr.s_addr = inet_addr(argv[1]); servaddr.sin_port = htons(atoi(argv[2])); } else { servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(7000); } //-------------------- IMU setup and main loop ---------------------------- imuSetup(); while(1) imuLoop(); } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(n) class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { vector<int> x, y; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j]) { x.emplace_back(i); y.emplace_back(j); } } } nth_element(x.begin(), x.begin() + x.size() / 2, x.end()); nth_element(y.begin(), y.begin() + y.size() / 2, y.end()); const int mid_x = x[x.size() / 2]; const int mid_y = y[y.size() / 2]; int sum = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j]) { sum += abs(mid_x - i) + abs(mid_y - j); } } } return sum; } }; <commit_msg>Update best-meeting-point.cpp<commit_after>// Time: O(m * n) // Space: O(m + n) class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { vector<int> x, y; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j]) { x.emplace_back(i); y.emplace_back(j); } } } nth_element(x.begin(), x.begin() + x.size() / 2, x.end()); nth_element(y.begin(), y.begin() + y.size() / 2, y.end()); const int mid_x = x[x.size() / 2]; const int mid_y = y[y.size() / 2]; int sum = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j]) { sum += abs(mid_x - i) + abs(mid_y - j); } } } return sum; } }; <|endoftext|>
<commit_before>//============================================================================================================= /** * @file ecddatatreeitem.cpp * @author Lorenz Esch <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date November, 2015 * * @section LICENSE * * Copyright (C) 2015, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief EcdDataTreeItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "ecddatatreeitem.h" #include "../common/metatreeitem.h" #include <inverse/dipoleFit/ecd_set.h> #include "../../3dhelpers/geometrymultiplier.h" #include "../../materials/geometrymultipliermaterial.h" //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QList> #include <QVariant> #include <QStringList> #include <QColor> #include <QVector3D> #include <QStandardItem> #include <QStandardItemModel> #include <Qt3DRender/qshaderprogram.h> #include <QQuaternion> #include <Qt3DExtras/QConeGeometry> #include <QMatrix4x4> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace INVERSELIB; using namespace DISP3DLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= EcdDataTreeItem::EcdDataTreeItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : Abstract3DTreeItem(p3DEntityParent, iType, text) { initItem(); } //************************************************************************************************************* void EcdDataTreeItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip("Dipole fit data"); } //************************************************************************************************************* void EcdDataTreeItem::addData(const ECDSet& pECDSet) { //Add further infos as children QList<QStandardItem*> list; MetaTreeItem *pItemNumDipoles = new MetaTreeItem(MetaTreeItemTypes::NumberDipoles, QString::number(pECDSet.size())); pItemNumDipoles->setEditable(false); list.clear(); list << pItemNumDipoles; list << new QStandardItem(pItemNumDipoles->toolTip()); this->appendRow(list); //Plot dipole moment plotDipoles(pECDSet); } //************************************************************************************************************* void EcdDataTreeItem::plotDipoles(const ECDSet& tECDSet) { //Plot dipoles //create geometry QSharedPointer<Qt3DExtras::QConeGeometry> pDipolGeometry = QSharedPointer<Qt3DExtras::QConeGeometry>::create(); pDipolGeometry->setBottomRadius(0.001f); pDipolGeometry->setLength(0.003f); //create instanced renderer GeometryMultiplier *pDipolMesh = new GeometryMultiplier(pDipolGeometry); QVector3D pos, to, from; //The Qt3D default cone orientation and the top of the cone lies in line with the positive y-axis. from = QVector3D(0.0, 1.0, 0.0); double norm; QVector<QColor> vColors; vColors.reserve(tECDSet.size()); QVector<QMatrix4x4> vTransforms; vTransforms.reserve(tECDSet.size()); for(int i = 0; i < tECDSet.size(); ++i) { pos.setX(tECDSet[i].rd(0)); pos.setY(tECDSet[i].rd(1)); pos.setZ(tECDSet[i].rd(2)); norm = sqrt(pow(tECDSet[i].Q(0),2)+pow(tECDSet[i].Q(1),2)+pow(tECDSet[i].Q(2),2)); to.setX(tECDSet[i].Q(0)/norm); to.setY(tECDSet[i].Q(1)/norm); to.setZ(tECDSet[i].Q(2)/norm); // qDebug()<<"EcdDataTreeItem::plotDipoles - from" << from; // qDebug()<<"EcdDataTreeItem::plotDipoles - to" << to; QQuaternion final = QQuaternion::rotationTo(from, to); //Set dipole position and orientation QMatrix4x4 m; m.translate(pos); m.rotate(final); vTransforms.push_back(m); //add random color; vColors.push_back(QColor(rand()%255, rand()%255, rand()%255)); } //Set instance Transform pDipolMesh->setTransforms(vTransforms); //Set instance colors pDipolMesh->setColors(vColors); this->addComponent(pDipolMesh); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial; pMaterial->setAmbient(QColor(0,0,0)); pMaterial->setAlpha(1.0f); this->addComponent(pMaterial); } <commit_msg>swapped unseeded rand() calls with qt equivalent<commit_after>//============================================================================================================= /** * @file ecddatatreeitem.cpp * @author Lorenz Esch <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date November, 2015 * * @section LICENSE * * Copyright (C) 2015, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief EcdDataTreeItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "ecddatatreeitem.h" #include "../common/metatreeitem.h" #include <inverse/dipoleFit/ecd_set.h> #include "../../3dhelpers/geometrymultiplier.h" #include "../../materials/geometrymultipliermaterial.h" //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QList> #include <QVariant> #include <QStringList> #include <QColor> #include <QVector3D> #include <QStandardItem> #include <QStandardItemModel> #include <Qt3DRender/qshaderprogram.h> #include <QQuaternion> #include <Qt3DExtras/QConeGeometry> #include <QMatrix4x4> #include <QRandomGenerator> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace INVERSELIB; using namespace DISP3DLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= EcdDataTreeItem::EcdDataTreeItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : Abstract3DTreeItem(p3DEntityParent, iType, text) { initItem(); } //************************************************************************************************************* void EcdDataTreeItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip("Dipole fit data"); } //************************************************************************************************************* void EcdDataTreeItem::addData(const ECDSet& pECDSet) { //Add further infos as children QList<QStandardItem*> list; MetaTreeItem *pItemNumDipoles = new MetaTreeItem(MetaTreeItemTypes::NumberDipoles, QString::number(pECDSet.size())); pItemNumDipoles->setEditable(false); list.clear(); list << pItemNumDipoles; list << new QStandardItem(pItemNumDipoles->toolTip()); this->appendRow(list); //Plot dipole moment plotDipoles(pECDSet); } //************************************************************************************************************* void EcdDataTreeItem::plotDipoles(const ECDSet& tECDSet) { //Plot dipoles //create geometry QSharedPointer<Qt3DExtras::QConeGeometry> pDipolGeometry = QSharedPointer<Qt3DExtras::QConeGeometry>::create(); pDipolGeometry->setBottomRadius(0.001f); pDipolGeometry->setLength(0.003f); //create instanced renderer GeometryMultiplier *pDipolMesh = new GeometryMultiplier(pDipolGeometry); QVector3D pos, to, from; //The Qt3D default cone orientation and the top of the cone lies in line with the positive y-axis. from = QVector3D(0.0, 1.0, 0.0); double norm; QVector<QColor> vColors; vColors.reserve(tECDSet.size()); QVector<QMatrix4x4> vTransforms; vTransforms.reserve(tECDSet.size()); for(int i = 0; i < tECDSet.size(); ++i) { pos.setX(tECDSet[i].rd(0)); pos.setY(tECDSet[i].rd(1)); pos.setZ(tECDSet[i].rd(2)); norm = sqrt(pow(tECDSet[i].Q(0),2)+pow(tECDSet[i].Q(1),2)+pow(tECDSet[i].Q(2),2)); to.setX(tECDSet[i].Q(0)/norm); to.setY(tECDSet[i].Q(1)/norm); to.setZ(tECDSet[i].Q(2)/norm); // qDebug()<<"EcdDataTreeItem::plotDipoles - from" << from; // qDebug()<<"EcdDataTreeItem::plotDipoles - to" << to; QQuaternion final = QQuaternion::rotationTo(from, to); //Set dipole position and orientation QMatrix4x4 m; m.translate(pos); m.rotate(final); vTransforms.push_back(m); //add random color; vColors.push_back(QColor(QRandomGenerator::global()->bounded(0 , 255), QRandomGenerator::global()->bounded(0 , 255), QRandomGenerator::global()->bounded(0 , 255))); } //Set instance Transform pDipolMesh->setTransforms(vTransforms); //Set instance colors pDipolMesh->setColors(vColors); this->addComponent(pDipolMesh); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial; pMaterial->setAmbient(QColor(0,0,0)); pMaterial->setAlpha(1.0f); this->addComponent(pMaterial); } <|endoftext|>
<commit_before>#include "SINSymbolTable.h" #include "SINAssert.h" #define ASSERT_CURRENT_SCOPE() SINASSERT(currScope < table.size()); SINASSERT(currScope >= 0) #define ASSERT_GIVEN_SCOPE() SINASSERT(scope < table.size()) #define ASSERT_SCOPE(SCOPE) SINASSERT(SCOPE < table.size()) #define RETURN_VALUE(SCOPE, FUNCTION_NAME, ARGUMENT) ASSERT_SCOPE(SCOPE); \ return table[SCOPE].FUNCTION_NAME(ARGUMENT) namespace SIN { //----------------------------------------------------------------- SymbolTable::SymbolTable(void) { table.reserve(20); table.push_back(VariableHolder()); currScope = 0; } SymbolTable::~SymbolTable() {} //----------------------------------------------------------------- // in current and smaller scopes SymbolTable::elem_t& SymbolTable::Lookup(const name_t& name) { ASSERT_CURRENT_SCOPE(); elem_t* element_p = 0x00; for(scope_id scope = currScope; scope > 0; --scope) if(static_cast<MemoryCell*>(*(element_p = &Lookup(scope, name))) != static_cast<MemoryCell*>(0x00)) return *element_p; // do once more for scope 0 return Lookup(0, name); } //----------------------------------------------------------------- // in given scope SymbolTable::elem_t& SymbolTable::Lookup(const scope_id& scope, const name_t& name) { RETURN_VALUE(scope, LookupArgument, name); } //----------------------------------------------------------------- // in current scope SymbolTable::elem_t& SymbolTable::LookupOnlyInCurrentScope(const name_t& name) { RETURN_VALUE(currScope, LookupArgument, name); } //----------------------------------------------------------------- // in current scope SymbolTable::elem_t& SymbolTable::LookupByIndex(const unsigned int index) { RETURN_VALUE(currScope, Argument, index); } //----------------------------------------------------------------- // in given scope SymbolTable::elem_t& SymbolTable::LookupByIndex(const scope_id& scope, const unsigned int index) { RETURN_VALUE(scope, Argument, index); } //----------------------------------------------------------------- // only in current scope void SymbolTable::Insert(const name_t& name, const SymbolTable::elem_t& element) { ASSERT_CURRENT_SCOPE(); table[currScope].AppendArgument(name, element); } //----------------------------------------------------------------- void SymbolTable::IncreaseScope(void) { table.push_back(VariableHolder()); ++currScope; } //----------------------------------------------------------------- void SymbolTable::DecreaseScope(void) { SINASSERT(!"not implemented"); } //----------------------------------------------------------------- const SymbolTable::scope_id SymbolTable::CurrentScope(void) const { return currScope; } //----------------------------------------------------------------- // current scope unsigned int SymbolTable::NumberOfSymbols(void) const { ASSERT_CURRENT_SCOPE(); return table[currScope].NumberOfArguments(); } //----------------------------------------------------------------- // in given scope unsigned int SymbolTable::NumberOfSymbols(const scope_id& scope) const { ASSERT_GIVEN_SCOPE(); return table[scope].NumberOfArguments(); } //----------------------------------------------------------------- struct CallableToEntryHolderAdaptor: public VariableHolder::Callable { typedef VariableHolder::Entry entry_t; typedef SymbolTable::EntryHandler handler_t; handler_t& entry_handler; handler_t const& const_entry_handler; CallableToEntryHolderAdaptor(handler_t& eh): entry_handler(eh), const_entry_handler(eh) { } CallableToEntryHolderAdaptor(handler_t const& eh): entry_handler(*static_cast<handler_t*>(0x00)), const_entry_handler(eh) { } virtual ~CallableToEntryHolderAdaptor(void) { } virtual bool operator ()(entry_t const& _entry) { return entry_handler(_entry.name, _entry.value); } virtual bool operator ()(entry_t const& _entry) const { return const_entry_handler(_entry.name, _entry.value); } }; // struct CallableToEntryHolderAdaptor #define FOR_EACH_SYMBOL() ASSERT_CURRENT_SCOPE(); \ table[currScope].for_each_argument(CallableToEntryHolderAdaptor(eh)); \ return eh //----------------------------------------------------------------- // in current scope SymbolTable::EntryHandler& SymbolTable::for_each_symbol(SymbolTable::EntryHandler& eh) const { FOR_EACH_SYMBOL(); } //----------------------------------------------------------------- // in current scope const SymbolTable::EntryHandler& SymbolTable::for_each_symbol(const SymbolTable::EntryHandler& eh) const { FOR_EACH_SYMBOL(); } }<commit_msg>Implemented all the SymbolTable methods<commit_after>#include "SINSymbolTable.h" #include "SINAssert.h" #define ASSERT_CURRENT_SCOPE() SINASSERT(currScope < table.size()); SINASSERT(currScope >= 0) #define ASSERT_GIVEN_SCOPE() SINASSERT(scope < table.size()) #define ASSERT_SCOPE(SCOPE) SINASSERT(SCOPE < table.size()) #define RETURN_VALUE(SCOPE, FUNCTION_NAME, ARGUMENT) ASSERT_SCOPE(SCOPE); \ return table[SCOPE].FUNCTION_NAME(ARGUMENT) namespace SIN { //----------------------------------------------------------------- SymbolTable::SymbolTable(void) { table.reserve(20); table.push_back(VariableHolder()); currScope = 0; } SymbolTable::~SymbolTable() {} //----------------------------------------------------------------- // in current and smaller scopes SymbolTable::elem_t& SymbolTable::Lookup(const name_t& name) { ASSERT_CURRENT_SCOPE(); elem_t* element_p = 0x00; for(scope_id scope = currScope; scope > 0; --scope) if(static_cast<MemoryCell*>(*(element_p = &Lookup(scope, name))) != static_cast<MemoryCell*>(0x00)) return *element_p; // do once more for scope 0 return Lookup(0, name); } //----------------------------------------------------------------- // in given scope SymbolTable::elem_t& SymbolTable::Lookup(const scope_id& scope, const name_t& name) { RETURN_VALUE(scope, LookupArgument, name); } //----------------------------------------------------------------- // in current scope SymbolTable::elem_t& SymbolTable::LookupOnlyInCurrentScope(const name_t& name) { RETURN_VALUE(currScope, LookupArgument, name); } //----------------------------------------------------------------- // in current scope SymbolTable::elem_t& SymbolTable::LookupByIndex(const unsigned int index) { RETURN_VALUE(currScope, Argument, index); } //----------------------------------------------------------------- // in given scope SymbolTable::elem_t& SymbolTable::LookupByIndex(const scope_id& scope, const unsigned int index) { RETURN_VALUE(scope, Argument, index); } //----------------------------------------------------------------- // only in current scope void SymbolTable::Insert(const name_t& name, const SymbolTable::elem_t& element) { ASSERT_CURRENT_SCOPE(); table[currScope].AppendArgument(name, element); } //----------------------------------------------------------------- void SymbolTable::IncreaseScope(void) { table.size() == 0 ? currScope = 0: ++currScope; table.push_back(VariableHolder()); } //----------------------------------------------------------------- void SymbolTable::DecreaseScope(void) { table.pop_back(); table.size() == 0 ? currScope = 0 : --currScope; } //----------------------------------------------------------------- const SymbolTable::scope_id SymbolTable::CurrentScope(void) const { return currScope; } //----------------------------------------------------------------- // current scope unsigned int SymbolTable::NumberOfSymbols(void) const { ASSERT_CURRENT_SCOPE(); return table[currScope].NumberOfArguments(); } //----------------------------------------------------------------- // in given scope unsigned int SymbolTable::NumberOfSymbols(const scope_id& scope) const { ASSERT_GIVEN_SCOPE(); return table[scope].NumberOfArguments(); } //----------------------------------------------------------------- struct CallableToEntryHolderAdaptor: public VariableHolder::Callable { typedef VariableHolder::Entry entry_t; typedef SymbolTable::EntryHandler handler_t; handler_t& entry_handler; handler_t const& const_entry_handler; CallableToEntryHolderAdaptor(handler_t& eh): entry_handler(eh), const_entry_handler(eh) { } CallableToEntryHolderAdaptor(handler_t const& eh): entry_handler(*static_cast<handler_t*>(0x00)), const_entry_handler(eh) { } virtual ~CallableToEntryHolderAdaptor(void) { } virtual bool operator ()(entry_t const& _entry) { return entry_handler(_entry.name, _entry.value); } virtual bool operator ()(entry_t const& _entry) const { return const_entry_handler(_entry.name, _entry.value); } }; // struct CallableToEntryHolderAdaptor #define FOR_EACH_SYMBOL() ASSERT_CURRENT_SCOPE(); \ table[currScope].for_each_argument(CallableToEntryHolderAdaptor(eh)); \ return eh //----------------------------------------------------------------- // in current scope SymbolTable::EntryHandler& SymbolTable::for_each_symbol(SymbolTable::EntryHandler& eh) const { FOR_EACH_SYMBOL(); } //----------------------------------------------------------------- // in current scope const SymbolTable::EntryHandler& SymbolTable::for_each_symbol(const SymbolTable::EntryHandler& eh) const { FOR_EACH_SYMBOL(); } }<|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCESTImageNormalizationFilter.h" #include <mitkCustomTagParser.h> #include <mitkImage.h> #include <mitkImageAccessByItk.h> #include <mitkImageCast.h> #include <boost/algorithm/string.hpp> mitk::CESTImageNormalizationFilter::CESTImageNormalizationFilter() { } mitk::CESTImageNormalizationFilter::~CESTImageNormalizationFilter() { } void mitk::CESTImageNormalizationFilter::GenerateData() { mitk::Image::ConstPointer inputImage = this->GetInput(0); if ((inputImage->GetDimension() != 4)) { mitkThrow() << "mitk::CESTImageNormalizationFilter:GenerateData works only with 4D images, sorry."; return; } auto resultMitkImage = this->GetOutput(); AccessFixedDimensionByItk(inputImage, NormalizeTimeSteps, 4); auto originalTimeGeometry = this->GetInput()->GetTimeGeometry(); auto resultTimeGeometry = mitk::ProportionalTimeGeometry::New(); unsigned int numberOfNonM0s = m_NonM0Indices.size(); resultTimeGeometry->Expand(numberOfNonM0s); for (unsigned int index = 0; index < numberOfNonM0s; ++index) { resultTimeGeometry->SetTimeStepGeometry(originalTimeGeometry->GetGeometryCloneForTimeStep(m_NonM0Indices.at(index)), index); } resultMitkImage->SetTimeGeometry(resultTimeGeometry); resultMitkImage->SetPropertyList(this->GetInput()->GetPropertyList()->Clone()); resultMitkImage->GetPropertyList()->SetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), m_RealOffsets.c_str()); } template <typename TPixel, unsigned int VImageDimension> void mitk::CESTImageNormalizationFilter::NormalizeTimeSteps(const itk::Image<TPixel, VImageDimension>* image) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<double, VImageDimension> OutputImageType; std::string offsets = ""; this->GetInput()->GetPropertyList()->GetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), offsets); std::vector<std::string> parts; boost::split(parts, offsets, boost::is_any_of(" ")); // determine normalization images std::vector<unsigned int> mZeroIndices; std::stringstream offsetsWithoutM0; m_NonM0Indices.clear(); for (unsigned int index = 0; index < parts.size(); ++index) { if ((std::stod(parts.at(index)) < -299) || (std::stod(parts.at(index)) > 299)) { mZeroIndices.push_back(index); } else { offsetsWithoutM0 << parts.at(index) << " "; m_NonM0Indices.push_back(index); } } auto resultImage = OutputImageType::New(); typename ImageType::RegionType targetEntireRegion = image->GetLargestPossibleRegion(); targetEntireRegion.SetSize(3, m_NonM0Indices.size()); resultImage->SetRegions(targetEntireRegion); resultImage->Allocate(); resultImage->FillBuffer(0); unsigned int numberOfTimesteps = image->GetLargestPossibleRegion().GetSize(3); typename ImageType::RegionType lowerMZeroRegion = image->GetLargestPossibleRegion(); lowerMZeroRegion.SetSize(3, 1); typename ImageType::RegionType upperMZeroRegion = image->GetLargestPossibleRegion(); upperMZeroRegion.SetSize(3, 1); typename ImageType::RegionType sourceRegion = image->GetLargestPossibleRegion(); sourceRegion.SetSize(3, 1); typename OutputImageType::RegionType targetRegion = resultImage->GetLargestPossibleRegion(); targetRegion.SetSize(3, 1); unsigned int targetTimestep = 0; for (unsigned int sourceTimestep = 0; sourceTimestep < numberOfTimesteps; ++sourceTimestep) { unsigned int lowerMZeroIndex = mZeroIndices[0]; unsigned int upperMZeroIndex = mZeroIndices[0]; for (unsigned int loop = 0; loop < mZeroIndices.size(); ++loop) { if (mZeroIndices[loop] <= sourceTimestep) { lowerMZeroIndex = mZeroIndices[loop]; } if (mZeroIndices[loop] > sourceTimestep) { upperMZeroIndex = mZeroIndices[loop]; break; } } bool isMZero = (lowerMZeroIndex == sourceTimestep); double weight = 0.0; if (lowerMZeroIndex == upperMZeroIndex) { weight = 1.0; } else { weight = 1.0 - double(sourceTimestep - lowerMZeroIndex) / double(upperMZeroIndex - lowerMZeroIndex); } lowerMZeroRegion.SetIndex(3, lowerMZeroIndex); upperMZeroRegion.SetIndex(3, upperMZeroIndex); sourceRegion.SetIndex(3, sourceTimestep); targetRegion.SetIndex(3, targetTimestep); itk::ImageRegionConstIterator<ImageType> lowerMZeroIterator(image, lowerMZeroRegion); itk::ImageRegionConstIterator<ImageType> upperMZeroIterator(image, upperMZeroRegion); itk::ImageRegionConstIterator<ImageType> sourceIterator(image, sourceRegion); itk::ImageRegionIterator<OutputImageType> targetIterator(resultImage.GetPointer(), targetRegion); if (isMZero) { //do nothing } else { while (!sourceIterator.IsAtEnd()) { targetIterator.Set(double(sourceIterator.Get()) / (weight * lowerMZeroIterator.Get() + (1.0 - weight) * upperMZeroIterator.Get())); ++lowerMZeroIterator; ++upperMZeroIterator; ++sourceIterator; ++targetIterator; } ++targetTimestep; } } // get Pointer to output image mitk::Image::Pointer resultMitkImage = this->GetOutput(); // write into output image mitk::CastToMitkImage<OutputImageType>(resultImage, resultMitkImage); m_RealOffsets = offsetsWithoutM0.str(); } void mitk::CESTImageNormalizationFilter::GenerateOutputInformation() { mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); itkDebugMacro(<< "GenerateOutputInformation()"); } <commit_msg>Remove uids after normalization and a fix for the last time step being M0<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCESTImageNormalizationFilter.h" #include <mitkCustomTagParser.h> #include <mitkImage.h> #include <mitkImageAccessByItk.h> #include <mitkImageCast.h> #include <boost/algorithm/string.hpp> mitk::CESTImageNormalizationFilter::CESTImageNormalizationFilter() { } mitk::CESTImageNormalizationFilter::~CESTImageNormalizationFilter() { } void mitk::CESTImageNormalizationFilter::GenerateData() { mitk::Image::ConstPointer inputImage = this->GetInput(0); if ((inputImage->GetDimension() != 4)) { mitkThrow() << "mitk::CESTImageNormalizationFilter:GenerateData works only with 4D images, sorry."; return; } auto resultMitkImage = this->GetOutput(); AccessFixedDimensionByItk(inputImage, NormalizeTimeSteps, 4); auto originalTimeGeometry = this->GetInput()->GetTimeGeometry(); auto resultTimeGeometry = mitk::ProportionalTimeGeometry::New(); unsigned int numberOfNonM0s = m_NonM0Indices.size(); resultTimeGeometry->Expand(numberOfNonM0s); for (unsigned int index = 0; index < numberOfNonM0s; ++index) { resultTimeGeometry->SetTimeStepGeometry(originalTimeGeometry->GetGeometryCloneForTimeStep(m_NonM0Indices.at(index)), index); } resultMitkImage->SetTimeGeometry(resultTimeGeometry); resultMitkImage->SetPropertyList(this->GetInput()->GetPropertyList()->Clone()); resultMitkImage->GetPropertyList()->SetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), m_RealOffsets.c_str()); // remove uids resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0008.0018"); resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0020.000D"); resultMitkImage->GetPropertyList()->DeleteProperty("DICOM.0020.000E"); } template <typename TPixel, unsigned int VImageDimension> void mitk::CESTImageNormalizationFilter::NormalizeTimeSteps(const itk::Image<TPixel, VImageDimension>* image) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<double, VImageDimension> OutputImageType; std::string offsets = ""; this->GetInput()->GetPropertyList()->GetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), offsets); std::vector<std::string> parts; boost::split(parts, offsets, boost::is_any_of(" ")); // determine normalization images std::vector<unsigned int> mZeroIndices; std::stringstream offsetsWithoutM0; m_NonM0Indices.clear(); for (unsigned int index = 0; index < parts.size(); ++index) { if ((std::stod(parts.at(index)) < -299) || (std::stod(parts.at(index)) > 299)) { mZeroIndices.push_back(index); } else { offsetsWithoutM0 << parts.at(index) << " "; m_NonM0Indices.push_back(index); } } auto resultImage = OutputImageType::New(); typename ImageType::RegionType targetEntireRegion = image->GetLargestPossibleRegion(); targetEntireRegion.SetSize(3, m_NonM0Indices.size()); resultImage->SetRegions(targetEntireRegion); resultImage->Allocate(); resultImage->FillBuffer(0); unsigned int numberOfTimesteps = image->GetLargestPossibleRegion().GetSize(3); typename ImageType::RegionType lowerMZeroRegion = image->GetLargestPossibleRegion(); lowerMZeroRegion.SetSize(3, 1); typename ImageType::RegionType upperMZeroRegion = image->GetLargestPossibleRegion(); upperMZeroRegion.SetSize(3, 1); typename ImageType::RegionType sourceRegion = image->GetLargestPossibleRegion(); sourceRegion.SetSize(3, 1); typename OutputImageType::RegionType targetRegion = resultImage->GetLargestPossibleRegion(); targetRegion.SetSize(3, 1); unsigned int targetTimestep = 0; for (unsigned int sourceTimestep = 0; sourceTimestep < numberOfTimesteps; ++sourceTimestep) { unsigned int lowerMZeroIndex = mZeroIndices[0]; unsigned int upperMZeroIndex = mZeroIndices[0]; for (unsigned int loop = 0; loop < mZeroIndices.size(); ++loop) { if (mZeroIndices[loop] <= sourceTimestep) { lowerMZeroIndex = mZeroIndices[loop]; } if (mZeroIndices[loop] > sourceTimestep) { upperMZeroIndex = mZeroIndices[loop]; break; } } bool isMZero = (lowerMZeroIndex == sourceTimestep); double weight = 0.0; if (lowerMZeroIndex == upperMZeroIndex) { weight = 1.0; } else { weight = 1.0 - double(sourceTimestep - lowerMZeroIndex) / double(upperMZeroIndex - lowerMZeroIndex); } if (isMZero) { //do nothing } else { lowerMZeroRegion.SetIndex(3, lowerMZeroIndex); upperMZeroRegion.SetIndex(3, upperMZeroIndex); sourceRegion.SetIndex(3, sourceTimestep); targetRegion.SetIndex(3, targetTimestep); itk::ImageRegionConstIterator<ImageType> lowerMZeroIterator(image, lowerMZeroRegion); itk::ImageRegionConstIterator<ImageType> upperMZeroIterator(image, upperMZeroRegion); itk::ImageRegionConstIterator<ImageType> sourceIterator(image, sourceRegion); itk::ImageRegionIterator<OutputImageType> targetIterator(resultImage.GetPointer(), targetRegion); while (!sourceIterator.IsAtEnd()) { targetIterator.Set(double(sourceIterator.Get()) / (weight * lowerMZeroIterator.Get() + (1.0 - weight) * upperMZeroIterator.Get())); ++lowerMZeroIterator; ++upperMZeroIterator; ++sourceIterator; ++targetIterator; } ++targetTimestep; } } // get Pointer to output image mitk::Image::Pointer resultMitkImage = this->GetOutput(); // write into output image mitk::CastToMitkImage<OutputImageType>(resultImage, resultMitkImage); m_RealOffsets = offsetsWithoutM0.str(); } void mitk::CESTImageNormalizationFilter::GenerateOutputInformation() { mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); itkDebugMacro(<< "GenerateOutputInformation()"); } <|endoftext|>
<commit_before>#include "amatrix.h" #include "checks.h" template<std::size_t TSize1, std::size_t TSize2> std::size_t TestZeroMatrixAssign() { AMatrix::Matrix<double, TSize1,TSize2> a_matrix; a_matrix = AMatrix::ZeroMatrix<double>(TSize1, TSize2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(a_matrix(i,j), 0.00); return 0; // not failed } template<std::size_t TSize1, std::size_t TSize2> std::size_t TestMatrixAssign() { AMatrix::Matrix<double, TSize1,TSize2> a_matrix; AMatrix::Matrix<double, TSize1,TSize2> b_matrix; for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) a_matrix(i, j) = 2.33 * i - 4.52 * j; b_matrix = a_matrix; for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(b_matrix(i,j), 2.33 * i - 4.52 * j); return 0; // not failed } int main() { std::size_t number_of_failed_tests = 0; number_of_failed_tests += TestZeroMatrixAssign<1,1>(); number_of_failed_tests += TestZeroMatrixAssign<1,2>(); number_of_failed_tests += TestZeroMatrixAssign<2,1>(); number_of_failed_tests += TestZeroMatrixAssign<2,2>(); number_of_failed_tests += TestZeroMatrixAssign<3,1>(); number_of_failed_tests += TestZeroMatrixAssign<3,2>(); number_of_failed_tests += TestZeroMatrixAssign<3,3>(); number_of_failed_tests += TestZeroMatrixAssign<1,3>(); number_of_failed_tests += TestZeroMatrixAssign<2,3>(); number_of_failed_tests += TestZeroMatrixAssign<3,3>(); number_of_failed_tests += TestMatrixAssign<1,1>(); number_of_failed_tests += TestMatrixAssign<1,2>(); number_of_failed_tests += TestMatrixAssign<2,1>(); number_of_failed_tests += TestMatrixAssign<2,2>(); number_of_failed_tests += TestMatrixAssign<3,1>(); number_of_failed_tests += TestMatrixAssign<3,2>(); number_of_failed_tests += TestMatrixAssign<3,3>(); number_of_failed_tests += TestMatrixAssign<1,3>(); number_of_failed_tests += TestMatrixAssign<2,3>(); number_of_failed_tests += TestMatrixAssign<3,3>(); std::cout << number_of_failed_tests << "tests failed" << std::endl; return number_of_failed_tests; } <commit_msg>Adding IdentityMatrix test<commit_after>#include "amatrix.h" #include "checks.h" template <std::size_t TSize1, std::size_t TSize2> std::size_t TestZeroMatrixAssign() { AMatrix::Matrix<double, TSize1, TSize2> a_matrix; a_matrix = AMatrix::ZeroMatrix<double>(TSize1, TSize2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(a_matrix(i, j), 0.00); return 0; // not failed } template <std::size_t TSize> std::size_t TestIdentityMatrixAssign() { AMatrix::Matrix<double, TSize, TSize> a_matrix; a_matrix = AMatrix::IdentityMatrix<double>(TSize); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++){ if (i == j) { AMATRIX_CHECK_EQUAL(a_matrix(i, j), 1.00); } else { AMATRIX_CHECK_EQUAL(a_matrix(i, j), 0.00); } } return 0; // not failed } template <std::size_t TSize1, std::size_t TSize2> std::size_t TestMatrixAssign() { AMatrix::Matrix<double, TSize1, TSize2> a_matrix; AMatrix::Matrix<double, TSize1, TSize2> b_matrix; for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) a_matrix(i, j) = 2.33 * i - 4.52 * j; b_matrix = a_matrix; for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(b_matrix(i, j), 2.33 * i - 4.52 * j); return 0; // not failed } int main() { std::size_t number_of_failed_tests = 0; number_of_failed_tests += TestZeroMatrixAssign<1, 1>(); number_of_failed_tests += TestZeroMatrixAssign<1, 2>(); number_of_failed_tests += TestZeroMatrixAssign<2, 1>(); number_of_failed_tests += TestZeroMatrixAssign<2, 2>(); number_of_failed_tests += TestZeroMatrixAssign<3, 1>(); number_of_failed_tests += TestZeroMatrixAssign<3, 2>(); number_of_failed_tests += TestZeroMatrixAssign<3, 3>(); number_of_failed_tests += TestZeroMatrixAssign<1, 3>(); number_of_failed_tests += TestZeroMatrixAssign<2, 3>(); number_of_failed_tests += TestZeroMatrixAssign<3, 3>(); number_of_failed_tests += TestIdentityMatrixAssign<1>(); number_of_failed_tests += TestIdentityMatrixAssign<2>(); number_of_failed_tests += TestIdentityMatrixAssign<3>(); number_of_failed_tests += TestMatrixAssign<1, 1>(); number_of_failed_tests += TestMatrixAssign<1, 2>(); number_of_failed_tests += TestMatrixAssign<2, 1>(); number_of_failed_tests += TestMatrixAssign<2, 2>(); number_of_failed_tests += TestMatrixAssign<3, 1>(); number_of_failed_tests += TestMatrixAssign<3, 2>(); number_of_failed_tests += TestMatrixAssign<3, 3>(); number_of_failed_tests += TestMatrixAssign<1, 3>(); number_of_failed_tests += TestMatrixAssign<2, 3>(); number_of_failed_tests += TestMatrixAssign<3, 3>(); std::cout << number_of_failed_tests << "tests failed" << std::endl; return number_of_failed_tests; } <|endoftext|>
<commit_before>/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/policy.hpp" #include "libtorrent/hasher.hpp" #include "test.hpp" using namespace libtorrent; boost::uint32_t hash_buffer(char const* buf, int len) { hasher h; h.update(buf, len); sha1_hash digest = h.final(); boost::uint32_t ret; memcpy(&ret, &digest[0], 4); return ntohl(ret); } int test_main() { // when the IP is the same, we hash the ports, sorted boost::uint32_t p = peer_priority( tcp::endpoint(address::from_string("230.12.123.3"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4)); // when we're in the same /24, we just hash the IPs p = peer_priority( tcp::endpoint(address::from_string("230.12.123.1"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\xe6\x0c\x7b\x01\xe6\x0c\x7b\x03", 8)); // when we're in the same /16, we just hash the IPs masked by // 0xffffff55 p = peer_priority( tcp::endpoint(address::from_string("230.12.23.1"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\xe6\x0c\x17\x01\xe6\x0c\x7b\x01", 8)); // when we're in different /16, we just hash the IPs masked by // 0xffff5555 p = peer_priority( tcp::endpoint(address::from_string("230.120.23.1"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\xe6\x0c\x51\x01\xe6\x78\x15\x01", 8)); // IPv6 has a twice as wide mask, and we only care about the top 64 bits // when the IPs are the same, just hash the ports p = peer_priority( tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2) , tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x12c)); TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4)); // these IPs don't belong to the same /32, so apply the full mask // 0xffffffff55555555 p = peer_priority( tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2) , tcp::endpoint(address::from_string("ffff:0fff:ffff:ffff::1"), 0x12c)); TEST_EQUAL(p, hash_buffer( "\xff\xff\x0f\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01" "\xff\xff\xff\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01", 32)); return 0; } <commit_msg>fix test support for platforms not supporting IPv6<commit_after>/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/policy.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/broadcast_socket.hpp" // for supports_ipv6() #include "test.hpp" using namespace libtorrent; boost::uint32_t hash_buffer(char const* buf, int len) { hasher h; h.update(buf, len); sha1_hash digest = h.final(); boost::uint32_t ret; memcpy(&ret, &digest[0], 4); return ntohl(ret); } int test_main() { // when the IP is the same, we hash the ports, sorted boost::uint32_t p = peer_priority( tcp::endpoint(address::from_string("230.12.123.3"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4)); // when we're in the same /24, we just hash the IPs p = peer_priority( tcp::endpoint(address::from_string("230.12.123.1"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\xe6\x0c\x7b\x01\xe6\x0c\x7b\x03", 8)); // when we're in the same /16, we just hash the IPs masked by // 0xffffff55 p = peer_priority( tcp::endpoint(address::from_string("230.12.23.1"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\xe6\x0c\x17\x01\xe6\x0c\x7b\x01", 8)); // when we're in different /16, we just hash the IPs masked by // 0xffff5555 p = peer_priority( tcp::endpoint(address::from_string("230.120.23.1"), 0x4d2) , tcp::endpoint(address::from_string("230.12.123.3"), 0x12c)); TEST_EQUAL(p, hash_buffer("\xe6\x0c\x51\x01\xe6\x78\x15\x01", 8)); if (supports_ipv6()) { // IPv6 has a twice as wide mask, and we only care about the top 64 bits // when the IPs are the same, just hash the ports p = peer_priority( tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2) , tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x12c)); TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4)); // these IPs don't belong to the same /32, so apply the full mask // 0xffffffff55555555 p = peer_priority( tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2) , tcp::endpoint(address::from_string("ffff:0fff:ffff:ffff::1"), 0x12c)); TEST_EQUAL(p, hash_buffer( "\xff\xff\x0f\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01" "\xff\xff\xff\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01", 32)); } return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include "Stroika/Foundation/DataExchange/OptionsFile.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/ModuleGetterSetter.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/Time/Duration.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Time; namespace { struct OptionsData_ { bool fEnabled = false; optional<DateTime> fLastSynchronizedAt; }; /* * OptionsData_Storage_IMPL_ is a 'traits' object, defining a GET and SET method to save/restore * OptionsData_. * * This need not worry about thread safety: * o in the constructor because C++ guarantees this for statically constructed objects * o and in the Get/Set methods because ModuleGetterSetter manages this locking * * A user COULD either choose NOT to persist the data (in which case the logic with fOptionsFile_ * would be removed/unneeded). Or could perist another way. * * But this example shows using OptionsFile to persist the data to a local JSON file, using * the ObjectVariantMapper to serialize/deserialize C++ data structures. */ struct OptionsData_Storage_IMPL_ { OptionsData_Storage_IMPL_ () : fOptionsFile_{ /* * Any module name will do. This will map (by default) to a MyModule.json file in XXX. * If you require a single configuration file 'Main" might be a better module name. * But if you have multiple modules with configuration data, pick a name that matches that module, * and they will all be stored under a folder for all your apps configuration. */ L"MyModule"sv, /* * C++ doesn't have intrinsically enough metadata to effectively serialize deserialize data, but its close. * You have to give it class mappings, and other non-builtin types mappings, so that it can serialize. * * Note - this serializing logic is VERY widely useful outside of configuration - for example it can be used * to provide WebService/REST interfaces, or for debugging/logging output. */ []() -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddClass<OptionsData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{ {L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (OptionsData_, fEnabled)}, {L"Last-Synchronized-At", Stroika_Foundation_DataExchange_StructFieldMetaInfo (OptionsData_, fLastSynchronizedAt)}, }); return mapper; }(), /* * Hooks for versioning, to manage as your application evolves and the configuration data changes */ OptionsFile::kDefaultUpgrader, /* * Hook to decide the folder (and filename pattern) where the configuration data will be stored. * * This defaults to * FileSystem::WellKnownLocations::GetApplicationData () + appName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + suffix * or folder: * L"/var/opt/Put-Your-App-Name-Here" or "C:\ProgramData\Put-Your-App-Name-Here" * and this module configuration file would be: * L"/var/opt/Put-Your-App-Name-Here/MyModule.json" OR * L"C:/ProgramData/Put-Your-App-Name-Here/MyModule.json" OR * * \note - this function does NOT create the 'Put-Your-App-Name-Here' folder first, and will NOT persist * files if this folder does not exist. * * Callers can easily repalce the default function provided in OptionsFile::mkFilenameMapper - just * dont call that and provide your own lambda - to create the folder. * * But a better pattern is to create the folder in your application installer, typically. */ OptionsFile::mkFilenameMapper (L"Put-Your-App-Name-Here")} , fActualCurrentConfigData_ (fOptionsFile_.Read<OptionsData_> (OptionsData_{})) { Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date } OptionsData_ Get () const { // no locking required here for thread safety. // This is always done inside of a read or a full lock by ModuleGetterSetter return fActualCurrentConfigData_; } void Set (const OptionsData_& v) { // no locking required here for thread safety. // This is always done inside of a write lock by ModuleGetterSetter fActualCurrentConfigData_ = v; fOptionsFile_.Write (v); } private: OptionsFile fOptionsFile_; OptionsData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized }; } namespace { ModuleGetterSetter<OptionsData_, OptionsData_Storage_IMPL_> sModuleConfiguration_; WaitableEvent sWaitableEvent_; // some thread could be waiting on this, and perform some reactive task when the module settings change void TestUse1_ () { // This will be by far the most common use pattern - just read some field of the configuraiton object if (sModuleConfiguration_.Get ().fEnabled) { // do something } } void TestUse2_ () { // or read several fields all guaranteed within this same snapshot (not holding a lock duing the action) auto d = sModuleConfiguration_.Get (); // lock not held here so configuration could change but this code remains safe and crash free if (d.fEnabled and d.fLastSynchronizedAt) { // do something } } void TestUse3_ () { if (sModuleConfiguration_.Get ().fEnabled) { // a non-atomic update of the entire OptionsData_ object auto n = sModuleConfiguration_.Get (); n.fEnabled = false; // change something in 'n' here sModuleConfiguration_.Set (n); } } void TestUse4_ () { // Use Update () to atomically update data // Use the return value to tell if a real change was made (so you can invoke some sort of notication/action) static const Duration kMinTime_ = 2min; if (sModuleConfiguration_.Update ([](const OptionsData_& data) -> optional<OptionsData_> { if (data.fLastSynchronizedAt && *data.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { OptionsData_ result = data; result.fLastSynchronizedAt = DateTime::Now (); return result; } return {}; })) { sWaitableEvent_.Set (); // e.g. trigger someone to wakeup and used changes? - no global lock held here... } } } int main (int argc, const char* argv[]) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())}; TestUse1_ (); TestUse2_ (); TestUse3_ (); TestUse4_ (); return EXIT_SUCCESS; } <commit_msg>silence compiler warning<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include "Stroika/Foundation/DataExchange/OptionsFile.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/ModuleGetterSetter.h" #include "Stroika/Foundation/Execution/WaitableEvent.h" #include "Stroika/Foundation/Time/Duration.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Time; namespace { struct OptionsData_ { bool fEnabled = false; optional<DateTime> fLastSynchronizedAt; }; /* * OptionsData_Storage_IMPL_ is a 'traits' object, defining a GET and SET method to save/restore * OptionsData_. * * This need not worry about thread safety: * o in the constructor because C++ guarantees this for statically constructed objects * o and in the Get/Set methods because ModuleGetterSetter manages this locking * * A user COULD either choose NOT to persist the data (in which case the logic with fOptionsFile_ * would be removed/unneeded). Or could perist another way. * * But this example shows using OptionsFile to persist the data to a local JSON file, using * the ObjectVariantMapper to serialize/deserialize C++ data structures. */ struct OptionsData_Storage_IMPL_ { OptionsData_Storage_IMPL_ () : fOptionsFile_{ /* * Any module name will do. This will map (by default) to a MyModule.json file in XXX. * If you require a single configuration file 'Main" might be a better module name. * But if you have multiple modules with configuration data, pick a name that matches that module, * and they will all be stored under a folder for all your apps configuration. */ L"MyModule"sv, /* * C++ doesn't have intrinsically enough metadata to effectively serialize deserialize data, but its close. * You have to give it class mappings, and other non-builtin types mappings, so that it can serialize. * * Note - this serializing logic is VERY widely useful outside of configuration - for example it can be used * to provide WebService/REST interfaces, or for debugging/logging output. */ []() -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddClass<OptionsData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{ {L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (OptionsData_, fEnabled)}, {L"Last-Synchronized-At", Stroika_Foundation_DataExchange_StructFieldMetaInfo (OptionsData_, fLastSynchronizedAt)}, }); return mapper; }(), /* * Hooks for versioning, to manage as your application evolves and the configuration data changes */ OptionsFile::kDefaultUpgrader, /* * Hook to decide the folder (and filename pattern) where the configuration data will be stored. * * This defaults to * FileSystem::WellKnownLocations::GetApplicationData () + appName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + suffix * or folder: * L"/var/opt/Put-Your-App-Name-Here" or "C:\ProgramData\Put-Your-App-Name-Here" * and this module configuration file would be: * L"/var/opt/Put-Your-App-Name-Here/MyModule.json" OR * L"C:/ProgramData/Put-Your-App-Name-Here/MyModule.json" OR * * \note - this function does NOT create the 'Put-Your-App-Name-Here' folder first, and will NOT persist * files if this folder does not exist. * * Callers can easily repalce the default function provided in OptionsFile::mkFilenameMapper - just * dont call that and provide your own lambda - to create the folder. * * But a better pattern is to create the folder in your application installer, typically. */ OptionsFile::mkFilenameMapper (L"Put-Your-App-Name-Here")} , fActualCurrentConfigData_ (fOptionsFile_.Read<OptionsData_> (OptionsData_{})) { Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date } OptionsData_ Get () const { // no locking required here for thread safety. // This is always done inside of a read or a full lock by ModuleGetterSetter return fActualCurrentConfigData_; } void Set (const OptionsData_& v) { // no locking required here for thread safety. // This is always done inside of a write lock by ModuleGetterSetter fActualCurrentConfigData_ = v; fOptionsFile_.Write (v); } private: OptionsFile fOptionsFile_; OptionsData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized }; } namespace { ModuleGetterSetter<OptionsData_, OptionsData_Storage_IMPL_> sModuleConfiguration_; WaitableEvent sWaitableEvent_; // some thread could be waiting on this, and perform some reactive task when the module settings change void TestUse1_ () { // This will be by far the most common use pattern - just read some field of the configuraiton object if (sModuleConfiguration_.Get ().fEnabled) { // do something } } void TestUse2_ () { // or read several fields all guaranteed within this same snapshot (not holding a lock duing the action) auto d = sModuleConfiguration_.Get (); // lock not held here so configuration could change but this code remains safe and crash free if (d.fEnabled and d.fLastSynchronizedAt) { // do something } } void TestUse3_ () { if (sModuleConfiguration_.Get ().fEnabled) { // a non-atomic update of the entire OptionsData_ object auto n = sModuleConfiguration_.Get (); n.fEnabled = false; // change something in 'n' here sModuleConfiguration_.Set (n); } } void TestUse4_ () { // Use Update () to atomically update data // Use the return value to tell if a real change was made (so you can invoke some sort of notication/action) static const Duration kMinTime_ = 2min; if (sModuleConfiguration_.Update ([](const OptionsData_& data) -> optional<OptionsData_> { if (data.fLastSynchronizedAt && *data.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { OptionsData_ result = data; result.fLastSynchronizedAt = DateTime::Now (); return result; } return {}; })) { sWaitableEvent_.Set (); // e.g. trigger someone to wakeup and used changes? - no global lock held here... } } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())}; TestUse1_ (); TestUse2_ (); TestUse3_ (); TestUse4_ (); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "Particle.h" #include "EEPROM_ACCESS_PARTICLE/EEPROM_ACCESS_PARTICLE.h" SYSTEM_MODE(MANUAL); char s[35]; int i; void setup() { i = 0; EEPROM.put(0,0); Particle.connect(); } void loop() { if(i % 4 == 0) Particle.connect(); if(i % 5 == 0) Particle.disconnect(); sprintf(s, "%d - repeat",i); i++; store_str = String(s); if(Particle.connected()) { Particle.process(); } boolean sent = Particle.publish("main", store_str); delay(1000); if(Particle.connected()) processData(); if(!Particle.connected()) storeData(); } <commit_msg>Update test.cpp<commit_after>#include "Particle.h" SYSTEM_MODE(MANUAL); SYSTEM_THREAD(ENABLED); char toPublish_m[10]; String text = "- Value"; //text to accompany data String event = "e-test"; //name of event float num_m; //data variable void setup() { //startup delay and initialization delay(5000); EEPROM.put(0, NO_DATA_EEPROM); EEPROM.put(5,0); num_m = 0; WiFi.on(); //MANUAL requires code to turn WiFi module on Particle.connect(); //Establishes connection to cloud } void loop() { Particle.process(); //maintains connection with cloud, must be executed, at most, every 20s if(waitFor(Particle.connected, 10000)) //checks if device is connected to cloud { Particle.process(); sprintf(toPublish_m, "%f - Value", num_m); Serial.printf("%f - Main\r\n", num_m); Particle.publish("main", toPublish_m); delay(1000); process(text, event, FRONT_APPEND); //processes eeprom stored data. sends text that data is appended to and event name } if(!Particle.connected()) { Serial.printf("Enter store condition\r\n"); store(num_m); //stores data in eeprom } num_m++; } <|endoftext|>
<commit_before>#ifndef TIMEDISPLAY_H #define TIMEDISPLAY_H #include "TimeDisplay.h" #include "SecondsRing.h" #include <graphics.h> #include <gpio.h> #include <led-matrix.h> #include <threaded-canvas-manipulator.h> #include <ctime> using namespace rgb_matrix; using namespace uwhtimer; TimeDisplay::TimeDisplay(RGBMatrix *M, unsigned DisplayNum) : ThreadedCanvasManipulator(M) , M(M) , DisplayNum(DisplayNum) {} void TimeDisplay::Run() { Color Yellow(255, 255, 0); Color Green(0, 255, 0); Color Black(0, 0, 0); FrameCanvas *Frame = M->CreateFrameCanvas(); while (running()) { unsigned Now = time(nullptr); unsigned Secs = Now % 60; unsigned Tens = Secs / 10; unsigned Ones = Secs % 10; // Minutes BigNumber::RenderHalfSingle(Frame, DisplayNum, Tens, 1, 2, Green, &Black); BigNumber::RenderHalfSingle(Frame, DisplayNum, Ones, 15, 2, Green, &Black); // Seconds BigNumber::RenderQuarterSingle(Frame, DisplayNum, Tens, 8, 18, Green, &Black); BigNumber::RenderQuarterSingle(Frame, DisplayNum, Ones, 15, 18, Green, &Black); SecondsRing::Render(Frame, DisplayNum, Secs, Yellow, &Black); Frame = M->SwapOnVSync(Frame); } } #endif <commit_msg>Add colons to TimeDisplay<commit_after>#ifndef TIMEDISPLAY_H #define TIMEDISPLAY_H #include "TimeDisplay.h" #include "SecondsRing.h" #include <graphics.h> #include <gpio.h> #include <led-matrix.h> #include <threaded-canvas-manipulator.h> #include <ctime> using namespace rgb_matrix; using namespace uwhtimer; TimeDisplay::TimeDisplay(RGBMatrix *M, unsigned DisplayNum) : ThreadedCanvasManipulator(M) , M(M) , DisplayNum(DisplayNum) {} void TimeDisplay::Run() { Color Yellow(255, 255, 0); Color Green(0, 255, 0); Color Black(0, 0, 0); FrameCanvas *Frame = M->CreateFrameCanvas(); while (running()) { unsigned Now = time(nullptr); unsigned Secs = Now % 60; unsigned Tens = Secs / 10; unsigned Ones = Secs % 10; // Minutes BigNumber::RenderHalfSingle(Frame, DisplayNum, Tens, 1, 2, Green, &Black); BigNumber::RenderHalfSingle(Frame, DisplayNum, Ones, 15, 2, Green, &Black); // Seconds BigNumber::RenderQuarterSingle(Frame, DisplayNum, Tens, 8, 18, Green, &Black); BigNumber::RenderQuarterSingle(Frame, DisplayNum, Ones, 15, 18, Green, &Black); // Top Colon Frame->SetPixel(7, 20, Green.r, Green.g, Green.b); Frame->SetPixel(8, 20, Green.r, Green.g, Green.b); Frame->SetPixel(7, 21, Green.r, Green.g, Green.b); Frame->SetPixel(8, 21, Green.r, Green.g, Green.b); // Bottom Colon Frame->SetPixel(7, 23, Green.r, Green.g, Green.b); Frame->SetPixel(8, 23, Green.r, Green.g, Green.b); Frame->SetPixel(7, 24, Green.r, Green.g, Green.b); Frame->SetPixel(8, 24, Green.r, Green.g, Green.b); SecondsRing::Render(Frame, DisplayNum, Now, Yellow, &Black); Frame = M->SwapOnVSync(Frame); } } #endif <|endoftext|>
<commit_before>// RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s #include "test.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> // dup2(oldfd, newfd) races with read(newfd). // This is not reported as race because: // 1. Some software dups a closed pipe in place of a socket before closing // the socket (to prevent races actually). // 2. Some daemons dup /dev/null in place of stdin/stdout. int fd; void *Thread(void *x) { char buf; if (read(fd, &buf, 1) != 1) exit(printf("read failed\n")); return 0; } int main() { fd = open("/dev/random", O_RDONLY); int fd2 = open("/dev/random", O_RDONLY); if (fd == -1 || fd2 == -1) exit(printf("open failed\n")); pthread_t th; pthread_create(&th, 0, Thread, 0); if (dup2(fd2, fd) == -1) exit(printf("dup2 failed\n")); pthread_join(th, 0); if (close(fd) == -1) exit(printf("close failed\n")); if (close(fd2) == -1) exit(printf("close failed\n")); printf("DONE\n"); } // CHECK-NOT: WARNING: ThreadSanitizer: data race // CHECK: DONE <commit_msg>tsan: fix flaky test<commit_after>// RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s #include "test.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> // dup2(oldfd, newfd) races with read(newfd). // This is not reported as race because: // 1. Some software dups a closed pipe in place of a socket before closing // the socket (to prevent races actually). // 2. Some daemons dup /dev/null in place of stdin/stdout. int fd; void *Thread(void *x) { char buf; int n = read(fd, &buf, 1); if (n != 1) { // This read can "legitimately" fail regadless of the fact that glibc claims // that "there is no instant in the middle of calling dup2 at which new is // closed and not yet a duplicate of old". Strace of the failing runs // looks as follows: // // [pid 122196] open("/dev/urandom", O_RDONLY) = 3 // [pid 122196] open("/dev/urandom", O_RDONLY) = 4 // Process 122382 attached // [pid 122382] read(3, <unfinished ...> // [pid 122196] dup2(4, 3 <unfinished ...> // [pid 122382] <... read resumed> 0x7fcd139960b7, 1) = -1 EBADF (Bad file descriptor) // [pid 122196] <... dup2 resumed> ) = 3 // read failed: n=-1 errno=9 // // The failing read does not interfere with what this test tests, // so we just ignore the failure. // // exit(printf("read failed: n=%d errno=%d\n", n, errno)); } return 0; } int main() { fd = open("/dev/urandom", O_RDONLY); int fd2 = open("/dev/urandom", O_RDONLY); if (fd == -1 || fd2 == -1) exit(printf("open failed\n")); pthread_t th; pthread_create(&th, 0, Thread, 0); if (dup2(fd2, fd) == -1) exit(printf("dup2 failed\n")); pthread_join(th, 0); if (close(fd) == -1) exit(printf("close failed\n")); if (close(fd2) == -1) exit(printf("close failed\n")); printf("DONE\n"); } // CHECK-NOT: WARNING: ThreadSanitizer: data race // CHECK: DONE <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; namespace { class JITtedFunctionCollector : public llvm::JITEventListener { private: llvm::SmallVector<llvm::Function*, 24> m_functions; llvm::ExecutionEngine *m_engine; public: JITtedFunctionCollector(): m_functions(), m_engine(0) { } virtual ~JITtedFunctionCollector() { } virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t, const JITEventListener::EmittedFunctionDetails&) { m_functions.push_back(const_cast<llvm::Function *>(&F)); } virtual void NotifyFreeingMachineCode(void* /*OldPtr*/) {} void UnregisterFunctionMapping(llvm::ExecutionEngine&); }; } void JITtedFunctionCollector::UnregisterFunctionMapping( llvm::ExecutionEngine &engine) { for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator it = m_functions.rbegin(), et = m_functions.rend(); it != et; ++it) { llvm::Function *ff = *it; engine.freeMachineCodeForFunction(ff); engine.updateGlobalMapping(ff, 0); } m_functions.clear(); } std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; ExecutionContext::ExecutionContext(): m_engine(0), m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // // Note: Engine takes ownership of the module. assert(m && "Module cannot be null"); llvm::EngineBuilder builder(m); builder.setOptLevel(llvm::CodeGenOpt::Less); std::string errMsg; builder.setErrorStr(&errMsg); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); m_engine = builder.create(); assert(m_engine && "Cannot initialize builder without module!"); //m_engine->addModule(m); // Note: The engine takes ownership of the module. // install lazy function m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } ExecutionContext::~ExecutionContext() { } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol (should never happen)!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols m_unresolvedSymbols.insert(mangled_name); // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } void ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.data()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: could not find function named " << funcname << '\n'; return; } JITtedFunctionCollector listener; // register the listener m_engine->RegisterJITEventListener(&listener); m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol \'" << *i << "\' unresolved!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); m_engine->updateGlobalMapping(ff, 0); m_engine->freeMachineCodeForFunction(ff); } m_unresolvedSymbols.clear(); // cleanup functions listener.UnregisterFunctionMapping(*m_engine); m_engine->UnregisterJITEventListener(&listener); return; } // cleanup list and unregister our listener m_engine->UnregisterJITEventListener(&listener); std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().value); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } m_engine->freeMachineCodeForFunction(f); } void ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); if (!m_engine) InitializeBuilder(m); assert(m_engine && "Code generation did not create an engine!"); if (!m_RunningStaticInits) { m_RunningStaticInits = true; llvm::GlobalVariable* gctors = m->getGlobalVariable("llvm.global_ctors", true); if (gctors) { m_engine->runStaticConstructorsDestructors(false); gctors->eraseFromParent(); } m_RunningStaticInits = false; } } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::outs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); address = m_engine->getPointerToGlobal(gvar); } return address; } <commit_msg>Be more verbose about missing symbols.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; namespace { class JITtedFunctionCollector : public llvm::JITEventListener { private: llvm::SmallVector<llvm::Function*, 24> m_functions; llvm::ExecutionEngine *m_engine; public: JITtedFunctionCollector(): m_functions(), m_engine(0) { } virtual ~JITtedFunctionCollector() { } virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t, const JITEventListener::EmittedFunctionDetails&) { m_functions.push_back(const_cast<llvm::Function *>(&F)); } virtual void NotifyFreeingMachineCode(void* /*OldPtr*/) {} void UnregisterFunctionMapping(llvm::ExecutionEngine&); }; } void JITtedFunctionCollector::UnregisterFunctionMapping( llvm::ExecutionEngine &engine) { for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator it = m_functions.rbegin(), et = m_functions.rend(); it != et; ++it) { llvm::Function *ff = *it; engine.freeMachineCodeForFunction(ff); engine.updateGlobalMapping(ff, 0); } m_functions.clear(); } std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; ExecutionContext::ExecutionContext(): m_engine(0), m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // // Note: Engine takes ownership of the module. assert(m && "Module cannot be null"); llvm::EngineBuilder builder(m); builder.setOptLevel(llvm::CodeGenOpt::Less); std::string errMsg; builder.setErrorStr(&errMsg); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); m_engine = builder.create(); assert(m_engine && "Cannot initialize builder without module!"); //m_engine->addModule(m); // Note: The engine takes ownership of the module. // install lazy function m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } ExecutionContext::~ExecutionContext() { } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol (should never happen)!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } void ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.data()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: could not find function named " << funcname << '\n'; return; } JITtedFunctionCollector listener; // register the listener m_engine->RegisterJITEventListener(&listener); m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol \'" << *i << "\' unresolved!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); m_engine->updateGlobalMapping(ff, 0); m_engine->freeMachineCodeForFunction(ff); } m_unresolvedSymbols.clear(); // cleanup functions listener.UnregisterFunctionMapping(*m_engine); m_engine->UnregisterJITEventListener(&listener); return; } // cleanup list and unregister our listener m_engine->UnregisterJITEventListener(&listener); std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().value); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } m_engine->freeMachineCodeForFunction(f); } void ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); if (!m_engine) InitializeBuilder(m); assert(m_engine && "Code generation did not create an engine!"); if (!m_RunningStaticInits) { m_RunningStaticInits = true; llvm::GlobalVariable* gctors = m->getGlobalVariable("llvm.global_ctors", true); if (gctors) { m_engine->runStaticConstructorsDestructors(false); gctors->eraseFromParent(); } m_RunningStaticInits = false; } } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::outs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); address = m_engine->getPointerToGlobal(gvar); } return address; } <|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/dom_ui/shown_sections_handler.h" #include "base/file_path.h" #include "base/scoped_ptr.h" #include "chrome/browser/json_pref_store.h" #include "chrome/browser/pref_service.h" #include "chrome/common/pref_names.h" #include "testing/gtest/include/gtest/gtest.h" class ShownSectionsHandlerTest : public testing::Test { }; TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) { PrefService pref(new JsonPrefStore(FilePath())); // Set an *old* value pref.RegisterIntegerPref(prefs::kNTPShownSections, 0); pref.SetInteger(prefs::kNTPShownSections, THUMB); ShownSectionsHandler::MigrateUserPrefs(&pref, 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) { PrefService pref((FilePath())); // Set an *old* value pref.RegisterIntegerPref(prefs::kNTPShownSections, 0); pref.SetInteger(prefs::kNTPShownSections, LIST); ShownSectionsHandler::MigrateUserPrefs(&pref, 1, 2); int shown_sections = pref.GetInteger(prefs::kNTPShownSections); EXPECT_TRUE(shown_sections & THUMB); EXPECT_FALSE(shown_sections & LIST); } <commit_msg>Fix compile error in ShownSectionsHandlerTest.<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/dom_ui/shown_sections_handler.h" #include "base/file_path.h" #include "base/scoped_ptr.h" #include "chrome/browser/json_pref_store.h" #include "chrome/browser/pref_service.h" #include "chrome/common/pref_names.h" #include "testing/gtest/include/gtest/gtest.h" class ShownSectionsHandlerTest : public testing::Test { }; TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) { PrefService pref(new JsonPrefStore(FilePath())); // Set an *old* value pref.RegisterIntegerPref(prefs::kNTPShownSections, 0); pref.SetInteger(prefs::kNTPShownSections, THUMB); ShownSectionsHandler::MigrateUserPrefs(&pref, 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) { PrefService pref(new JsonPrefStore(FilePath())); // Set an *old* value pref.RegisterIntegerPref(prefs::kNTPShownSections, 0); pref.SetInteger(prefs::kNTPShownSections, LIST); ShownSectionsHandler::MigrateUserPrefs(&pref, 1, 2); int shown_sections = pref.GetInteger(prefs::kNTPShownSections); EXPECT_TRUE(shown_sections & THUMB); EXPECT_FALSE(shown_sections & LIST); } <|endoftext|>
<commit_before>// // EigenJS.cpp // ~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // 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 EIGENJS_COMPLEX_HPP #define EIGENJS_COMPLEX_HPP #include <node.h> #include <v8.h> #include <nan.h> #include <complex> #include <sstream> #define EIGENJS_COMPLEX_CLASS_METHOD( NAME ) \ static NAN_METHOD( NAME ) { \ NanScope(); \ \ if ( args.Length() == 1 && HasInstance(args[0]) ) { \ const Complex* obj = \ node::ObjectWrap::Unwrap<Complex>( args[0]->ToObject() ); \ \ const complex_type& NAME = std::NAME( obj->complex_ ); \ const element_type& real = NAME.real(); \ const element_type& imag = NAME.imag(); \ \ v8::Local<v8::Function> ctor = NanNew( constructor ); \ v8::Local<v8::Value> argv[] = { \ NanNew<v8::Number>( real ) \ , NanNew<v8::Number>( imag ) \ }; \ \ v8::Local<v8::Object> new_complex = ctor->NewInstance( \ sizeof( argv ) / sizeof( v8::Local<v8::Value> ) \ , argv \ ); \ \ NanReturnValue( new_complex ); \ } \ \ NanReturnUndefined(); \ } \ /**/ namespace EigenJS { template <typename ValueType> class Complex : public node::ObjectWrap { typedef ValueType element_type; typedef std::complex<element_type> complex_type; public: static void Init(v8::Handle<v8::Object> exports) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New); tpl->SetClassName(NanNew("Complex")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "abs", abs); NODE_SET_PROTOTYPE_METHOD(tpl, "arg", arg); NODE_SET_PROTOTYPE_METHOD(tpl, "norm", norm); NODE_SET_PROTOTYPE_METHOD(tpl, "conj", conj); NODE_SET_METHOD(tpl, "polar", polar); NODE_SET_METHOD(tpl, "proj", proj); NODE_SET_METHOD(tpl, "cos", cos); NODE_SET_METHOD(tpl, "cosh", cosh); NODE_SET_METHOD(tpl, "exp", exp); NODE_SET_METHOD(tpl, "log", log); NODE_SET_METHOD(tpl, "log10", log10); NODE_SET_METHOD(tpl, "pow", pow); NODE_SET_METHOD(tpl, "sin", sin); NODE_SET_METHOD(tpl, "sinh", sinh); NODE_SET_METHOD(tpl, "sqrt", sqrt); NODE_SET_METHOD(tpl, "tan", tan); NODE_SET_METHOD(tpl, "tanh", tanh); NODE_SET_METHOD(tpl, "acos", acos); NODE_SET_METHOD(tpl, "acosh", acosh); NODE_SET_METHOD(tpl, "asin", asin); NODE_SET_METHOD(tpl, "asinh", asinh); NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString); v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate(); proto->SetAccessor(NanNew("real"), get_real, set_real); proto->SetAccessor(NanNew("imag"), get_imag, set_imag); NanAssignPersistent(constructor, tpl->GetFunction()); exports->Set(NanNew("Complex"), tpl->GetFunction()); NanAssignPersistent(function_template, tpl); } static NAN_METHOD(abs) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::abs(obj->complex_))); } static NAN_METHOD(arg) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::arg(obj->complex_))); } static NAN_METHOD(norm) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::norm(obj->complex_))); } static NAN_METHOD(conj) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); const complex_type& c = std::conj(obj->complex_); const element_type& real = c.real(); const element_type& imag = c.imag(); NanScope(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(real) , NanNew<v8::Number>(imag) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } static NAN_METHOD(polar) { NanScope(); if (args.Length() == 2 && args[0]->IsNumber() && args[1]->IsNumber()) { const element_type& rho = args[0]->NumberValue(); const element_type& theta = args[1]->NumberValue(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(rho) , NanNew<v8::Number>(theta) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } NanReturnUndefined(); } EIGENJS_COMPLEX_CLASS_METHOD(proj) EIGENJS_COMPLEX_CLASS_METHOD(cos) EIGENJS_COMPLEX_CLASS_METHOD(cosh) EIGENJS_COMPLEX_CLASS_METHOD(exp) EIGENJS_COMPLEX_CLASS_METHOD(log) EIGENJS_COMPLEX_CLASS_METHOD(log10) EIGENJS_COMPLEX_CLASS_METHOD(sin) EIGENJS_COMPLEX_CLASS_METHOD(sinh) EIGENJS_COMPLEX_CLASS_METHOD(sqrt) EIGENJS_COMPLEX_CLASS_METHOD(tan) EIGENJS_COMPLEX_CLASS_METHOD(tanh) EIGENJS_COMPLEX_CLASS_METHOD(acos) EIGENJS_COMPLEX_CLASS_METHOD(acosh) EIGENJS_COMPLEX_CLASS_METHOD(asin) EIGENJS_COMPLEX_CLASS_METHOD(asinh) static NAN_METHOD(pow) { NanScope(); if (args.Length() == 2 && is_complex_or_saclar(args[0]) && is_complex_or_saclar(args[1])) { const bool& arg0_is_complex = is_complex(args[0]); const bool& arg1_is_complex = is_complex(args[1]); const bool& arg0_is_scalar = is_saclar(args[0]); const bool& arg1_is_scalar = is_saclar(args[1]); complex_type c; if (arg0_is_complex && arg1_is_complex) { const Complex* obj0 = node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject()); const Complex* obj1 = node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject()); c = std::pow(obj0->complex_, obj1->complex_); } else if (arg0_is_complex && arg1_is_scalar) { const Complex* obj0 = node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject()); const element_type& scalar1 = args[1]->NumberValue(); c = std::pow(obj0->complex_, scalar1); } else if (arg0_is_scalar && arg1_is_complex) { const element_type& scalar0 = args[0]->NumberValue(); const Complex* obj1 = node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject()); c = std::pow(scalar0, obj1->complex_); } else if (arg0_is_scalar && arg1_is_scalar) { const element_type& scalar0 = args[0]->NumberValue(); const element_type& scalar1 = args[1]->NumberValue(); c = std::pow(scalar0, scalar1); } v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(c.real()) , NanNew<v8::Number>(c.imag()) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } NanReturnUndefined(); } static NAN_METHOD(toString) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); std::ostringstream result; result << obj->complex_; NanReturnValue(NanNew(result.str().c_str())); NanReturnUndefined(); } static NAN_GETTER(get_real) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.real())); } static NAN_SETTER(set_real) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( value->NumberValue() , obj->complex_.imag() ); } } static NAN_GETTER(get_imag) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.imag())); } static NAN_SETTER(set_imag) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( obj->complex_.real() , value->NumberValue() ); } } private: Complex(const element_type& real, const element_type& imag) : complex_(real, imag) {} ~Complex() {} static NAN_METHOD(New) { NanScope(); if (args.Length() < 2) { NanThrowError("Tried creating complex without real and imag arguments"); NanReturnUndefined(); } if (args.IsConstructCall()) { const element_type& real = args[0]->NumberValue(); const element_type& imag = args[1]->NumberValue(); Complex* obj = new Complex(real, imag); obj->Wrap(args.This()); NanReturnValue(args.This()); } else { v8::Local<v8::Function> ctr = NanNew(constructor); v8::Local<v8::Value> argv[] = {args[0], args[1]}; NanReturnValue( ctr->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ) ); } } static bool HasInstance(const v8::Handle<v8::Value>& value) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template); return tpl->HasInstance(value); } private: static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; private: static bool is_complex(const v8::Handle<v8::Value>& arg) { return HasInstance(arg) ? true : false; } static bool is_saclar(const v8::Handle<v8::Value>& arg) { return arg->IsNumber() ? true : false; } static bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) { return HasInstance(arg) || arg->IsNumber() ? true : false; } private: complex_type complex_; }; template<typename ValueType> v8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template; template<typename ValueType> v8::Persistent<v8::Function> Complex<ValueType>::constructor; } // namespace EigenJS #undef EIGENJS_COMPLEX_CLASS_METHOD #endif // EIGENJS_COMPLEX_HPP <commit_msg>src: added class method 'Complex.atan()'<commit_after>// // EigenJS.cpp // ~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // 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 EIGENJS_COMPLEX_HPP #define EIGENJS_COMPLEX_HPP #include <node.h> #include <v8.h> #include <nan.h> #include <complex> #include <sstream> #define EIGENJS_COMPLEX_CLASS_METHOD( NAME ) \ static NAN_METHOD( NAME ) { \ NanScope(); \ \ if ( args.Length() == 1 && HasInstance(args[0]) ) { \ const Complex* obj = \ node::ObjectWrap::Unwrap<Complex>( args[0]->ToObject() ); \ \ const complex_type& NAME = std::NAME( obj->complex_ ); \ const element_type& real = NAME.real(); \ const element_type& imag = NAME.imag(); \ \ v8::Local<v8::Function> ctor = NanNew( constructor ); \ v8::Local<v8::Value> argv[] = { \ NanNew<v8::Number>( real ) \ , NanNew<v8::Number>( imag ) \ }; \ \ v8::Local<v8::Object> new_complex = ctor->NewInstance( \ sizeof( argv ) / sizeof( v8::Local<v8::Value> ) \ , argv \ ); \ \ NanReturnValue( new_complex ); \ } \ \ NanReturnUndefined(); \ } \ /**/ namespace EigenJS { template <typename ValueType> class Complex : public node::ObjectWrap { typedef ValueType element_type; typedef std::complex<element_type> complex_type; public: static void Init(v8::Handle<v8::Object> exports) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New); tpl->SetClassName(NanNew("Complex")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "abs", abs); NODE_SET_PROTOTYPE_METHOD(tpl, "arg", arg); NODE_SET_PROTOTYPE_METHOD(tpl, "norm", norm); NODE_SET_PROTOTYPE_METHOD(tpl, "conj", conj); NODE_SET_METHOD(tpl, "polar", polar); NODE_SET_METHOD(tpl, "proj", proj); NODE_SET_METHOD(tpl, "cos", cos); NODE_SET_METHOD(tpl, "cosh", cosh); NODE_SET_METHOD(tpl, "exp", exp); NODE_SET_METHOD(tpl, "log", log); NODE_SET_METHOD(tpl, "log10", log10); NODE_SET_METHOD(tpl, "pow", pow); NODE_SET_METHOD(tpl, "sin", sin); NODE_SET_METHOD(tpl, "sinh", sinh); NODE_SET_METHOD(tpl, "sqrt", sqrt); NODE_SET_METHOD(tpl, "tan", tan); NODE_SET_METHOD(tpl, "tanh", tanh); NODE_SET_METHOD(tpl, "acos", acos); NODE_SET_METHOD(tpl, "acosh", acosh); NODE_SET_METHOD(tpl, "asin", asin); NODE_SET_METHOD(tpl, "asinh", asinh); NODE_SET_METHOD(tpl, "atan", atan); NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString); v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate(); proto->SetAccessor(NanNew("real"), get_real, set_real); proto->SetAccessor(NanNew("imag"), get_imag, set_imag); NanAssignPersistent(constructor, tpl->GetFunction()); exports->Set(NanNew("Complex"), tpl->GetFunction()); NanAssignPersistent(function_template, tpl); } static NAN_METHOD(abs) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::abs(obj->complex_))); } static NAN_METHOD(arg) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::arg(obj->complex_))); } static NAN_METHOD(norm) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::norm(obj->complex_))); } static NAN_METHOD(conj) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); const complex_type& c = std::conj(obj->complex_); const element_type& real = c.real(); const element_type& imag = c.imag(); NanScope(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(real) , NanNew<v8::Number>(imag) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } static NAN_METHOD(polar) { NanScope(); if (args.Length() == 2 && args[0]->IsNumber() && args[1]->IsNumber()) { const element_type& rho = args[0]->NumberValue(); const element_type& theta = args[1]->NumberValue(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(rho) , NanNew<v8::Number>(theta) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } NanReturnUndefined(); } EIGENJS_COMPLEX_CLASS_METHOD(proj) EIGENJS_COMPLEX_CLASS_METHOD(cos) EIGENJS_COMPLEX_CLASS_METHOD(cosh) EIGENJS_COMPLEX_CLASS_METHOD(exp) EIGENJS_COMPLEX_CLASS_METHOD(log) EIGENJS_COMPLEX_CLASS_METHOD(log10) EIGENJS_COMPLEX_CLASS_METHOD(sin) EIGENJS_COMPLEX_CLASS_METHOD(sinh) EIGENJS_COMPLEX_CLASS_METHOD(sqrt) EIGENJS_COMPLEX_CLASS_METHOD(tan) EIGENJS_COMPLEX_CLASS_METHOD(tanh) EIGENJS_COMPLEX_CLASS_METHOD(acos) EIGENJS_COMPLEX_CLASS_METHOD(acosh) EIGENJS_COMPLEX_CLASS_METHOD(asin) EIGENJS_COMPLEX_CLASS_METHOD(asinh) EIGENJS_COMPLEX_CLASS_METHOD(atan) static NAN_METHOD(pow) { NanScope(); if (args.Length() == 2 && is_complex_or_saclar(args[0]) && is_complex_or_saclar(args[1])) { const bool& arg0_is_complex = is_complex(args[0]); const bool& arg1_is_complex = is_complex(args[1]); const bool& arg0_is_scalar = is_saclar(args[0]); const bool& arg1_is_scalar = is_saclar(args[1]); complex_type c; if (arg0_is_complex && arg1_is_complex) { const Complex* obj0 = node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject()); const Complex* obj1 = node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject()); c = std::pow(obj0->complex_, obj1->complex_); } else if (arg0_is_complex && arg1_is_scalar) { const Complex* obj0 = node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject()); const element_type& scalar1 = args[1]->NumberValue(); c = std::pow(obj0->complex_, scalar1); } else if (arg0_is_scalar && arg1_is_complex) { const element_type& scalar0 = args[0]->NumberValue(); const Complex* obj1 = node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject()); c = std::pow(scalar0, obj1->complex_); } else if (arg0_is_scalar && arg1_is_scalar) { const element_type& scalar0 = args[0]->NumberValue(); const element_type& scalar1 = args[1]->NumberValue(); c = std::pow(scalar0, scalar1); } v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(c.real()) , NanNew<v8::Number>(c.imag()) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } NanReturnUndefined(); } static NAN_METHOD(toString) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); std::ostringstream result; result << obj->complex_; NanReturnValue(NanNew(result.str().c_str())); NanReturnUndefined(); } static NAN_GETTER(get_real) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.real())); } static NAN_SETTER(set_real) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( value->NumberValue() , obj->complex_.imag() ); } } static NAN_GETTER(get_imag) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.imag())); } static NAN_SETTER(set_imag) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( obj->complex_.real() , value->NumberValue() ); } } private: Complex(const element_type& real, const element_type& imag) : complex_(real, imag) {} ~Complex() {} static NAN_METHOD(New) { NanScope(); if (args.Length() < 2) { NanThrowError("Tried creating complex without real and imag arguments"); NanReturnUndefined(); } if (args.IsConstructCall()) { const element_type& real = args[0]->NumberValue(); const element_type& imag = args[1]->NumberValue(); Complex* obj = new Complex(real, imag); obj->Wrap(args.This()); NanReturnValue(args.This()); } else { v8::Local<v8::Function> ctr = NanNew(constructor); v8::Local<v8::Value> argv[] = {args[0], args[1]}; NanReturnValue( ctr->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ) ); } } static bool HasInstance(const v8::Handle<v8::Value>& value) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template); return tpl->HasInstance(value); } private: static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; private: static bool is_complex(const v8::Handle<v8::Value>& arg) { return HasInstance(arg) ? true : false; } static bool is_saclar(const v8::Handle<v8::Value>& arg) { return arg->IsNumber() ? true : false; } static bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) { return HasInstance(arg) || arg->IsNumber() ? true : false; } private: complex_type complex_; }; template<typename ValueType> v8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template; template<typename ValueType> v8::Persistent<v8::Function> Complex<ValueType>::constructor; } // namespace EigenJS #undef EIGENJS_COMPLEX_CLASS_METHOD #endif // EIGENJS_COMPLEX_HPP <|endoftext|>
<commit_before>#include "swift/IDE/CodeCompletion.h" #include "swift/AST/NameLookup.h" #include "swift/Basic/LLVM.h" #include "swift/ClangImporter/ClangImporter.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Subsystems.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "clang/Sema/Lookup.h" #include <algorithm> #include <string> using namespace swift; using namespace code_completion; std::string swift::code_completion::removeCodeCompletionTokens( StringRef Input, StringRef TokenName, unsigned *CompletionOffset) { assert(TokenName.size() >= 1); *CompletionOffset = ~0U; std::string CleanFile; CleanFile.reserve(Input.size()); const std::string Token = std::string("#^") + TokenName.str() + "^#"; for (const char *Ptr = Input.begin(), *End = Input.end(); Ptr != End; ++Ptr) { const char C = *Ptr; if (C == '#' && Ptr <= End - Token.size() && StringRef(Ptr, Token.size()) == Token) { Ptr += Token.size() - 1; *CompletionOffset = CleanFile.size() + 1; continue; } if (C == '#' && Ptr <= End - 2 && Ptr[1] == '^') { do { Ptr++; } while(*Ptr != '#'); continue; } CleanFile += C; } return CleanFile; } CodeCompletionString::CodeCompletionString(ArrayRef<Chunk> Chunks) { Chunk *TailChunks = reinterpret_cast<Chunk *>(this + 1); std::copy(Chunks.begin(), Chunks.end(), TailChunks); NumChunks = Chunks.size(); } void CodeCompletionString::print(raw_ostream &OS) const { unsigned PrevNestingLevel = 0; for (auto C : getChunks()) { if (C.getNestingLevel() < PrevNestingLevel) { OS << "#}"; } switch (C.getKind()) { case Chunk::ChunkKind::Text: case Chunk::ChunkKind::LeftParen: case Chunk::ChunkKind::RightParen: case Chunk::ChunkKind::LeftBracket: case Chunk::ChunkKind::RightBracket: case Chunk::ChunkKind::Dot: case Chunk::ChunkKind::Comma: case Chunk::ChunkKind::CallParameterName: case Chunk::ChunkKind::CallParameterColon: case Chunk::ChunkKind::CallParameterType: OS << C.getText(); break; case Chunk::ChunkKind::OptionalBegin: case Chunk::ChunkKind::CallParameterBegin: OS << "{#"; break; case Chunk::ChunkKind::TypeAnnotation: OS << "[#"; OS << C.getText(); OS << "#]"; } PrevNestingLevel = C.getNestingLevel(); } while (PrevNestingLevel > 0) { OS << "#}"; PrevNestingLevel--; } } void CodeCompletionString::dump() const { print(llvm::outs()); } void CodeCompletionResult::print(raw_ostream &OS) const { switch (Kind) { case ResultKind::SwiftDeclaration: OS << "SwiftDecl: "; break; case ResultKind::ClangDeclaration: OS << "ClangDecl: "; break; case ResultKind::Keyword: OS << "Keyword: "; break; case ResultKind::Pattern: OS << "Pattern: "; break; } CompletionString->print(OS); } void CodeCompletionResult::dump() const { print(llvm::outs()); } void CodeCompletionResultBuilder::addChunkWithText( CodeCompletionString::Chunk::ChunkKind Kind, StringRef Text) { Chunks.push_back(CodeCompletionString::Chunk::createWithText( Kind, CurrentNestingLevel, Context.copyString(Text))); } CodeCompletionResult *CodeCompletionResultBuilder::takeResult() { void *Mem = Context.Allocator .Allocate(sizeof(CodeCompletionResult) + Chunks.size() * sizeof(CodeCompletionString::Chunk), llvm::alignOf<CodeCompletionString>()); switch (Kind) { case CodeCompletionResult::ResultKind::SwiftDeclaration: return new (Context.Allocator) CodeCompletionResult(new (Mem) CodeCompletionString(Chunks), AssociatedDecl.get<const Decl *>()); case CodeCompletionResult::ResultKind::ClangDeclaration: return new (Context.Allocator) CodeCompletionResult(new (Mem) CodeCompletionString(Chunks), AssociatedDecl.get<const clang::Decl *>()); case CodeCompletionResult::ResultKind::Keyword: case CodeCompletionResult::ResultKind::Pattern: return new (Context.Allocator) CodeCompletionResult(Kind, new (Mem) CodeCompletionString(Chunks)); } } void CodeCompletionResultBuilder::finishResult() { Context.CurrentCompletionResults.push_back(takeResult()); } StringRef CodeCompletionContext::copyString(StringRef String) { char *Mem = Allocator.Allocate<char>(String.size()); std::copy(String.begin(), String.end(), Mem); return StringRef(Mem, String.size()); } ArrayRef<CodeCompletionResult *> CodeCompletionContext::takeResults() { const size_t Count = CurrentCompletionResults.size(); CodeCompletionResult **Results = Allocator.Allocate<CodeCompletionResult *>(Count); std::copy(CurrentCompletionResults.begin(), CurrentCompletionResults.end(), Results); CurrentCompletionResults.clear(); return llvm::makeArrayRef(Results, Count); } namespace { class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; TranslationUnit *const TU; void typecheckExpr(Expr *&E) { assert(E && "should have an expression"); DEBUG(llvm::dbgs() << "\nparsed:\n"; E->print(llvm::dbgs()); llvm::dbgs() << "\n"); if (!typeCheckCompletionContextExpr(TU, E)) return; DEBUG(llvm::dbgs() << "\type checked:\n"; E->print(llvm::dbgs()); llvm::dbgs() << "\n"); } public: CodeCompletionCallbacksImpl(Parser &P, CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CodeCompletionCallbacks(P), CompletionContext(CompletionContext), Consumer(Consumer), TU(P.TU) { } void completeExpr() override; void completeDotExpr(Expr *E) override; void completePostfixExpr(Expr *E) override; }; } // end unnamed namespace void CodeCompletionCallbacksImpl::completeExpr() { Parser::ParserPositionRAII RestorePosition(P); P.restoreParserPosition(ExprBeginPosition); // FIXME: implement fallback code completion. Consumer.handleResults(CompletionContext.takeResults()); } namespace { /// Build completions by doing visible decl lookup from a context. class CompletionLookup : swift::VisibleDeclConsumer, clang::VisibleDeclConsumer { CodeCompletionContext &CompletionContext; ASTContext &SwiftContext; enum class LookupKind { ValueExpr, DeclContext }; LookupKind Kind; Type ExprType; bool HaveDot = false; public: CompletionLookup(CodeCompletionContext &CompletionContext, ASTContext &SwiftContext) : CompletionContext(CompletionContext), SwiftContext(SwiftContext) { } void setHaveDot() { HaveDot = true; } void addSwiftVarDeclRef(const VarDecl *VD) { StringRef Name = VD->getName().get(); assert(!Name.empty() && "name should not be empty"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(VD); if (!HaveDot) Builder.addDot(); Builder.addTextChunk(Name); Builder.addTypeAnnotation(VD->getType().getString()); } void addTuplePatternParameters(CodeCompletionResultBuilder &Builder, const TuplePattern *TP) { bool NeedComma = false; for (auto TupleElt : TP->getFields()) { if (NeedComma) Builder.addComma(", "); Builder.addCallParameter(TupleElt.getPattern()->getBoundName().str(), TupleElt.getPattern()->getType().getString()); NeedComma = true; } } void addSwiftMethodCall(const FuncDecl *FD) { StringRef Name = FD->getName().get(); assert(!Name.empty() && "name should not be empty"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(FD); if (!HaveDot) Builder.addDot(); Builder.addTextChunk(Name); Builder.addLeftParen(); auto *FE = FD->getBody(); auto Patterns = FE->getArgParamPatterns(); unsigned FirstIndex = 0; if (Patterns[0]->isImplicit()) FirstIndex = 1; addTuplePatternParameters(Builder, cast<TuplePattern>(Patterns[FirstIndex])); Builder.addRightParen(); // FIXME: Pattern should pretty-print itself. llvm::SmallString<32> Type; for (unsigned i = FirstIndex + 1, e = Patterns.size(); i != e; ++i) { Type += "("; for (auto TupleElt : cast<TuplePattern>(Patterns[i])->getFields()) { Type += TupleElt.getPattern()->getBoundName().str(); Type += ": "; Type += TupleElt.getPattern()->getType().getString(); } Type += ") -> "; } Type += FE->getResultType(SwiftContext).getString(); Builder.addTypeAnnotation(Type); // TODO: skip arguments with default parameters? } void addSwiftConstructorCall(const ConstructorDecl *CD) { assert(!HaveDot && "can not add a constructor call after a dot"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(CD); Builder.addLeftParen(); addTuplePatternParameters(Builder, cast<TuplePattern>(CD->getArguments())); Builder.addRightParen(); Builder.addTypeAnnotation(CD->getResultType().getString()); } void addSwiftSubscriptCall(const SubscriptDecl *SD) { assert(!HaveDot && "can not add a subscript after a dot"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(SD); Builder.addLeftBracket(); addTuplePatternParameters(Builder, cast<TuplePattern>(SD->getIndices())); Builder.addRightBracket(); Builder.addTypeAnnotation(SD->getElementType().getString()); } void addClangDecl(const clang::NamedDecl *ND) { // FIXME: Eventually, we'll import the Clang Decl and format it as a Swift // declaration. Right now we don't do this because of performance reasons. StringRef Name = ND->getName(); if (Name.empty()) return; CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::ClangDeclaration); Builder.setAssociatedClangDecl(ND); Builder.addTextChunk(Name); } void addKeyword(StringRef Name) { CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::Keyword); if (!HaveDot) Builder.addDot(); Builder.addTextChunk(Name); } // Implement swift::VisibleDeclConsumer void foundDecl(ValueDecl *D) override { if (Kind == LookupKind::ValueExpr) { if (auto *VD = dyn_cast<VarDecl>(D)) { // Swift does not have class variables. // FIXME: add code completion results when class variables are added. if (ExprType->is<MetaTypeType>()) return; addSwiftVarDeclRef(VD); return; } if (auto *FD = dyn_cast<FuncDecl>(D)) { // We can not call getters or setters. We use VarDecls and // SubscriptDecls to produce completions that refer to getters and // setters. if (FD->isGetterOrSetter()) return; // Don't complete class methods of instances; don't complete instance // methods of metatypes. if (FD->isStatic() != ExprType->is<MetaTypeType>()) return; addSwiftMethodCall(FD); return; } if (HaveDot) return; // FIXME: super.constructor if (auto *CD = dyn_cast<ConstructorDecl>(D)) { if (!ExprType->is<MetaTypeType>()) return; addSwiftConstructorCall(CD); return; } if (auto *SD = dyn_cast<SubscriptDecl>(D)) { if (ExprType->is<MetaTypeType>()) return; addSwiftSubscriptCall(SD); return; } } } // Implement clang::VisibleDeclConsumer void FoundDecl(clang::NamedDecl *ND, clang::NamedDecl *Hiding, clang::DeclContext *Ctx, bool InBaseClass) override { addClangDecl(ND); } void getValueExprCompletions(Type ExprType) { Kind = LookupKind::ValueExpr; this->ExprType = ExprType; if (ExprType->is<AnyFunctionType>()) { // FIXME: produce a call. } else { lookupVisibleDecls(*this, ExprType); } // Add the special qualified keyword 'metatype' so that, for example, // 'Int.metatype' can be completed. addKeyword("metatype"); } void getCompletionsInDeclContext(DeclContext *DC, SourceLoc Loc) { Kind = LookupKind::DeclContext; lookupVisibleDecls(*this, DC, Loc); if (auto Importer = SwiftContext.getClangModuleLoader()) static_cast<ClangImporter&>(*Importer).lookupVisibleDecls(*this); } }; } // end unnamed namespace void CodeCompletionCallbacksImpl::completeDotExpr(Expr *E) { typecheckExpr(E); CompletionLookup Lookup(CompletionContext, TU->Ctx); Lookup.setHaveDot(); Lookup.getValueExprCompletions(E->getType()); Consumer.handleResults(CompletionContext.takeResults()); } void CodeCompletionCallbacksImpl::completePostfixExpr(Expr *E) { typecheckExpr(E); CompletionLookup Lookup(CompletionContext, TU->Ctx); Lookup.getValueExprCompletions(E->getType()); Consumer.handleResults(CompletionContext.takeResults()); } void PrintingCodeCompletionConsumer::handleResults( ArrayRef<CodeCompletionResult *> Results) { OS << "Begin completions\n"; for (auto Result : Results) { Result->print(OS); OS << "\n"; } OS << "End completions\n"; } namespace { class CodeCompletionCallbacksFactoryImpl : public CodeCompletionCallbacksFactory { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; public: CodeCompletionCallbacksFactoryImpl(CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CompletionContext(CompletionContext), Consumer(Consumer) {} CodeCompletionCallbacks *createCodeCompletionCallbacks(Parser &P) override { return new CodeCompletionCallbacksImpl(P, CompletionContext, Consumer); } }; } // end unnamed namespace CodeCompletionCallbacksFactory * swift::code_completion::makeCodeCompletionCallbacksFactory( CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) { return new CodeCompletionCallbacksFactoryImpl(CompletionContext, Consumer); } <commit_msg>dump() output should go to errs(). Thanks, Jordan!<commit_after>#include "swift/IDE/CodeCompletion.h" #include "swift/AST/NameLookup.h" #include "swift/Basic/LLVM.h" #include "swift/ClangImporter/ClangImporter.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Subsystems.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "clang/Sema/Lookup.h" #include <algorithm> #include <string> using namespace swift; using namespace code_completion; std::string swift::code_completion::removeCodeCompletionTokens( StringRef Input, StringRef TokenName, unsigned *CompletionOffset) { assert(TokenName.size() >= 1); *CompletionOffset = ~0U; std::string CleanFile; CleanFile.reserve(Input.size()); const std::string Token = std::string("#^") + TokenName.str() + "^#"; for (const char *Ptr = Input.begin(), *End = Input.end(); Ptr != End; ++Ptr) { const char C = *Ptr; if (C == '#' && Ptr <= End - Token.size() && StringRef(Ptr, Token.size()) == Token) { Ptr += Token.size() - 1; *CompletionOffset = CleanFile.size() + 1; continue; } if (C == '#' && Ptr <= End - 2 && Ptr[1] == '^') { do { Ptr++; } while(*Ptr != '#'); continue; } CleanFile += C; } return CleanFile; } CodeCompletionString::CodeCompletionString(ArrayRef<Chunk> Chunks) { Chunk *TailChunks = reinterpret_cast<Chunk *>(this + 1); std::copy(Chunks.begin(), Chunks.end(), TailChunks); NumChunks = Chunks.size(); } void CodeCompletionString::print(raw_ostream &OS) const { unsigned PrevNestingLevel = 0; for (auto C : getChunks()) { if (C.getNestingLevel() < PrevNestingLevel) { OS << "#}"; } switch (C.getKind()) { case Chunk::ChunkKind::Text: case Chunk::ChunkKind::LeftParen: case Chunk::ChunkKind::RightParen: case Chunk::ChunkKind::LeftBracket: case Chunk::ChunkKind::RightBracket: case Chunk::ChunkKind::Dot: case Chunk::ChunkKind::Comma: case Chunk::ChunkKind::CallParameterName: case Chunk::ChunkKind::CallParameterColon: case Chunk::ChunkKind::CallParameterType: OS << C.getText(); break; case Chunk::ChunkKind::OptionalBegin: case Chunk::ChunkKind::CallParameterBegin: OS << "{#"; break; case Chunk::ChunkKind::TypeAnnotation: OS << "[#"; OS << C.getText(); OS << "#]"; } PrevNestingLevel = C.getNestingLevel(); } while (PrevNestingLevel > 0) { OS << "#}"; PrevNestingLevel--; } } void CodeCompletionString::dump() const { print(llvm::errs()); } void CodeCompletionResult::print(raw_ostream &OS) const { switch (Kind) { case ResultKind::SwiftDeclaration: OS << "SwiftDecl: "; break; case ResultKind::ClangDeclaration: OS << "ClangDecl: "; break; case ResultKind::Keyword: OS << "Keyword: "; break; case ResultKind::Pattern: OS << "Pattern: "; break; } CompletionString->print(OS); } void CodeCompletionResult::dump() const { print(llvm::errs()); } void CodeCompletionResultBuilder::addChunkWithText( CodeCompletionString::Chunk::ChunkKind Kind, StringRef Text) { Chunks.push_back(CodeCompletionString::Chunk::createWithText( Kind, CurrentNestingLevel, Context.copyString(Text))); } CodeCompletionResult *CodeCompletionResultBuilder::takeResult() { void *Mem = Context.Allocator .Allocate(sizeof(CodeCompletionResult) + Chunks.size() * sizeof(CodeCompletionString::Chunk), llvm::alignOf<CodeCompletionString>()); switch (Kind) { case CodeCompletionResult::ResultKind::SwiftDeclaration: return new (Context.Allocator) CodeCompletionResult(new (Mem) CodeCompletionString(Chunks), AssociatedDecl.get<const Decl *>()); case CodeCompletionResult::ResultKind::ClangDeclaration: return new (Context.Allocator) CodeCompletionResult(new (Mem) CodeCompletionString(Chunks), AssociatedDecl.get<const clang::Decl *>()); case CodeCompletionResult::ResultKind::Keyword: case CodeCompletionResult::ResultKind::Pattern: return new (Context.Allocator) CodeCompletionResult(Kind, new (Mem) CodeCompletionString(Chunks)); } } void CodeCompletionResultBuilder::finishResult() { Context.CurrentCompletionResults.push_back(takeResult()); } StringRef CodeCompletionContext::copyString(StringRef String) { char *Mem = Allocator.Allocate<char>(String.size()); std::copy(String.begin(), String.end(), Mem); return StringRef(Mem, String.size()); } ArrayRef<CodeCompletionResult *> CodeCompletionContext::takeResults() { const size_t Count = CurrentCompletionResults.size(); CodeCompletionResult **Results = Allocator.Allocate<CodeCompletionResult *>(Count); std::copy(CurrentCompletionResults.begin(), CurrentCompletionResults.end(), Results); CurrentCompletionResults.clear(); return llvm::makeArrayRef(Results, Count); } namespace { class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; TranslationUnit *const TU; void typecheckExpr(Expr *&E) { assert(E && "should have an expression"); DEBUG(llvm::dbgs() << "\nparsed:\n"; E->print(llvm::dbgs()); llvm::dbgs() << "\n"); if (!typeCheckCompletionContextExpr(TU, E)) return; DEBUG(llvm::dbgs() << "\type checked:\n"; E->print(llvm::dbgs()); llvm::dbgs() << "\n"); } public: CodeCompletionCallbacksImpl(Parser &P, CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CodeCompletionCallbacks(P), CompletionContext(CompletionContext), Consumer(Consumer), TU(P.TU) { } void completeExpr() override; void completeDotExpr(Expr *E) override; void completePostfixExpr(Expr *E) override; }; } // end unnamed namespace void CodeCompletionCallbacksImpl::completeExpr() { Parser::ParserPositionRAII RestorePosition(P); P.restoreParserPosition(ExprBeginPosition); // FIXME: implement fallback code completion. Consumer.handleResults(CompletionContext.takeResults()); } namespace { /// Build completions by doing visible decl lookup from a context. class CompletionLookup : swift::VisibleDeclConsumer, clang::VisibleDeclConsumer { CodeCompletionContext &CompletionContext; ASTContext &SwiftContext; enum class LookupKind { ValueExpr, DeclContext }; LookupKind Kind; Type ExprType; bool HaveDot = false; public: CompletionLookup(CodeCompletionContext &CompletionContext, ASTContext &SwiftContext) : CompletionContext(CompletionContext), SwiftContext(SwiftContext) { } void setHaveDot() { HaveDot = true; } void addSwiftVarDeclRef(const VarDecl *VD) { StringRef Name = VD->getName().get(); assert(!Name.empty() && "name should not be empty"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(VD); if (!HaveDot) Builder.addDot(); Builder.addTextChunk(Name); Builder.addTypeAnnotation(VD->getType().getString()); } void addTuplePatternParameters(CodeCompletionResultBuilder &Builder, const TuplePattern *TP) { bool NeedComma = false; for (auto TupleElt : TP->getFields()) { if (NeedComma) Builder.addComma(", "); Builder.addCallParameter(TupleElt.getPattern()->getBoundName().str(), TupleElt.getPattern()->getType().getString()); NeedComma = true; } } void addSwiftMethodCall(const FuncDecl *FD) { StringRef Name = FD->getName().get(); assert(!Name.empty() && "name should not be empty"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(FD); if (!HaveDot) Builder.addDot(); Builder.addTextChunk(Name); Builder.addLeftParen(); auto *FE = FD->getBody(); auto Patterns = FE->getArgParamPatterns(); unsigned FirstIndex = 0; if (Patterns[0]->isImplicit()) FirstIndex = 1; addTuplePatternParameters(Builder, cast<TuplePattern>(Patterns[FirstIndex])); Builder.addRightParen(); // FIXME: Pattern should pretty-print itself. llvm::SmallString<32> Type; for (unsigned i = FirstIndex + 1, e = Patterns.size(); i != e; ++i) { Type += "("; for (auto TupleElt : cast<TuplePattern>(Patterns[i])->getFields()) { Type += TupleElt.getPattern()->getBoundName().str(); Type += ": "; Type += TupleElt.getPattern()->getType().getString(); } Type += ") -> "; } Type += FE->getResultType(SwiftContext).getString(); Builder.addTypeAnnotation(Type); // TODO: skip arguments with default parameters? } void addSwiftConstructorCall(const ConstructorDecl *CD) { assert(!HaveDot && "can not add a constructor call after a dot"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(CD); Builder.addLeftParen(); addTuplePatternParameters(Builder, cast<TuplePattern>(CD->getArguments())); Builder.addRightParen(); Builder.addTypeAnnotation(CD->getResultType().getString()); } void addSwiftSubscriptCall(const SubscriptDecl *SD) { assert(!HaveDot && "can not add a subscript after a dot"); CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::SwiftDeclaration); Builder.setAssociatedSwiftDecl(SD); Builder.addLeftBracket(); addTuplePatternParameters(Builder, cast<TuplePattern>(SD->getIndices())); Builder.addRightBracket(); Builder.addTypeAnnotation(SD->getElementType().getString()); } void addClangDecl(const clang::NamedDecl *ND) { // FIXME: Eventually, we'll import the Clang Decl and format it as a Swift // declaration. Right now we don't do this because of performance reasons. StringRef Name = ND->getName(); if (Name.empty()) return; CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::ClangDeclaration); Builder.setAssociatedClangDecl(ND); Builder.addTextChunk(Name); } void addKeyword(StringRef Name) { CodeCompletionResultBuilder Builder( CompletionContext, CodeCompletionResult::ResultKind::Keyword); if (!HaveDot) Builder.addDot(); Builder.addTextChunk(Name); } // Implement swift::VisibleDeclConsumer void foundDecl(ValueDecl *D) override { if (Kind == LookupKind::ValueExpr) { if (auto *VD = dyn_cast<VarDecl>(D)) { // Swift does not have class variables. // FIXME: add code completion results when class variables are added. if (ExprType->is<MetaTypeType>()) return; addSwiftVarDeclRef(VD); return; } if (auto *FD = dyn_cast<FuncDecl>(D)) { // We can not call getters or setters. We use VarDecls and // SubscriptDecls to produce completions that refer to getters and // setters. if (FD->isGetterOrSetter()) return; // Don't complete class methods of instances; don't complete instance // methods of metatypes. if (FD->isStatic() != ExprType->is<MetaTypeType>()) return; addSwiftMethodCall(FD); return; } if (HaveDot) return; // FIXME: super.constructor if (auto *CD = dyn_cast<ConstructorDecl>(D)) { if (!ExprType->is<MetaTypeType>()) return; addSwiftConstructorCall(CD); return; } if (auto *SD = dyn_cast<SubscriptDecl>(D)) { if (ExprType->is<MetaTypeType>()) return; addSwiftSubscriptCall(SD); return; } } } // Implement clang::VisibleDeclConsumer void FoundDecl(clang::NamedDecl *ND, clang::NamedDecl *Hiding, clang::DeclContext *Ctx, bool InBaseClass) override { addClangDecl(ND); } void getValueExprCompletions(Type ExprType) { Kind = LookupKind::ValueExpr; this->ExprType = ExprType; if (ExprType->is<AnyFunctionType>()) { // FIXME: produce a call. } else { lookupVisibleDecls(*this, ExprType); } // Add the special qualified keyword 'metatype' so that, for example, // 'Int.metatype' can be completed. addKeyword("metatype"); } void getCompletionsInDeclContext(DeclContext *DC, SourceLoc Loc) { Kind = LookupKind::DeclContext; lookupVisibleDecls(*this, DC, Loc); if (auto Importer = SwiftContext.getClangModuleLoader()) static_cast<ClangImporter&>(*Importer).lookupVisibleDecls(*this); } }; } // end unnamed namespace void CodeCompletionCallbacksImpl::completeDotExpr(Expr *E) { typecheckExpr(E); CompletionLookup Lookup(CompletionContext, TU->Ctx); Lookup.setHaveDot(); Lookup.getValueExprCompletions(E->getType()); Consumer.handleResults(CompletionContext.takeResults()); } void CodeCompletionCallbacksImpl::completePostfixExpr(Expr *E) { typecheckExpr(E); CompletionLookup Lookup(CompletionContext, TU->Ctx); Lookup.getValueExprCompletions(E->getType()); Consumer.handleResults(CompletionContext.takeResults()); } void PrintingCodeCompletionConsumer::handleResults( ArrayRef<CodeCompletionResult *> Results) { OS << "Begin completions\n"; for (auto Result : Results) { Result->print(OS); OS << "\n"; } OS << "End completions\n"; } namespace { class CodeCompletionCallbacksFactoryImpl : public CodeCompletionCallbacksFactory { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; public: CodeCompletionCallbacksFactoryImpl(CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CompletionContext(CompletionContext), Consumer(Consumer) {} CodeCompletionCallbacks *createCodeCompletionCallbacks(Parser &P) override { return new CodeCompletionCallbacksImpl(P, CompletionContext, Consumer); } }; } // end unnamed namespace CodeCompletionCallbacksFactory * swift::code_completion::makeCodeCompletionCallbacksFactory( CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) { return new CodeCompletionCallbacksFactoryImpl(CompletionContext, Consumer); } <|endoftext|>
<commit_before>#include "Content.h" #include "ContentGraphicsItem.h" #include "main.h" #include "TextureContent.h" #include "DynamicTextureContent.h" #include "MovieContent.h" Content::Content(std::string uri) { uri_ = uri; // default position / size x_ = y_ = 0.; w_ = h_ = 0.25; // default to centered centerX_ = 0.5; centerY_ = 0.5; // default to no zoom zoom_ = 1.; } boost::shared_ptr<DisplayGroup> Content::getDisplayGroup() { return displayGroup_.lock(); } void Content::setDisplayGroup(boost::shared_ptr<DisplayGroup> displayGroup) { displayGroup_ = displayGroup; } std::string Content::getURI() { return uri_; } void Content::setCoordinates(double x, double y, double w, double h, bool setGraphicsItem) { x_ = x; y_ = y; w_ = w; h_ = h; if(setGraphicsItem == true) { if(graphicsItem_ != NULL) { graphicsItem_->setRect(x_, y_, w_, h_); } } // force synchronization g_displayGroup->sendDisplayGroup(); } void Content::getCoordinates(double &x, double &y, double &w, double &h) { x = x_; y = y_; w = w_; h = h_; } void Content::setCenterCoordinates(double centerX, double centerY) { centerX_ = centerX; centerY_ = centerY; // force synchronization g_displayGroup->sendDisplayGroup(); } void Content::getCenterCoordinates(double &centerX, double &centerY) { centerX = centerX_; centerY = centerY_; } void Content::setZoom(double zoom) { zoom_ = zoom; // force synchronization g_displayGroup->sendDisplayGroup(); } double Content::getZoom() { return zoom_; } boost::shared_ptr<ContentGraphicsItem> Content::getGraphicsItem() { if(graphicsItem_ == NULL) { boost::shared_ptr<ContentGraphicsItem> gi(new ContentGraphicsItem(shared_from_this())); graphicsItem_ = gi; } return graphicsItem_; } void Content::render() { // calculate texture coordinates float tX = centerX_ - 0.5 / zoom_; float tY = centerY_ - 0.5 / zoom_; float tW = 1./zoom_; float tH = 1./zoom_; // transform to a normalize coordinate system so the content can be rendered at (x,y,w,h) = (0,0,1,1) glPushMatrix(); glTranslatef(x_, y_, 0.); glScalef(w_, h_, 1.); // render the factory object renderFactoryObject(tX, tY, tW, tH); glPopMatrix(); // render the border double horizontalBorder = 20. / (double)g_configuration->getTotalHeight(); // 20 pixels double verticalBorder = (double)g_configuration->getTotalHeight() / (double)g_configuration->getTotalWidth() * horizontalBorder; glPushAttrib(GL_CURRENT_BIT); glColor4f(1,1,1,1); GLWindow::drawRectangle(x_-verticalBorder,y_-horizontalBorder,w_+2.*verticalBorder,h_+2.*horizontalBorder); glPopAttrib(); } boost::shared_ptr<Content> Content::getContent(std::string uri) { // see if this is an image QImageReader imageReader(uri.c_str()); if(imageReader.canRead() == true) { // get its size QSize size = imageReader.size(); // small images will use Texture; larger images will use DynamicTexture boost::shared_ptr<Content> c; if(size.width() <= 4096 && size.height() <= 4096) { boost::shared_ptr<Content> temp(new TextureContent(uri)); c = temp; } else { boost::shared_ptr<Content> temp(new DynamicTextureContent(uri)); c = temp; } return c; } // see if this is a movie // todo: need a better way to determine file type else if(QString::fromStdString(uri).endsWith(".mov") || QString::fromStdString(uri).endsWith(".avi") || QString::fromStdString(uri).endsWith(".mp4") || QString::fromStdString(uri).endsWith(".mkv")) { boost::shared_ptr<Content> c(new MovieContent(uri)); return c; } // see if this is an image pyramid else if(QString::fromStdString(uri).endsWith(".pyr")) { boost::shared_ptr<Content> c(new DynamicTextureContent(uri)); return c; } // otherwise, return NULL return boost::shared_ptr<Content>(); } <commit_msg>reduced Content window border size to 5 pixels on the tiled display.<commit_after>#include "Content.h" #include "ContentGraphicsItem.h" #include "main.h" #include "TextureContent.h" #include "DynamicTextureContent.h" #include "MovieContent.h" Content::Content(std::string uri) { uri_ = uri; // default position / size x_ = y_ = 0.; w_ = h_ = 0.25; // default to centered centerX_ = 0.5; centerY_ = 0.5; // default to no zoom zoom_ = 1.; } boost::shared_ptr<DisplayGroup> Content::getDisplayGroup() { return displayGroup_.lock(); } void Content::setDisplayGroup(boost::shared_ptr<DisplayGroup> displayGroup) { displayGroup_ = displayGroup; } std::string Content::getURI() { return uri_; } void Content::setCoordinates(double x, double y, double w, double h, bool setGraphicsItem) { x_ = x; y_ = y; w_ = w; h_ = h; if(setGraphicsItem == true) { if(graphicsItem_ != NULL) { graphicsItem_->setRect(x_, y_, w_, h_); } } // force synchronization g_displayGroup->sendDisplayGroup(); } void Content::getCoordinates(double &x, double &y, double &w, double &h) { x = x_; y = y_; w = w_; h = h_; } void Content::setCenterCoordinates(double centerX, double centerY) { centerX_ = centerX; centerY_ = centerY; // force synchronization g_displayGroup->sendDisplayGroup(); } void Content::getCenterCoordinates(double &centerX, double &centerY) { centerX = centerX_; centerY = centerY_; } void Content::setZoom(double zoom) { zoom_ = zoom; // force synchronization g_displayGroup->sendDisplayGroup(); } double Content::getZoom() { return zoom_; } boost::shared_ptr<ContentGraphicsItem> Content::getGraphicsItem() { if(graphicsItem_ == NULL) { boost::shared_ptr<ContentGraphicsItem> gi(new ContentGraphicsItem(shared_from_this())); graphicsItem_ = gi; } return graphicsItem_; } void Content::render() { // calculate texture coordinates float tX = centerX_ - 0.5 / zoom_; float tY = centerY_ - 0.5 / zoom_; float tW = 1./zoom_; float tH = 1./zoom_; // transform to a normalize coordinate system so the content can be rendered at (x,y,w,h) = (0,0,1,1) glPushMatrix(); glTranslatef(x_, y_, 0.); glScalef(w_, h_, 1.); // render the factory object renderFactoryObject(tX, tY, tW, tH); glPopMatrix(); // render the border double horizontalBorder = 5. / (double)g_configuration->getTotalHeight(); // 5 pixels double verticalBorder = (double)g_configuration->getTotalHeight() / (double)g_configuration->getTotalWidth() * horizontalBorder; glPushAttrib(GL_CURRENT_BIT); glColor4f(1,1,1,1); GLWindow::drawRectangle(x_-verticalBorder,y_-horizontalBorder,w_+2.*verticalBorder,h_+2.*horizontalBorder); glPopAttrib(); } boost::shared_ptr<Content> Content::getContent(std::string uri) { // see if this is an image QImageReader imageReader(uri.c_str()); if(imageReader.canRead() == true) { // get its size QSize size = imageReader.size(); // small images will use Texture; larger images will use DynamicTexture boost::shared_ptr<Content> c; if(size.width() <= 4096 && size.height() <= 4096) { boost::shared_ptr<Content> temp(new TextureContent(uri)); c = temp; } else { boost::shared_ptr<Content> temp(new DynamicTextureContent(uri)); c = temp; } return c; } // see if this is a movie // todo: need a better way to determine file type else if(QString::fromStdString(uri).endsWith(".mov") || QString::fromStdString(uri).endsWith(".avi") || QString::fromStdString(uri).endsWith(".mp4") || QString::fromStdString(uri).endsWith(".mkv")) { boost::shared_ptr<Content> c(new MovieContent(uri)); return c; } // see if this is an image pyramid else if(QString::fromStdString(uri).endsWith(".pyr")) { boost::shared_ptr<Content> c(new DynamicTextureContent(uri)); return c; } // otherwise, return NULL return boost::shared_ptr<Content>(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_harness.h" #include "chrome/browser/sync/protocol/sync_protocol_error.h" #include "chrome/browser/sync/test/integration/bookmarks_helper.h" #include "chrome/browser/sync/test/integration/passwords_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/common/net/gaia/google_service_auth_error.h" using bookmarks_helper::AddFolder; using bookmarks_helper::SetTitle; using passwords_helper::AddLogin; using passwords_helper::CreateTestPasswordForm; using passwords_helper::GetPasswordCount; using passwords_helper::GetPasswordStore; using passwords_helper::GetVerifierPasswordCount; using passwords_helper::GetVerifierPasswordStore; using passwords_helper::ProfileContainsSamePasswordFormsAsVerifier; using webkit::forms::PasswordForm; class SyncErrorTest : public SyncTest{ public: SyncErrorTest() : SyncTest(SINGLE_CLIENT) {} virtual ~SyncErrorTest() {} private: DISALLOW_COPY_AND_ASSIGN(SyncErrorTest); }; IN_PROC_BROWSER_TEST_F(SyncErrorTest, BirthdayErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change.")); TriggerBirthdayError(); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE(GetClient(0)->AwaitSyncDisabled("Birthday error.")); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, TransientErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change.")); TriggerTransientError(); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE( GetClient(0)->AwaitExponentialBackoffVerification()); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, ActionableErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync.")); browser_sync::SyncProtocolError protocol_error; protocol_error.error_type = browser_sync::TRANSIENT_ERROR; protocol_error.action = browser_sync::UPGRADE_CLIENT; protocol_error.error_description = "Not My Fault"; protocol_error.url = "www.google.com"; TriggerSyncError(protocol_error); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE( GetClient(0)->AwaitActionableError()); ProfileSyncService::Status status = GetClient(0)->GetStatus(); ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type); ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action); ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url); ASSERT_EQ(status.sync_protocol_error.error_description, protocol_error.error_description); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, BirthdayErrorUsingActionableErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync.")); browser_sync::SyncProtocolError protocol_error; protocol_error.error_type = browser_sync::NOT_MY_BIRTHDAY; protocol_error.action = browser_sync::DISABLE_SYNC_ON_CLIENT; protocol_error.error_description = "Not My Fault"; protocol_error.url = "www.google.com"; TriggerSyncError(protocol_error); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE( GetClient(0)->AwaitSyncDisabled("Birthday Error.")); ProfileSyncService::Status status = GetClient(0)->GetStatus(); ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type); ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action); ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url); ASSERT_EQ(status.sync_protocol_error.error_description, protocol_error.error_description); } // TODO(rsimha): Enable after fixing crbug.com/107611. IN_PROC_BROWSER_TEST_F(SyncErrorTest, DISABLED_AuthErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; PasswordForm form0 = CreateTestPasswordForm(0); AddLogin(GetVerifierPasswordStore(), form0); ASSERT_EQ(1, GetVerifierPasswordCount()); AddLogin(GetPasswordStore(0), form0); ASSERT_EQ(1, GetPasswordCount(0)); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Added a login.")); ASSERT_TRUE(ProfileContainsSamePasswordFormsAsVerifier(0)); ASSERT_EQ(1, GetPasswordCount(0)); TriggerAuthError(); PasswordForm form1 = CreateTestPasswordForm(1); AddLogin(GetPasswordStore(0), form1); ASSERT_FALSE(GetClient(0)->AwaitFullSyncCompletion("Must get auth error.")); ASSERT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS, GetClient(0)->service()->GetAuthError().state()); ASSERT_EQ(ProfileSyncService::Status::OFFLINE_UNSYNCED, GetClient(0)->GetStatus().summary); } <commit_msg>Fix AuthErrorTest for Mac<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_harness.h" #include "chrome/browser/sync/protocol/sync_protocol_error.h" #include "chrome/browser/sync/test/integration/bookmarks_helper.h" #include "chrome/browser/sync/test/integration/passwords_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/common/net/gaia/google_service_auth_error.h" using bookmarks_helper::AddFolder; using bookmarks_helper::SetTitle; class SyncErrorTest : public SyncTest{ public: SyncErrorTest() : SyncTest(SINGLE_CLIENT) {} virtual ~SyncErrorTest() {} private: DISALLOW_COPY_AND_ASSIGN(SyncErrorTest); }; IN_PROC_BROWSER_TEST_F(SyncErrorTest, BirthdayErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change.")); TriggerBirthdayError(); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE(GetClient(0)->AwaitSyncDisabled("Birthday error.")); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, TransientErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Offline state change.")); TriggerTransientError(); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE( GetClient(0)->AwaitExponentialBackoffVerification()); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, ActionableErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync.")); browser_sync::SyncProtocolError protocol_error; protocol_error.error_type = browser_sync::TRANSIENT_ERROR; protocol_error.action = browser_sync::UPGRADE_CLIENT; protocol_error.error_description = "Not My Fault"; protocol_error.url = "www.google.com"; TriggerSyncError(protocol_error); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE( GetClient(0)->AwaitActionableError()); ProfileSyncService::Status status = GetClient(0)->GetStatus(); ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type); ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action); ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url); ASSERT_EQ(status.sync_protocol_error.error_description, protocol_error.error_description); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, BirthdayErrorUsingActionableErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync.")); browser_sync::SyncProtocolError protocol_error; protocol_error.error_type = browser_sync::NOT_MY_BIRTHDAY; protocol_error.action = browser_sync::DISABLE_SYNC_ON_CLIENT; protocol_error.error_description = "Not My Fault"; protocol_error.url = "www.google.com"; TriggerSyncError(protocol_error); // Now make one more change so we will do another sync. const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_TRUE( GetClient(0)->AwaitSyncDisabled("Birthday Error.")); ProfileSyncService::Status status = GetClient(0)->GetStatus(); ASSERT_EQ(status.sync_protocol_error.error_type, protocol_error.error_type); ASSERT_EQ(status.sync_protocol_error.action, protocol_error.action); ASSERT_EQ(status.sync_protocol_error.url, protocol_error.url); ASSERT_EQ(status.sync_protocol_error.error_description, protocol_error.error_description); } IN_PROC_BROWSER_TEST_F(SyncErrorTest, AuthErrorTest) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const BookmarkNode* node1 = AddFolder(0, 0, L"title1"); SetTitle(0, node1, L"new_title1"); ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Sync.")); TriggerAuthError(); const BookmarkNode* node2 = AddFolder(0, 0, L"title2"); SetTitle(0, node2, L"new_title2"); ASSERT_FALSE(GetClient(0)->AwaitFullSyncCompletion("Must get auth error.")); ASSERT_EQ(GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS, GetClient(0)->service()->GetAuthError().state()); ASSERT_EQ(ProfileSyncService::Status::OFFLINE_UNSYNCED, GetClient(0)->GetStatus().summary); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <platform/dirutils.h> #include "callbacks.h" #include "common.h" #include "compress.h" #include "kvstore.h" extern "C" { static rel_time_t basic_current_time(void) { return 0; } rel_time_t (*ep_current_time)() = basic_current_time; time_t ep_real_time() { return time(NULL); } } class WriteCallback : public Callback<mutation_result> { public: WriteCallback() {} void callback(mutation_result &result) { } }; class StatsCallback : public Callback<kvstats_ctx> { public: StatsCallback() {} void callback(kvstats_ctx &result) { } }; class CacheCallback : public Callback<CacheLookup> { public: CacheCallback(int64_t s, int64_t e, uint16_t vbid) : start(s), end(e), vb(vbid) { } void callback(CacheLookup &lookup) { cb_assert(lookup.getVBucketId() == vb); cb_assert(start <= lookup.getBySeqno()); cb_assert(lookup.getBySeqno() <= end); } private: int64_t start; int64_t end; uint16_t vb; }; class GetCallback : public Callback<GetValue> { public: GetCallback() : expectCompressed(false) { } GetCallback(bool expect_compressed) : expectCompressed(expect_compressed) { } void callback(GetValue &result) { if (expectCompressed) { cb_assert(result.getValue()->getDataType() == PROTOCOL_BINARY_DATATYPE_COMPRESSED); snap_buf output; cb_assert(doSnappyUncompress(result.getValue()->getData(), result.getValue()->getNBytes(), output) == SNAP_SUCCESS); cb_assert(strncmp("value", output.buf.get(), output.len) == 0); } else { cb_assert(strncmp("value", result.getValue()->getData(), result.getValue()->getNBytes()) == 0); } delete result.getValue(); } private: bool expectCompressed; }; void basic_kvstore_test(std::string& backend) { std::string data_dir("/tmp/kvstore-test"); CouchbaseDirectoryUtilities::rmrf(data_dir.c_str()); KVStoreConfig config(1024, 4, data_dir, backend, 0); KVStore* kvstore = KVStoreFactory::create(config); StatsCallback sc; std::string failoverLog(""); vbucket_state state(vbucket_state_active, 0, 0, 0, 0, 0, 0, 0, 0, failoverLog); kvstore->snapshotVBucket(0, state, &sc); kvstore->begin(); Item item("key", 3, 0, 0, "value", 5); WriteCallback wc; kvstore->set(item, wc); kvstore->commit(&sc); GetCallback gc; kvstore->get("key", 0, gc); delete kvstore; } void kvstore_get_compressed_test(std::string& backend) { std::string data_dir("/tmp/kvstore-test"); CouchbaseDirectoryUtilities::rmrf(data_dir.c_str()); KVStoreConfig config(1024, 4, data_dir, backend, 0); KVStore* kvstore = KVStoreFactory::create(config); StatsCallback sc; std::string failoverLog(""); vbucket_state state(vbucket_state_active, 0, 0, 0, 0, 0, 0, 0, 0, failoverLog); kvstore->snapshotVBucket(0, state, &sc); kvstore->begin(); uint8_t datatype = PROTOCOL_BINARY_RAW_BYTES; for (int i = 1; i <= 5; i++) { std::string key("key" + std::to_string(i)); Item item(key.c_str(), key.length(), 0, 0, "value", 5, &datatype, 1, 0, i); WriteCallback wc; kvstore->set(item, wc); } kvstore->commit(&sc); shared_ptr<Callback<GetValue> > cb(new GetCallback(true)); shared_ptr<Callback<CacheLookup> > cl(new CacheCallback(1, 5, 0)); ScanContext* scanCtx; scanCtx = kvstore->initScanContext(cb, cl, 0, 1, DocumentFilter::ALL_ITEMS, ValueFilter::VALUES_COMPRESSED); cb_assert(scanCtx); cb_assert(kvstore->scan(scanCtx) == scan_success); delete kvstore; } int main(int argc, char **argv) { (void)argc; (void)argv; putenv(strdup("ALLOW_NO_STATS_UPDATE=yeah")); std::string backend("couchdb"); basic_kvstore_test(backend); kvstore_get_compressed_test(backend); backend = "forestdb"; basic_kvstore_test(backend); } <commit_msg>Addressing an issue where callback reference goes out of context<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <platform/dirutils.h> #include "callbacks.h" #include "common.h" #include "compress.h" #include "kvstore.h" extern "C" { static rel_time_t basic_current_time(void) { return 0; } rel_time_t (*ep_current_time)() = basic_current_time; time_t ep_real_time() { return time(NULL); } } class WriteCallback : public Callback<mutation_result> { public: WriteCallback() {} void callback(mutation_result &result) { } }; class StatsCallback : public Callback<kvstats_ctx> { public: StatsCallback() {} void callback(kvstats_ctx &result) { } }; class CacheCallback : public Callback<CacheLookup> { public: CacheCallback(int64_t s, int64_t e, uint16_t vbid) : start(s), end(e), vb(vbid) { } void callback(CacheLookup &lookup) { cb_assert(lookup.getVBucketId() == vb); cb_assert(start <= lookup.getBySeqno()); cb_assert(lookup.getBySeqno() <= end); } private: int64_t start; int64_t end; uint16_t vb; }; class GetCallback : public Callback<GetValue> { public: GetCallback() : expectCompressed(false) { } GetCallback(bool expect_compressed) : expectCompressed(expect_compressed) { } void callback(GetValue &result) { if (expectCompressed) { cb_assert(result.getValue()->getDataType() == PROTOCOL_BINARY_DATATYPE_COMPRESSED); snap_buf output; cb_assert(doSnappyUncompress(result.getValue()->getData(), result.getValue()->getNBytes(), output) == SNAP_SUCCESS); cb_assert(strncmp("value", output.buf.get(), output.len) == 0); } else { cb_assert(strncmp("value", result.getValue()->getData(), result.getValue()->getNBytes()) == 0); } delete result.getValue(); } private: bool expectCompressed; }; void basic_kvstore_test(std::string& backend) { std::string data_dir("/tmp/kvstore-test"); CouchbaseDirectoryUtilities::rmrf(data_dir.c_str()); KVStoreConfig config(1024, 4, data_dir, backend, 0); KVStore* kvstore = KVStoreFactory::create(config); StatsCallback sc; std::string failoverLog(""); vbucket_state state(vbucket_state_active, 0, 0, 0, 0, 0, 0, 0, 0, failoverLog); kvstore->snapshotVBucket(0, state, &sc); kvstore->begin(); Item item("key", 3, 0, 0, "value", 5); WriteCallback wc; kvstore->set(item, wc); kvstore->commit(&sc); GetCallback gc; kvstore->get("key", 0, gc); delete kvstore; } void kvstore_get_compressed_test(std::string& backend) { std::string data_dir("/tmp/kvstore-test"); CouchbaseDirectoryUtilities::rmrf(data_dir.c_str()); KVStoreConfig config(1024, 4, data_dir, backend, 0); KVStore* kvstore = KVStoreFactory::create(config); StatsCallback sc; std::string failoverLog(""); vbucket_state state(vbucket_state_active, 0, 0, 0, 0, 0, 0, 0, 0, failoverLog); kvstore->snapshotVBucket(0, state, &sc); kvstore->begin(); uint8_t datatype = PROTOCOL_BINARY_RAW_BYTES; WriteCallback wc; for (int i = 1; i <= 5; i++) { std::string key("key" + std::to_string(i)); Item item(key.c_str(), key.length(), 0, 0, "value", 5, &datatype, 1, 0, i); kvstore->set(item, wc); } kvstore->commit(&sc); shared_ptr<Callback<GetValue> > cb(new GetCallback(true)); shared_ptr<Callback<CacheLookup> > cl(new CacheCallback(1, 5, 0)); ScanContext* scanCtx; scanCtx = kvstore->initScanContext(cb, cl, 0, 1, DocumentFilter::ALL_ITEMS, ValueFilter::VALUES_COMPRESSED); cb_assert(scanCtx); cb_assert(kvstore->scan(scanCtx) == scan_success); delete kvstore; } int main(int argc, char **argv) { (void)argc; (void)argv; putenv(strdup("ALLOW_NO_STATS_UPDATE=yeah")); std::string backend("couchdb"); basic_kvstore_test(backend); kvstore_get_compressed_test(backend); backend = "forestdb"; basic_kvstore_test(backend); } <|endoftext|>
<commit_before>//===--- AccessMarkerElimination.cpp - Eliminate access markers. ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This pass eliminates the instructions that demarcate memory access regions. /// If no memory access markers exist, then the pass does nothing. Otherwise, it /// unconditionally eliminates all non-dynamic markers (plus any dynamic markers /// if dynamic exclusivity checking is disabled). /// /// This is an always-on pass for temporary bootstrapping. It allows running /// test cases through the pipeline and exercising SIL verification before all /// passes support access markers. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "access-marker-elim" #include "swift/Basic/Range.h" #include "swift/SIL/SILFunction.h" #include "swift/SILOptimizer/PassManager/Transforms.h" using namespace swift; namespace { struct AccessMarkerElimination : SILModuleTransform { void run() override { // Don't bother doing anything unless some kind of exclusivity // enforcement is enabled. auto &M = *getModule(); bool removedAny = false; for (auto &F : M) { // Iterating in reverse eliminates more begin_access users before they // need to be replaced. for (auto &BB : reversed(F)) { // Don't cache the begin iterator since we're reverse iterating. for (auto II = BB.end(); II != BB.begin();) { SILInstruction *inst = &*(--II); if (auto beginAccess = dyn_cast<BeginAccessInst>(inst)) { // Leave dynamic accesses in place, but delete all others. if (beginAccess->getEnforcement() == SILAccessEnforcement::Dynamic && M.getOptions().EnforceExclusivityDynamic) continue; // Handle all the uses: while (!beginAccess->use_empty()) { Operand *op = *beginAccess->use_begin(); // Delete any associated end_access instructions. if (auto endAccess = dyn_cast<EndAccessInst>(op->getUser())) { assert(endAccess->use_empty() && "found use of end_access"); endAccess->eraseFromParent(); // Forward all other uses to the original address. } else { op->set(beginAccess->getSource()); } } II = BB.erase(beginAccess); removedAny = true; continue; } // end_access instructions will be handled when we process the // begin_access. } } // Don't invalidate any analyses if we didn't do anything. if (!removedAny) continue; auto InvalidKind = SILAnalysis::InvalidationKind::Instructions; invalidateAnalysis(&F, InvalidKind); } } }; } // end anonymous namespace SILTransform *swift::createAccessMarkerElimination() { return new AccessMarkerElimination(); } <commit_msg>[Exclusivity] Eliminate unpaired access instructions before optimization.<commit_after>//===--- AccessMarkerElimination.cpp - Eliminate access markers. ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This pass eliminates the instructions that demarcate memory access regions. /// If no memory access markers exist, then the pass does nothing. Otherwise, it /// unconditionally eliminates all non-dynamic markers (plus any dynamic markers /// if dynamic exclusivity checking is disabled). /// /// This is an always-on pass for temporary bootstrapping. It allows running /// test cases through the pipeline and exercising SIL verification before all /// passes support access markers. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "access-marker-elim" #include "swift/Basic/Range.h" #include "swift/SIL/SILFunction.h" #include "swift/SILOptimizer/PassManager/Transforms.h" using namespace swift; namespace { struct AccessMarkerElimination : SILModuleTransform { void replaceBeginAccessUsers(BeginAccessInst *beginAccess) { // Handle all the uses: while (!beginAccess->use_empty()) { Operand *op = *beginAccess->use_begin(); // Delete any associated end_access instructions. if (auto endAccess = dyn_cast<EndAccessInst>(op->getUser())) { assert(endAccess->use_empty() && "found use of end_access"); endAccess->eraseFromParent(); // Forward all other uses to the original address. } else { op->set(beginAccess->getSource()); } } } void run() override { // Don't bother doing anything unless some kind of exclusivity // enforcement is enabled. auto &M = *getModule(); auto preserveAccess = [&M](SILAccessEnforcement enforcement) { // Leave dynamic accesses in place, but delete all others. return enforcement == SILAccessEnforcement::Dynamic && M.getOptions().EnforceExclusivityDynamic; }; bool removedAny = false; auto eraseInst = [&removedAny](SILInstruction *inst) { removedAny = true; return inst->getParent()->erase(inst); }; for (auto &F : M) { // Iterating in reverse eliminates more begin_access users before they // need to be replaced. for (auto &BB : reversed(F)) { // Don't cache the begin iterator since we're reverse iterating. for (auto II = BB.end(); II != BB.begin();) { SILInstruction *inst = &*(--II); if (auto beginAccess = dyn_cast<BeginAccessInst>(inst)) { // Leave dynamic accesses in place, but delete all others. if (preserveAccess(beginAccess->getEnforcement())) continue; replaceBeginAccessUsers(beginAccess); II = eraseInst(beginAccess); continue; } // end_access instructions will be handled when we process the // begin_access. // begin_unpaired_access instructions will be directly removed and // simply replaced with their operand. if (auto BUA = dyn_cast<BeginUnpairedAccessInst>(inst)) { if (preserveAccess(BUA->getEnforcement())) continue; BUA->replaceAllUsesWith(BUA->getSource()); II = eraseInst(BUA); continue; } // end_unpaired_access instructions will be directly removed and // simply replaced with their operand. if (auto EUA = dyn_cast<EndUnpairedAccessInst>(inst)) { if (preserveAccess(EUA->getEnforcement())) continue; assert(EUA->use_empty() && "use of end_unpaired_access"); II = eraseInst(EUA); continue; } } } // Don't invalidate any analyses if we didn't do anything. if (!removedAny) continue; auto InvalidKind = SILAnalysis::InvalidationKind::Instructions; invalidateAnalysis(&F, InvalidKind); } } }; } // end anonymous namespace SILTransform *swift::createAccessMarkerElimination() { return new AccessMarkerElimination(); } <|endoftext|>
<commit_before>// Tests for UNIX to-from struct tm functions. // // http://trac.osgeo.org/gdal/browser/trunk/gdal/port/cpl_time.cpp // // 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. // // The GDAL progress handler setup does not expose the scaled progress data // cleanly, so it is difficult to test. #include <time.h> #include <cstdlib> #include "gunit.h" #include "port/cpl_port.h" #include "port/cpl_time.h" // Tests Unix to struct time and back. TEST(TimeTest, Time) { struct tm time; struct tm *time_result; // Start of the unix epoch. GIntBig test_seconds = 0; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(&time, time_result); ASSERT_EQ(0, time.tm_sec); ASSERT_EQ(0, time.tm_min); ASSERT_EQ(0, time.tm_hour); ASSERT_EQ(1, time.tm_mday); ASSERT_EQ(0, time.tm_mon); ASSERT_EQ(70, time.tm_year); ASSERT_EQ(4, time.tm_wday); ASSERT_EQ(0, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // One second before the unix epoch. test_seconds = -1; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(&time, time_result); ASSERT_EQ(59, time.tm_sec); ASSERT_EQ(59, time.tm_min); ASSERT_EQ(23, time.tm_hour); ASSERT_EQ(31, time.tm_mday); ASSERT_EQ(11, time.tm_mon); ASSERT_EQ(69, time.tm_year); ASSERT_EQ(3, time.tm_wday); ASSERT_EQ(364, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // Middle of summer for daylight savings time. test_seconds = 1405018019; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(59, time.tm_sec); ASSERT_EQ(46, time.tm_min); ASSERT_EQ(18, time.tm_hour); ASSERT_EQ(10, time.tm_mday); ASSERT_EQ(6, time.tm_mon); ASSERT_EQ(114, time.tm_year); ASSERT_EQ(4, time.tm_wday); ASSERT_EQ(190, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // Leap day. test_seconds = 1204243247; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(47, time.tm_sec); ASSERT_EQ(0, time.tm_min); ASSERT_EQ(0, time.tm_hour); ASSERT_EQ(29, time.tm_mday); ASSERT_EQ(1, time.tm_mon); ASSERT_EQ(108, time.tm_year); ASSERT_EQ(5, time.tm_wday); ASSERT_EQ(59, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // Far future. test_seconds = 5000000000; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(20, time.tm_sec); ASSERT_EQ(53, time.tm_min); ASSERT_EQ(8, time.tm_hour); ASSERT_EQ(11, time.tm_mday); ASSERT_EQ(5, time.tm_mon); ASSERT_EQ(228, time.tm_year); ASSERT_EQ(5, time.tm_wday); ASSERT_EQ(162, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // 1900. test_seconds = -2208988800; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(0, time.tm_sec); ASSERT_EQ(0, time.tm_min); ASSERT_EQ(0, time.tm_hour); ASSERT_EQ(1, time.tm_mday); ASSERT_EQ(0, time.tm_mon); ASSERT_EQ(0, time.tm_year); ASSERT_EQ(1, time.tm_wday); ASSERT_EQ(0, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); } // Tests round trip of random values. TEST(TimeTest, FuzzRandomTime) { struct tm time; struct tm *time_result; // Start of the unix epoch. for (int count=0; count < 10000; ++count) { const GIntBig test_seconds = static_cast<GIntBig> (random() % 10000000000 - 5000000000); time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); } } <commit_msg>Test CPLParseRFC822DateTime<commit_after>// Tests for UNIX to-from struct tm functions. // // http://trac.osgeo.org/gdal/browser/trunk/gdal/port/cpl_time.cpp // // 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. // // See also: // // https://tools.ietf.org/html/rfc822 // https://tools.ietf.org/html/rfc2445 // https://tools.ietf.org/html/rfc3339 #include <time.h> #include <cstdlib> #include "gunit.h" #include "port/cpl_port.h" #include "port/cpl_time.h" // Tests Unix to struct time and back. TEST(TimeTest, Time) { struct tm time; struct tm *time_result; // Start of the unix epoch. GIntBig test_seconds = 0; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(&time, time_result); ASSERT_EQ(0, time.tm_sec); ASSERT_EQ(0, time.tm_min); ASSERT_EQ(0, time.tm_hour); ASSERT_EQ(1, time.tm_mday); ASSERT_EQ(0, time.tm_mon); ASSERT_EQ(70, time.tm_year); ASSERT_EQ(4, time.tm_wday); ASSERT_EQ(0, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // One second before the unix epoch. test_seconds = -1; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(&time, time_result); ASSERT_EQ(59, time.tm_sec); ASSERT_EQ(59, time.tm_min); ASSERT_EQ(23, time.tm_hour); ASSERT_EQ(31, time.tm_mday); ASSERT_EQ(11, time.tm_mon); ASSERT_EQ(69, time.tm_year); ASSERT_EQ(3, time.tm_wday); ASSERT_EQ(364, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // Middle of summer for daylight savings time. test_seconds = 1405018019; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(59, time.tm_sec); ASSERT_EQ(46, time.tm_min); ASSERT_EQ(18, time.tm_hour); ASSERT_EQ(10, time.tm_mday); ASSERT_EQ(6, time.tm_mon); ASSERT_EQ(114, time.tm_year); ASSERT_EQ(4, time.tm_wday); ASSERT_EQ(190, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // Leap day. test_seconds = 1204243247; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(47, time.tm_sec); ASSERT_EQ(0, time.tm_min); ASSERT_EQ(0, time.tm_hour); ASSERT_EQ(29, time.tm_mday); ASSERT_EQ(1, time.tm_mon); ASSERT_EQ(108, time.tm_year); ASSERT_EQ(5, time.tm_wday); ASSERT_EQ(59, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // Far future. test_seconds = 5000000000; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(20, time.tm_sec); ASSERT_EQ(53, time.tm_min); ASSERT_EQ(8, time.tm_hour); ASSERT_EQ(11, time.tm_mday); ASSERT_EQ(5, time.tm_mon); ASSERT_EQ(228, time.tm_year); ASSERT_EQ(5, time.tm_wday); ASSERT_EQ(162, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); // 1900. test_seconds = -2208988800; time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(0, time.tm_sec); ASSERT_EQ(0, time.tm_min); ASSERT_EQ(0, time.tm_hour); ASSERT_EQ(1, time.tm_mday); ASSERT_EQ(0, time.tm_mon); ASSERT_EQ(0, time.tm_year); ASSERT_EQ(1, time.tm_wday); ASSERT_EQ(0, time.tm_yday); ASSERT_EQ(0, time.tm_isdst); // Always 0. ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); } // Tests round trip of random values. TEST(TimeTest, FuzzRandomTime) { struct tm time; struct tm *time_result; // Start of the unix epoch. for (int count=0; count < 10000; ++count) { const GIntBig test_seconds = static_cast<GIntBig> (random() % 10000000000 - 5000000000); time_result = CPLUnixTimeToYMDHMS(test_seconds, &time); ASSERT_EQ(test_seconds, CPLYMDHMSToUnixTime(&time)); } } TEST(DirectRfc822Test, NullPointers) { EXPECT_FALSE(CPLParseRFC822DateTime(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); } constexpr int kUndefined = -9999; class Rfc822Test : public ::testing::Test { protected: bool Check(const char* rfc822datetime) { int result = CPLParseRFC822DateTime(rfc822datetime, &year_, &month_, &day_, &hour_, &minute_, &second_, &tzflag_, &weekday_); CHECK(result == FALSE || result == TRUE); return CPL_TO_BOOL(result); } int year_ = kUndefined; int month_ = kUndefined; int day_ = kUndefined; int hour_ = kUndefined; int minute_ = kUndefined; int second_ = kUndefined; int tzflag_ = kUndefined; int weekday_ = kUndefined; }; TEST_F(Rfc822Test, BasicFails) { EXPECT_FALSE(Check("")); EXPECT_EQ(kUndefined, year_); EXPECT_EQ(kUndefined, month_); EXPECT_EQ(kUndefined, day_); EXPECT_EQ(kUndefined, hour_); EXPECT_EQ(kUndefined, minute_); EXPECT_EQ(kUndefined, second_); EXPECT_EQ(kUndefined, tzflag_); EXPECT_EQ(kUndefined, weekday_); day_ = kUndefined; EXPECT_FALSE(Check("0 Dec 1 05:24:17")); EXPECT_EQ(kUndefined, day_); EXPECT_FALSE(Check("32 Dec 301 05:24:17")); EXPECT_EQ(kUndefined, day_); EXPECT_FALSE(Check("100 Dec 301 05:24:17")); EXPECT_EQ(kUndefined, day_); // Out of range day EXPECT_FALSE(Check("-1 Dec 1 05:24:17")); EXPECT_EQ(kUndefined, day_); } TEST_F(Rfc822Test, Basic) { EXPECT_TRUE(Check("28 Dec 2007 05:24:17")); EXPECT_EQ(2007, year_); EXPECT_EQ(12, month_); EXPECT_EQ(28, day_); EXPECT_EQ(5, hour_); EXPECT_EQ(24, minute_); EXPECT_EQ(17, second_); EXPECT_EQ(0, tzflag_); EXPECT_EQ(0, weekday_); } TEST_F(Rfc822Test, NoSeconds) { EXPECT_TRUE(Check("28 Dec 2007 05:24")); EXPECT_EQ(2007, year_); EXPECT_EQ(12, month_); EXPECT_EQ(28, day_); EXPECT_EQ(5, hour_); EXPECT_EQ(24, minute_); EXPECT_EQ(-1, second_); EXPECT_EQ(0, tzflag_); EXPECT_EQ(0, weekday_); } TEST_F(Rfc822Test, NoDayOrTimeZone) { EXPECT_TRUE(Check("28 Dec 2007 05:24:17")); EXPECT_EQ(2007, year_); EXPECT_EQ(12, month_); EXPECT_EQ(28, day_); EXPECT_EQ(5, hour_); EXPECT_EQ(24, minute_); EXPECT_EQ(17, second_); EXPECT_EQ(0, tzflag_); EXPECT_EQ(0, weekday_); } TEST_F(Rfc822Test, SmallYear) { EXPECT_TRUE(Check("28 Dec 1 05:24:17")); EXPECT_EQ(2001, year_); EXPECT_TRUE(Check("28 Dec 301 05:24:17")); EXPECT_EQ(301, year_); } TEST_F(Rfc822Test, DayAndTimeZone) { EXPECT_TRUE(Check("Fri 28 Dec 2007 05:24:17 GMT")); EXPECT_EQ(2007, year_); EXPECT_EQ(12, month_); EXPECT_EQ(28, day_); EXPECT_EQ(5, hour_); EXPECT_EQ(24, minute_); EXPECT_EQ(17, second_); EXPECT_EQ(100, tzflag_); EXPECT_EQ(5, weekday_); } <|endoftext|>
<commit_before>/* --------------------------------------------------------------------- The template library textwolf implements an input iterator on a set of XML path expressions without backward references on an STL conforming input iterator as source. It does no buffering or read ahead and is dedicated for stream processing of XML for a small set of XML queries. Stream processing in this Object refers to processing the document without buffering anything but the current result token processed with its tag hierarchy information. Copyright (C) 2010,2011,2012,2013,2014 Patrick Frey This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -------------------------------------------------------------------- The latest version of textwolf can be found at 'http://github.com/patrickfrey/textwolf' For documentation see 'http://patrickfrey.github.com/textwolf' -------------------------------------------------------------------- */ /// \file textwolf/xmlprinter.hpp /// \brief XML printer interface hiding character encoding properties #ifndef __TEXTWOLF_XML_PRINTER_HPP__ #define __TEXTWOLF_XML_PRINTER_HPP__ #include "textwolf/cstringiterator.hpp" #include "textwolf/textscanner.hpp" #include "textwolf/xmlscanner.hpp" #include "textwolf/charset.hpp" #include "textwolf/xmltagstack.hpp" #include <cstring> #include <cstdlib> /// \namespace textwolf /// \brief Toplevel namespace of the library namespace textwolf { /// \class XMLPrinter /// \brief Character encoding dependent XML printer /// \tparam IOCharset Character set encoding of input and output /// \tparam AppCharset Character set encoding of the application processor /// \tparam BufferType STL back insertion sequence to use for printing output template <class IOCharset, class AppCharset,class BufferType> class XMLPrinter { private: /// \brief Prints a character string to an STL back insertion sequence buffer in the IO character set encoding /// \param [in] src pointer to string to print /// \param [in] srcsize size of src in bytes /// \param [out] buf buffer to append result to void printToBuffer( const char* src, std::size_t srcsize, BufferType& buf) const { CStringIterator itr( src, srcsize); TextScanner<CStringIterator,AppCharset> ts( itr); UChar ch; while ((ch = ts.chr()) != 0) { m_output.print( ch, buf); ++ts; } } /// \brief print a character substitute or the character itself /// \param [in] ch character to print /// \param [in,out] buf buffer to print to /// \param [in] nof_echr number of elements in echr and estr /// \param [in] echr ASCII characters to substitute /// \param [in] estr ASCII strings to substitute with (array parallel to echr) void printEsc( char ch, BufferType& buf, unsigned int nof_echr, const char* echr, const char** estr) const { const char* cc = (const char*)memchr( echr, ch, nof_echr); if (cc) { unsigned int ii = 0; const char* tt = estr[ cc-echr]; while (tt[ii]) m_output.print( tt[ii++], buf); } else { m_output.print( ch, buf); } } /// \brief print a value with some characters replaced by a string /// \param [in] src pointer to attribute value string to print /// \param [in] srcsize size of src in bytes /// \param [in,out] buf buffer to print to /// \param [in] nof_echr number of elements in echr and estr /// \param [in] echr ASCII characters to substitute /// \param [in] estr ASCII strings to substitute with (array parallel to echr) void printToBufferSubstChr( const char* src, std::size_t srcsize, BufferType& buf, unsigned int nof_echr, const char* echr, const char** estr) const { CStringIterator itr( src, srcsize); textwolf::TextScanner<CStringIterator,AppCharset> ts( itr); textwolf::UChar ch; while ((ch = ts.chr()) != 0) { if (ch < 128) { printEsc( (char)ch, buf, nof_echr, echr, estr); } else { m_output.print( ch, buf); } ++ts; } } /// \brief print attribute value string /// \param [in] src pointer to attribute value string to print /// \param [in] srcsize size of src in bytes /// \param [in,out] buf buffer to print to void printToBufferAttributeValue( const char* src, std::size_t srcsize, BufferType& buf) const { enum {nof_echr = 12}; static const char* estr[nof_echr] = {"&lt;", "&gt;", "&apos;", "&quot;", "&amp;", "&#0;", "&#8;", "&#9;", "&#10;", "&#13;"}; static const char echr[nof_echr+1] = "<>'\"&\0\b\t\n\r"; m_output.print( '"', buf); printToBufferSubstChr( src, srcsize, buf, nof_echr, echr, estr); m_output.print( '"', buf); } /// \brief print content value string /// \param [in] src pointer to content string to print /// \param [in] srcsize size of src in bytes /// \param [in,out] buf buffer to print to void printToBufferContent( const char* src, std::size_t srcsize, BufferType& buf) const { enum {nof_echr = 6}; static const char* estr[nof_echr] = {"&lt;", "&gt;", "&amp;", "&#0;", "&#8;"}; static const char echr[nof_echr+1] = "<>&\0\b"; printToBufferSubstChr( src, srcsize, buf, nof_echr, echr, estr); } /// \brief Prints a character to an STL back insertion sequence buffer in the IO character set encoding /// \param [in] ch character to print /// \param [in,out] buf buffer to print to void printToBuffer( char ch, BufferType& buf) const { m_output.print( (textwolf::UChar)(unsigned char)ch, buf); } public: /// \brief Default constructor /// \param[in] subDocument do not require an Xml header to be printed if set to true /// \note Uses the default code pages (IsoLatin-1 for IsoLatin) for output explicit XMLPrinter( bool subDocument=false) :m_state(subDocument?Content:Init),m_lasterror(0){} /// \brief Constructor /// \param[in] output_ character set encoding instance (with the code page tables needed) for output /// \param[in] subDocument do not require an Xml header to be printed if set to true explicit XMLPrinter( const IOCharset& output_, bool subDocument=false) :m_state(subDocument?Content:Init),m_output(output_),m_lasterror(0){} /// \brief Copy constructor XMLPrinter( const XMLPrinter& o) :m_state(o.m_state),m_tagstack(o.m_tagstack),m_output(o.m_output),m_lasterror(o.m_lasterror) {} /// \brief Reset the state /// \param[in] subDocument do not require an Xml header to be printed if set to true void reset( bool subDocument=false) { m_state = subDocument?Content:Init; m_tagstack.clear(); m_lasterror = 0; } /// \brief Prints an XML header (version "1.0") /// \param [in] encoding character set encoding name /// \param [in] standalone standalone attribute ("yes","no" or NULL for undefined) /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printHeader( const char* encoding, const char* standalone, BufferType& buf) { if (m_state != Init) { m_lasterror = "printing xml header not at the beginning of the document"; return false; } std::string enc = encoding?encoding:"UTF-8"; printToBuffer( "<?xml version=\"1.0\" encoding=\"", 30, buf); printToBuffer( enc.c_str(), enc.size(), buf); if (standalone) { printToBuffer( "\" standalone=\"", 14, buf); printToBuffer( standalone, std::strlen(standalone), buf); printToBuffer( "\"?>\n", 4, buf); } else { printToBuffer( "\"?>\n", 4, buf); } m_state = Content; return true; } /// \brief Prints an XML <!DOCTYPE ...> declaration /// \param [in] rootid root element name /// \param [in] publicid PUBLIC attribute /// \param [in] systemid SYSTEM attribute /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printDoctype( const char* rootid, const char* publicid, const char* systemid, BufferType& buf) { if (rootid) { if (publicid) { if (!systemid) { m_lasterror = "defined DOCTYPE with PUBLIC id but no SYSTEM id"; return false; } printToBuffer( "<!DOCTYPE ", 10, buf); printToBuffer( rootid, std::strlen( rootid), buf); printToBuffer( " PUBLIC \"", 9, buf); printToBuffer( publicid, std::strlen( publicid), buf); printToBuffer( "\" \"", 3, buf); printToBuffer( systemid, std::strlen( systemid), buf); printToBuffer( "\">", 2, buf); } else if (systemid) { printToBuffer( "<!DOCTYPE ", 10, buf); printToBuffer( rootid, std::strlen( rootid), buf); printToBuffer( " SYSTEM \"", 9, buf); printToBuffer( systemid, std::strlen( systemid), buf); printToBuffer( "\">", 2, buf); } else { printToBuffer( "<!DOCTYPE ", 11, buf); printToBuffer( rootid, std::strlen( rootid), buf); printToBuffer( ">", 2, buf); } } return true; } /// \brief Close the current tag attribute context opened /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool exitTagContext( BufferType& buf) { if (m_state != Content) { if (m_state == Init) { m_lasterror = "printed xml without root element"; return false; } printToBuffer( '>', buf); m_state = Content; } return true; } /// \brief Print the start of an open tag /// \param [in] src start of the tag name /// \param [in] srcsize length of the tag name in bytes /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printOpenTag( const char* src, std::size_t srcsize, BufferType& buf) { if (!exitTagContext( buf)) return false; printToBuffer( '<', buf); printToBuffer( (const char*)src, srcsize, buf); m_tagstack.push( src, srcsize); m_state = TagElement; return true; } /// \brief Print the start of an attribute name /// \param [in] src start of the attribute name /// \param [in] srcsize length of the attribute name in bytes /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printAttribute( const char* src, std::size_t srcsize, BufferType& buf) { if (m_state == TagElement) { printToBuffer( ' ', buf); printToBuffer( (const char*)src, srcsize, buf); printToBuffer( '=', buf); m_state = TagAttribute; return true; } return false; } /// \brief Print a content or attribute value depending on context /// \param [in] src start of the value /// \param [in] srcsize length of the value in bytes /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printValue( const char* src, std::size_t srcsize, BufferType& buf) { if (m_state == TagAttribute) { printToBufferAttributeValue( (const char*)src, srcsize, buf); m_state = TagElement; } else { if (!exitTagContext( buf)) return false; printToBufferContent( (const char*)src, srcsize, buf); } return true; } /// \brief Print the close of the current tag open /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printCloseTag( BufferType& buf) { const void* cltag; std::size_t cltagsize; if (!m_tagstack.top( cltag, cltagsize) || !cltagsize) { return false; } if (m_state == TagElement) { printToBuffer( '/', buf); printToBuffer( '>', buf); m_state = Content; } else if (m_state != Content) { return false; } else { printToBuffer( '<', buf); printToBuffer( '/', buf); printToBuffer( (const char*)cltag, cltagsize, buf); printToBuffer( '>', buf); } m_tagstack.pop(); if (m_tagstack.empty()) { printToBuffer( '\n', buf); } return true; } /// \brief Internal state enum State { Init, Content, TagAttribute, TagElement }; /// \brief Get the current internal state /// \return the current state State state() const { return m_state; } /// \brief Get the last error occurred /// \return the last error string const char* lasterror() const { return m_lasterror; } private: State m_state; ///< internal state TagStack m_tagstack; ///< tag name stack of open tags IOCharset m_output; ///< output character set encoding const char* m_lasterror; ///< the last error occurred }; } //namespace #endif <commit_msg>adapt changes in textwolf<commit_after>/* --------------------------------------------------------------------- The template library textwolf implements an input iterator on a set of XML path expressions without backward references on an STL conforming input iterator as source. It does no buffering or read ahead and is dedicated for stream processing of XML for a small set of XML queries. Stream processing in this Object refers to processing the document without buffering anything but the current result token processed with its tag hierarchy information. Copyright (C) 2010,2011,2012,2013,2014 Patrick Frey This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -------------------------------------------------------------------- The latest version of textwolf can be found at 'http://github.com/patrickfrey/textwolf' For documentation see 'http://patrickfrey.github.com/textwolf' -------------------------------------------------------------------- */ /// \file textwolf/xmlprinter.hpp /// \brief XML printer interface hiding character encoding properties #ifndef __TEXTWOLF_XML_PRINTER_HPP__ #define __TEXTWOLF_XML_PRINTER_HPP__ #include "textwolf/cstringiterator.hpp" #include "textwolf/textscanner.hpp" #include "textwolf/xmlscanner.hpp" #include "textwolf/charset.hpp" #include "textwolf/xmltagstack.hpp" #include <cstring> #include <cstdlib> /// \namespace textwolf /// \brief Toplevel namespace of the library namespace textwolf { /// \class XMLPrinter /// \brief Character encoding dependent XML printer /// \tparam IOCharset Character set encoding of input and output /// \tparam AppCharset Character set encoding of the application processor /// \tparam BufferType STL back insertion sequence to use for printing output template <class IOCharset, class AppCharset,class BufferType> class XMLPrinter { public: /// \brief Prints a character string to an STL back insertion sequence buffer in the IO character set encoding /// \param [in] src pointer to string to print /// \param [in] srcsize size of src in bytes /// \param [out] buf buffer to append result to void printToBuffer( const char* src, std::size_t srcsize, BufferType& buf) const { CStringIterator itr( src, srcsize); TextScanner<CStringIterator,AppCharset> ts( itr); UChar ch; while ((ch = ts.chr()) != 0) { m_output.print( ch, buf); ++ts; } } /// \brief print a character substitute or the character itself /// \param [in] ch character to print /// \param [in,out] buf buffer to print to /// \param [in] nof_echr number of elements in echr and estr /// \param [in] echr ASCII characters to substitute /// \param [in] estr ASCII strings to substitute with (array parallel to echr) void printEsc( char ch, BufferType& buf, unsigned int nof_echr, const char* echr, const char** estr) const { const char* cc = (const char*)memchr( echr, ch, nof_echr); if (cc) { unsigned int ii = 0; const char* tt = estr[ cc-echr]; while (tt[ii]) m_output.print( tt[ii++], buf); } else { m_output.print( ch, buf); } } /// \brief print a value with some characters replaced by a string /// \param [in] src pointer to attribute value string to print /// \param [in] srcsize size of src in bytes /// \param [in,out] buf buffer to print to /// \param [in] nof_echr number of elements in echr and estr /// \param [in] echr ASCII characters to substitute /// \param [in] estr ASCII strings to substitute with (array parallel to echr) void printToBufferSubstChr( const char* src, std::size_t srcsize, BufferType& buf, unsigned int nof_echr, const char* echr, const char** estr) const { CStringIterator itr( src, srcsize); textwolf::TextScanner<CStringIterator,AppCharset> ts( itr); textwolf::UChar ch; while ((ch = ts.chr()) != 0) { if (ch < 128) { printEsc( (char)ch, buf, nof_echr, echr, estr); } else { m_output.print( ch, buf); } ++ts; } } /// \brief print attribute value string /// \param [in] src pointer to attribute value string to print /// \param [in] srcsize size of src in bytes /// \param [in,out] buf buffer to print to void printToBufferAttributeValue( const char* src, std::size_t srcsize, BufferType& buf) const { enum {nof_echr = 12}; static const char* estr[nof_echr] = {"&lt;", "&gt;", "&apos;", "&quot;", "&amp;", "&#0;", "&#8;", "&#9;", "&#10;", "&#13;"}; static const char echr[nof_echr+1] = "<>'\"&\0\b\t\n\r"; m_output.print( '"', buf); printToBufferSubstChr( src, srcsize, buf, nof_echr, echr, estr); m_output.print( '"', buf); } /// \brief print content value string /// \param [in] src pointer to content string to print /// \param [in] srcsize size of src in bytes /// \param [in,out] buf buffer to print to void printToBufferContent( const char* src, std::size_t srcsize, BufferType& buf) const { enum {nof_echr = 6}; static const char* estr[nof_echr] = {"&lt;", "&gt;", "&amp;", "&#0;", "&#8;"}; static const char echr[nof_echr+1] = "<>&\0\b"; printToBufferSubstChr( src, srcsize, buf, nof_echr, echr, estr); } /// \brief Prints a character to an STL back insertion sequence buffer in the IO character set encoding /// \param [in] ch character to print /// \param [in,out] buf buffer to print to void printToBuffer( char ch, BufferType& buf) const { m_output.print( (textwolf::UChar)(unsigned char)ch, buf); } public: /// \brief Default constructor /// \param[in] subDocument do not require an Xml header to be printed if set to true /// \note Uses the default code pages (IsoLatin-1 for IsoLatin) for output explicit XMLPrinter( bool subDocument=false) :m_state(subDocument?Content:Init),m_lasterror(0){} /// \brief Constructor /// \param[in] output_ character set encoding instance (with the code page tables needed) for output /// \param[in] subDocument do not require an Xml header to be printed if set to true explicit XMLPrinter( const IOCharset& output_, bool subDocument=false) :m_state(subDocument?Content:Init),m_output(output_),m_lasterror(0){} /// \brief Copy constructor XMLPrinter( const XMLPrinter& o) :m_state(o.m_state),m_tagstack(o.m_tagstack),m_output(o.m_output),m_lasterror(o.m_lasterror) {} /// \brief Reset the state /// \param[in] subDocument do not require an Xml header to be printed if set to true void reset( bool subDocument=false) { m_state = subDocument?Content:Init; m_tagstack.clear(); m_lasterror = 0; } /// \brief Prints an XML header (version "1.0") /// \param [in] encoding character set encoding name /// \param [in] standalone standalone attribute ("yes","no" or NULL for undefined) /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printHeader( const char* encoding, const char* standalone, BufferType& buf) { if (m_state != Init) { m_lasterror = "printing xml header not at the beginning of the document"; return false; } std::string enc = encoding?encoding:"UTF-8"; printToBuffer( "<?xml version=\"1.0\" encoding=\"", 30, buf); printToBuffer( enc.c_str(), enc.size(), buf); if (standalone) { printToBuffer( "\" standalone=\"", 14, buf); printToBuffer( standalone, std::strlen(standalone), buf); printToBuffer( "\"?>\n", 4, buf); } else { printToBuffer( "\"?>\n", 4, buf); } m_state = Content; return true; } /// \brief Prints an XML <!DOCTYPE ...> declaration /// \param [in] rootid root element name /// \param [in] publicid PUBLIC attribute /// \param [in] systemid SYSTEM attribute /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printDoctype( const char* rootid, const char* publicid, const char* systemid, BufferType& buf) { if (rootid) { if (publicid) { if (!systemid) { m_lasterror = "defined DOCTYPE with PUBLIC id but no SYSTEM id"; return false; } printToBuffer( "<!DOCTYPE ", 10, buf); printToBuffer( rootid, std::strlen( rootid), buf); printToBuffer( " PUBLIC \"", 9, buf); printToBuffer( publicid, std::strlen( publicid), buf); printToBuffer( "\" \"", 3, buf); printToBuffer( systemid, std::strlen( systemid), buf); printToBuffer( "\">", 2, buf); } else if (systemid) { printToBuffer( "<!DOCTYPE ", 10, buf); printToBuffer( rootid, std::strlen( rootid), buf); printToBuffer( " SYSTEM \"", 9, buf); printToBuffer( systemid, std::strlen( systemid), buf); printToBuffer( "\">", 2, buf); } else { printToBuffer( "<!DOCTYPE ", 11, buf); printToBuffer( rootid, std::strlen( rootid), buf); printToBuffer( ">", 2, buf); } } return true; } /// \brief Close the current tag attribute context opened /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool exitTagContext( BufferType& buf) { if (m_state != Content) { if (m_state == Init) { m_lasterror = "printed xml without root element"; return false; } printToBuffer( '>', buf); m_state = Content; } return true; } /// \brief Print the start of an open tag /// \param [in] src start of the tag name /// \param [in] srcsize length of the tag name in bytes /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printOpenTag( const char* src, std::size_t srcsize, BufferType& buf) { if (!exitTagContext( buf)) return false; printToBuffer( '<', buf); printToBuffer( (const char*)src, srcsize, buf); m_tagstack.push( src, srcsize); m_state = TagElement; return true; } /// \brief Print the start of an attribute name /// \param [in] src start of the attribute name /// \param [in] srcsize length of the attribute name in bytes /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printAttribute( const char* src, std::size_t srcsize, BufferType& buf) { if (m_state == TagElement) { printToBuffer( ' ', buf); printToBuffer( (const char*)src, srcsize, buf); printToBuffer( '=', buf); m_state = TagAttribute; return true; } return false; } /// \brief Print a content or attribute value depending on context /// \param [in] src start of the value /// \param [in] srcsize length of the value in bytes /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printValue( const char* src, std::size_t srcsize, BufferType& buf) { if (m_state == TagAttribute) { printToBufferAttributeValue( (const char*)src, srcsize, buf); m_state = TagElement; } else { if (!exitTagContext( buf)) return false; printToBufferContent( (const char*)src, srcsize, buf); } return true; } /// \brief Print the close of the current tag open /// \param [out] buf buffer to print to /// \return true on success, false if failed (check lasterror()) bool printCloseTag( BufferType& buf) { const void* cltag; std::size_t cltagsize; if (!m_tagstack.top( cltag, cltagsize) || !cltagsize) { return false; } if (m_state == TagElement) { printToBuffer( '/', buf); printToBuffer( '>', buf); m_state = Content; } else if (m_state != Content) { return false; } else { printToBuffer( '<', buf); printToBuffer( '/', buf); printToBuffer( (const char*)cltag, cltagsize, buf); printToBuffer( '>', buf); } m_tagstack.pop(); if (m_tagstack.empty()) { printToBuffer( '\n', buf); } return true; } /// \brief Internal state enum State { Init, Content, TagAttribute, TagElement }; /// \brief Get the current internal state /// \return the current state State state() const { return m_state; } /// \brief Get the last error occurred /// \return the last error string const char* lasterror() const { return m_lasterror; } private: State m_state; ///< internal state TagStack m_tagstack; ///< tag name stack of open tags IOCharset m_output; ///< output character set encoding const char* m_lasterror; ///< the last error occurred }; } //namespace #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MiniAppManager.h" #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <itkImage.h> #include <itkImageFileReader.h> #include <itkExceptionObject.h> #include <itkImageFileWriter.h> #include <itkMetaDataObject.h> #include <itkVectorImage.h> #include <itkResampleImageFilter.h> #include <mitkBaseDataIOFactory.h> #include <mitkDiffusionImage.h> #include <mitkQBallImage.h> #include <mitkBaseData.h> #include <mitkDiffusionCoreObjectFactory.h> #include <mitkFiberTrackingObjectFactory.h> #include <mitkFiberBundleX.h> #include "ctkCommandLineParser.h" #include <boost/lexical_cast.hpp> /** * Short program to average redundant gradients in dwi-files */ mitk::FiberBundleX::Pointer LoadFib(std::string filename) { const std::string s1="", s2=""; std::vector<mitk::BaseData::Pointer> fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( fibInfile.empty() ) MITK_INFO << "File " << filename << " could not be read!"; mitk::BaseData::Pointer baseData = fibInfile.at(0); return dynamic_cast<mitk::FiberBundleX*>(baseData.GetPointer()); } int FiberProcessing(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input fiber bundle (.fib)", us::Any(), false); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); parser.addArgument("resample", "r", ctkCommandLineParser::Float, "Resample fiber with the given point distance (in mm)"); parser.addArgument("smooth", "s", ctkCommandLineParser::Float, "Smooth fiber with the given point distance (in mm)"); parser.addArgument("minLength", "l", ctkCommandLineParser::Float, "Minimum fiber length (in mm)"); parser.addArgument("maxLength", "m", ctkCommandLineParser::Float, "Maximum fiber length (in mm)"); parser.addArgument("minCurv", "a", ctkCommandLineParser::Float, "Minimum curvature radius (in mm)"); parser.addArgument("mirror", "p", ctkCommandLineParser::Int, "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; float pointDist = -1; if (parsedArgs.count("resample")) pointDist = us::any_cast<float>(parsedArgs["resample"]); float smoothDist = -1; if (parsedArgs.count("smooth")) smoothDist = us::any_cast<float>(parsedArgs["smooth"]); float minFiberLength = -1; if (parsedArgs.count("minLength")) minFiberLength = us::any_cast<float>(parsedArgs["minLength"]); float maxFiberLength = -1; if (parsedArgs.count("maxLength")) maxFiberLength = us::any_cast<float>(parsedArgs["maxLength"]); float curvThres = -1; if (parsedArgs.count("minCurv")) curvThres = us::any_cast<float>(parsedArgs["minCurv"]); int axis = 0; if (parsedArgs.count("mirror")) axis = us::any_cast<int>(parsedArgs["mirror"]); string inFileName = us::any_cast<string>(parsedArgs["input"]); string outFileName = us::any_cast<string>(parsedArgs["outFile"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); mitk::FiberBundleX::Pointer fib = LoadFib(inFileName); if (minFiberLength>0) fib->RemoveShortFibers(minFiberLength); if (maxFiberLength>0) fib->RemoveLongFibers(maxFiberLength); if (curvThres>0) fib->ApplyCurvatureThreshold(curvThres, false); if (pointDist>0) fib->ResampleFibers(pointDist); if (smoothDist>0) fib->DoFiberSmoothing(smoothDist); if (axis/100==1) fib->MirrorFibers(0); if ((axis%100)/10==1) fib->MirrorFibers(1); if (axis%10==1) fib->MirrorFibers(2); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(fib.GetPointer()) ) { MITK_INFO << "writing " << outFileName; (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( fib.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } } RegisterDiffusionMiniApp(FiberProcessing); <commit_msg>remove unnecessary includes and wrong class comment<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MiniAppManager.h" #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <itkImageFileWriter.h> #include <itkMetaDataObject.h> #include <itkVectorImage.h> #include <mitkBaseDataIOFactory.h> #include <mitkBaseData.h> #include <mitkDiffusionCoreObjectFactory.h> #include <mitkFiberTrackingObjectFactory.h> #include <mitkFiberBundleX.h> #include "ctkCommandLineParser.h" #include <boost/lexical_cast.hpp> mitk::FiberBundleX::Pointer LoadFib(std::string filename) { const std::string s1="", s2=""; std::vector<mitk::BaseData::Pointer> fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( fibInfile.empty() ) MITK_INFO << "File " << filename << " could not be read!"; mitk::BaseData::Pointer baseData = fibInfile.at(0); return dynamic_cast<mitk::FiberBundleX*>(baseData.GetPointer()); } int FiberProcessing(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input fiber bundle (.fib)", us::Any(), false); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); parser.addArgument("resample", "r", ctkCommandLineParser::Float, "Resample fiber with the given point distance (in mm)"); parser.addArgument("smooth", "s", ctkCommandLineParser::Float, "Smooth fiber with the given point distance (in mm)"); parser.addArgument("minLength", "l", ctkCommandLineParser::Float, "Minimum fiber length (in mm)"); parser.addArgument("maxLength", "m", ctkCommandLineParser::Float, "Maximum fiber length (in mm)"); parser.addArgument("minCurv", "a", ctkCommandLineParser::Float, "Minimum curvature radius (in mm)"); parser.addArgument("mirror", "p", ctkCommandLineParser::Int, "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; float pointDist = -1; if (parsedArgs.count("resample")) pointDist = us::any_cast<float>(parsedArgs["resample"]); float smoothDist = -1; if (parsedArgs.count("smooth")) smoothDist = us::any_cast<float>(parsedArgs["smooth"]); float minFiberLength = -1; if (parsedArgs.count("minLength")) minFiberLength = us::any_cast<float>(parsedArgs["minLength"]); float maxFiberLength = -1; if (parsedArgs.count("maxLength")) maxFiberLength = us::any_cast<float>(parsedArgs["maxLength"]); float curvThres = -1; if (parsedArgs.count("minCurv")) curvThres = us::any_cast<float>(parsedArgs["minCurv"]); int axis = 0; if (parsedArgs.count("mirror")) axis = us::any_cast<int>(parsedArgs["mirror"]); string inFileName = us::any_cast<string>(parsedArgs["input"]); string outFileName = us::any_cast<string>(parsedArgs["outFile"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); mitk::FiberBundleX::Pointer fib = LoadFib(inFileName); if (minFiberLength>0) fib->RemoveShortFibers(minFiberLength); if (maxFiberLength>0) fib->RemoveLongFibers(maxFiberLength); if (curvThres>0) fib->ApplyCurvatureThreshold(curvThres, false); if (pointDist>0) fib->ResampleFibers(pointDist); if (smoothDist>0) fib->DoFiberSmoothing(smoothDist); if (axis/100==1) fib->MirrorFibers(0); if ((axis%100)/10==1) fib->MirrorFibers(1); if (axis%10==1) fib->MirrorFibers(2); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(fib.GetPointer()) ) { MITK_INFO << "writing " << outFileName; (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( fib.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } } RegisterDiffusionMiniApp(FiberProcessing); <|endoftext|>
<commit_before>/* $Id$ */ # ifndef CPPAD_HASH_CODE_INCLUDED # define CPPAD_HASH_CODE_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-09 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /*! file hash_code.cpp A General Purpose hashing utility. */ /*! \def CPPAD_HASH_TABLE_SIZE the codes retruned by hash_code are between zero and CPPAD_HASH_TABLE_SIZE minus one. */ # define CPPAD_HASH_TABLE_SIZE 65536 CPPAD_BEGIN_NAMESPACE /*! Returns a hash code for an arbitrary value. \tparam Value is the type of the argument being hash coded. It should be a plain old data class; i.e., the values included in the equality operator in the object and not pointed to by the object. \param value the value that we are generating a hash code for. \return is a hash code that is between zero and CPPAD_HASH_TABLE_SIZE - 1. \par Restrictions It is assumed (and checked when NDEBUG is not defined) that the $codei%sizeof(%Value%)%$$ is even and that $code sizeof(unsigned short)$$ is equal to two. */ template <class Value> unsigned short hash_code(const Value& value) { CPPAD_ASSERT_UNKNOWN( sizeof(unsigned short) == 2 ); static unsigned short n = sizeof(value) / 2; CPPAD_ASSERT_UNKNOWN( sizeof(value) == 2 * n ); const unsigned short* v; size_t i; unsigned short code; v = reinterpret_cast<const unsigned short*>(& value); i = n; code = v[i]; while(i--) code += v[i]; return code; } CPPAD_END_NAMESPACE # endif <commit_msg>branches/optimize: missing from previous commit hash_code.hpp: fix bug in hash coding function<commit_after>/* $Id$ */ # ifndef CPPAD_HASH_CODE_INCLUDED # define CPPAD_HASH_CODE_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-09 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /*! file hash_code.cpp A General Purpose hashing utility. */ /*! \def CPPAD_HASH_TABLE_SIZE the codes retruned by hash_code are between zero and CPPAD_HASH_TABLE_SIZE minus one. */ # define CPPAD_HASH_TABLE_SIZE 65536 CPPAD_BEGIN_NAMESPACE /*! Returns a hash code for an arbitrary value. \tparam Value is the type of the argument being hash coded. It should be a plain old data class; i.e., the values included in the equality operator in the object and not pointed to by the object. \param value the value that we are generating a hash code for. \return is a hash code that is between zero and CPPAD_HASH_TABLE_SIZE - 1. \par Restrictions It is assumed (and checked when NDEBUG is not defined) that the $codei%sizeof(%Value%)%$$ is even and that $code sizeof(unsigned short)$$ is equal to two. */ template <class Value> unsigned short hash_code(const Value& value) { CPPAD_ASSERT_UNKNOWN( sizeof(unsigned short) == 2 ); static unsigned short n = sizeof(value) / 2; CPPAD_ASSERT_UNKNOWN( sizeof(value) == 2 * n ); const unsigned short* v; size_t i; unsigned short code; v = reinterpret_cast<const unsigned short*>(& value); i = n - 1; code = v[i]; while(i--) code += v[i]; return code; } CPPAD_END_NAMESPACE # endif <|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. * *=========================================================================*/ #ifndef __itkImageSeriesWriter_hxx #define __itkImageSeriesWriter_hxx #include "itkImageSeriesWriter.h" #include "itkDataObject.h" #include "itkImageIOFactory.h" #include "itkIOCommon.h" #include "itkProgressReporter.h" #include "itkImageRegionIterator.h" #include "itkMetaDataObject.h" #include "itkArray.h" #include "vnl/algo/vnl_determinant.h" #include <cstdio> namespace itk { //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > ImageSeriesWriter< TInputImage, TOutputImage > ::ImageSeriesWriter(): m_ImageIO(ITK_NULLPTR), m_UserSpecifiedImageIO(false), m_SeriesFormat("%d"), m_StartIndex(1), m_IncrementIndex(1), m_MetaDataDictionaryArray(ITK_NULLPTR) { m_UseCompression = false; } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > ImageSeriesWriter< TInputImage, TOutputImage > ::~ImageSeriesWriter() {} //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::SetInput(const InputImageType *input) { // ProcessObject is not const_correct so this cast is required here. this->ProcessObject::SetNthInput( 0, const_cast< TInputImage * >( input ) ); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > const typename ImageSeriesWriter< TInputImage, TOutputImage >::InputImageType * ImageSeriesWriter< TInputImage, TOutputImage > ::GetInput(void) { return itkDynamicCastInDebugMode< TInputImage * >( this->GetPrimaryInput() ); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > const typename ImageSeriesWriter< TInputImage, TOutputImage >::InputImageType * ImageSeriesWriter< TInputImage, TOutputImage > ::GetInput(unsigned int idx) { return itkDynamicCastInDebugMode< TInputImage * >( this->ProcessObject::GetInput(idx) ); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::Write(void) { const InputImageType *inputImage = this->GetInput(); itkDebugMacro(<< "Writing an image file"); // Make sure input is available if ( inputImage == ITK_NULLPTR ) { itkExceptionMacro(<< "No input to writer!"); } // Make sure the data is up-to-date. // NOTE: this const_cast<> is due to the lack of const-correctness // of the ProcessObject. InputImageType *nonConstImage = const_cast< InputImageType * >( inputImage ); nonConstImage->Update(); // Notify start event observers this->InvokeEvent( StartEvent() ); // Actually do something this->GenerateData(); // Notify end event observers this->InvokeEvent( EndEvent() ); // Release upstream data if requested if ( inputImage->ShouldIReleaseData() ) { nonConstImage->ReleaseData(); } } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::GenerateNumericFileNamesAndWrite(void) { itkWarningMacro("This functionality has been DEPRECATED. Use NumericSeriesFileName for generating the filenames"); this->GenerateNumericFileNames(); this->WriteFiles(); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::GenerateNumericFileNames(void) { const InputImageType *inputImage = this->GetInput(); if ( !inputImage ) { itkExceptionMacro(<< "Input image is NULL"); } m_FileNames.clear(); // We need two regions. One for the input, one for the output. ImageRegion< TInputImage::ImageDimension > inRegion = inputImage->GetRequestedRegion(); SizeValueType fileNumber = this->m_StartIndex; char fileName[IOCommon::ITK_MAXPATHLEN + 1]; // Compute the number of files to be generated unsigned int numberOfFiles = 1; for ( unsigned int n = TOutputImage::ImageDimension; n < TInputImage::ImageDimension; n++ ) { numberOfFiles *= inRegion.GetSize(n); } for ( unsigned int slice = 0; slice < numberOfFiles; slice++ ) { sprintf (fileName, m_SeriesFormat.c_str(), fileNumber); m_FileNames.push_back(fileName); fileNumber += this->m_IncrementIndex; } } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::GenerateData(void) { itkDebugMacro(<< "Writing a series of files"); if ( m_FileNames.empty() ) { // this method will be deprecated. It is here only to maintain the old API this->GenerateNumericFileNamesAndWrite(); return; } this->WriteFiles(); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::WriteFiles() { const InputImageType *inputImage = this->GetInput(); if ( !inputImage ) { itkExceptionMacro(<< "Input image is NULL"); } // We need two regions. One for the input, one for the output. ImageRegion< TInputImage::ImageDimension > inRegion = inputImage->GetRequestedRegion(); ImageRegion< TOutputImage::ImageDimension > outRegion; // The size of the output will match the input sizes, up to the // dimension of the input. for ( unsigned int i = 0; i < TOutputImage::ImageDimension; i++ ) { outRegion.SetSize(i, inputImage->GetRequestedRegion().GetSize()[i]); } // Allocate an image for output and create an iterator for it typename OutputImageType::Pointer outputImage = OutputImageType::New(); outputImage->SetRegions(outRegion); outputImage->Allocate(); ImageRegionIterator< OutputImageType > ot(outputImage, outRegion); // Set the origin and spacing of the output double spacing[TOutputImage::ImageDimension]; double origin[TOutputImage::ImageDimension]; typename TOutputImage::DirectionType direction; for ( unsigned int i = 0; i < TOutputImage::ImageDimension; i++ ) { origin[i] = inputImage->GetOrigin()[i]; spacing[i] = inputImage->GetSpacing()[i]; outRegion.SetSize(i, inputImage->GetRequestedRegion().GetSize()[i]); for ( unsigned int j = 0; j < TOutputImage::ImageDimension; j++ ) { direction[j][i] = inputImage->GetDirection()[j][i]; } } // // Address the fact that when taking a 2x2 sub-matrix from // the direction matrix we may obtain a singular matrix. // A 2x2 orientation can't represent a 3x3 orientation and // therefore, replacing the orientation with an identity // is as arbitrary as any other choice. // if ( vnl_determinant( direction.GetVnlMatrix() ) == 0.0 ) { direction.SetIdentity(); } outputImage->SetOrigin(origin); outputImage->SetSpacing(spacing); outputImage->SetDirection(direction); Index< TInputImage::ImageDimension > inIndex; Size< TInputImage::ImageDimension > inSize; SizeValueType pixelsPerFile = outputImage->GetRequestedRegion().GetNumberOfPixels(); inSize.Fill(1); for ( unsigned int ns = 0; ns < TOutputImage::ImageDimension; ns++ ) { inSize[ns] = outRegion.GetSize()[ns]; } unsigned int expectedNumberOfFiles = 1; for ( unsigned int n = TOutputImage::ImageDimension; n < TInputImage::ImageDimension; n++ ) { expectedNumberOfFiles *= inRegion.GetSize(n); } if ( m_FileNames.size() != expectedNumberOfFiles ) { itkExceptionMacro( << "The number of filenames passed is " << m_FileNames.size() << " but " << expectedNumberOfFiles << " were expected "); return; } itkDebugMacro( << "Number of files to write = " << m_FileNames.size() ); ProgressReporter progress(this, 0, expectedNumberOfFiles, expectedNumberOfFiles); // For each "slice" in the input, copy the region to the output, // build a filename and write the file. typename InputImageType::OffsetValueType offset = 0; for ( unsigned int slice = 0; slice < m_FileNames.size(); slice++ ) { // Select a "slice" of the image. inIndex = inputImage->ComputeIndex(offset); inRegion.SetIndex(inIndex); inRegion.SetSize(inSize); ImageRegionConstIterator< InputImageType > it (inputImage, inRegion); // Copy the selected "slice" into the output image. it.GoToBegin(); ot.GoToBegin(); while ( !ot.IsAtEnd() ) { ot.Set( it.Get() ); ++it; ++ot; } typename WriterType::Pointer writer = WriterType::New(); writer->UseInputMetaDataDictionaryOff(); // use the dictionary from the // ImageIO class writer->SetInput(outputImage); if ( m_ImageIO ) { writer->SetImageIO(m_ImageIO); } if ( m_MetaDataDictionaryArray ) { if ( m_ImageIO ) { if ( slice > m_MetaDataDictionaryArray->size() - 1 ) { itkExceptionMacro ( "The slice number: " << slice + 1 << " exceeds the size of the MetaDataDictionaryArray " << m_MetaDataDictionaryArray->size() << "."); } DictionaryRawPointer dictionary = ( *m_MetaDataDictionaryArray )[slice]; m_ImageIO->SetMetaDataDictionary( ( *dictionary ) ); } else { itkExceptionMacro(<< "Attempted to use a MetaDataDictionaryArray without specifying an ImageIO!"); } } else { if ( m_ImageIO ) { DictionaryType & dictionary = m_ImageIO->GetMetaDataDictionary(); typename InputImageType::SpacingType spacing2 = inputImage->GetSpacing(); // origin of the output slice in the // N-Dimensional space of the input image. typename InputImageType::PointType origin2; inputImage->TransformIndexToPhysicalPoint(inIndex, origin2); const unsigned int inputImageDimension = TInputImage::ImageDimension; typedef Array< double > DoubleArrayType; DoubleArrayType originArray(inputImageDimension); DoubleArrayType spacingArray(inputImageDimension); for ( unsigned int d = 0; d < inputImageDimension; d++ ) { originArray[d] = origin2[d]; spacingArray[d] = spacing2[d]; } EncapsulateMetaData< DoubleArrayType >(dictionary, ITK_Origin, originArray); EncapsulateMetaData< DoubleArrayType >(dictionary, ITK_Spacing, spacingArray); EncapsulateMetaData< unsigned int >(dictionary, ITK_NumberOfDimensions, inputImageDimension); typename InputImageType::DirectionType direction2 = inputImage->GetDirection(); typedef Matrix< double, inputImageDimension, inputImageDimension> DoubleMatrixType; DoubleMatrixType directionMatrix; for( unsigned int i = 0; i < inputImageDimension; i++ ) { for( unsigned int j = 0; j < inputImageDimension; j++ ) { directionMatrix[j][i] = direction2[i][j]; } } EncapsulateMetaData< DoubleMatrixType >( dictionary, ITK_ZDirection, directionMatrix ); } } writer->SetFileName( m_FileNames[slice].c_str() ); writer->SetUseCompression(m_UseCompression); writer->Update(); progress.CompletedPixel(); offset += pixelsPerFile; } } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Image IO: "; if ( m_ImageIO.IsNull() ) { os << "(none)\n"; } else { os << m_ImageIO << "\n"; } os << indent << "StartIndex: " << m_StartIndex << std::endl; os << indent << "IncrementIndex: " << m_IncrementIndex << std::endl; os << indent << "SeriesFormat: " << m_SeriesFormat << std::endl; os << indent << "MetaDataDictionaryArray: " << m_MetaDataDictionaryArray << std::endl; if ( m_UseCompression ) { os << indent << "Compression: On\n"; } else { os << indent << "Compression: Off\n"; } } } // end namespace itk #endif <commit_msg>COMP: Fix unsafe usage of sprintf<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. * *=========================================================================*/ #ifndef __itkImageSeriesWriter_hxx #define __itkImageSeriesWriter_hxx #include "itkImageSeriesWriter.h" #include "itkDataObject.h" #include "itkImageIOFactory.h" #include "itkIOCommon.h" #include "itkProgressReporter.h" #include "itkImageRegionIterator.h" #include "itkMetaDataObject.h" #include "itkArray.h" #include "vnl/algo/vnl_determinant.h" #include <cstdio> #if defined(_MSC_VER) #define snprintf _snprintf #endif // _MSC_VER namespace itk { //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > ImageSeriesWriter< TInputImage, TOutputImage > ::ImageSeriesWriter(): m_ImageIO(ITK_NULLPTR), m_UserSpecifiedImageIO(false), m_SeriesFormat("%d"), m_StartIndex(1), m_IncrementIndex(1), m_MetaDataDictionaryArray(ITK_NULLPTR) { m_UseCompression = false; } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > ImageSeriesWriter< TInputImage, TOutputImage > ::~ImageSeriesWriter() {} //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::SetInput(const InputImageType *input) { // ProcessObject is not const_correct so this cast is required here. this->ProcessObject::SetNthInput( 0, const_cast< TInputImage * >( input ) ); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > const typename ImageSeriesWriter< TInputImage, TOutputImage >::InputImageType * ImageSeriesWriter< TInputImage, TOutputImage > ::GetInput(void) { return itkDynamicCastInDebugMode< TInputImage * >( this->GetPrimaryInput() ); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > const typename ImageSeriesWriter< TInputImage, TOutputImage >::InputImageType * ImageSeriesWriter< TInputImage, TOutputImage > ::GetInput(unsigned int idx) { return itkDynamicCastInDebugMode< TInputImage * >( this->ProcessObject::GetInput(idx) ); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::Write(void) { const InputImageType *inputImage = this->GetInput(); itkDebugMacro(<< "Writing an image file"); // Make sure input is available if ( inputImage == ITK_NULLPTR ) { itkExceptionMacro(<< "No input to writer!"); } // Make sure the data is up-to-date. // NOTE: this const_cast<> is due to the lack of const-correctness // of the ProcessObject. InputImageType *nonConstImage = const_cast< InputImageType * >( inputImage ); nonConstImage->Update(); // Notify start event observers this->InvokeEvent( StartEvent() ); // Actually do something this->GenerateData(); // Notify end event observers this->InvokeEvent( EndEvent() ); // Release upstream data if requested if ( inputImage->ShouldIReleaseData() ) { nonConstImage->ReleaseData(); } } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::GenerateNumericFileNamesAndWrite(void) { itkWarningMacro("This functionality has been DEPRECATED. Use NumericSeriesFileName for generating the filenames"); this->GenerateNumericFileNames(); this->WriteFiles(); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::GenerateNumericFileNames(void) { const InputImageType *inputImage = this->GetInput(); if ( !inputImage ) { itkExceptionMacro(<< "Input image is NULL"); } m_FileNames.clear(); // We need two regions. One for the input, one for the output. ImageRegion< TInputImage::ImageDimension > inRegion = inputImage->GetRequestedRegion(); SizeValueType fileNumber = this->m_StartIndex; char fileName[IOCommon::ITK_MAXPATHLEN + 1]; // Compute the number of files to be generated unsigned int numberOfFiles = 1; for ( unsigned int n = TOutputImage::ImageDimension; n < TInputImage::ImageDimension; n++ ) { numberOfFiles *= inRegion.GetSize(n); } for ( unsigned int slice = 0; slice < numberOfFiles; slice++ ) { snprintf (fileName, IOCommon::ITK_MAXPATHLEN + 1, m_SeriesFormat.c_str(), fileNumber); m_FileNames.push_back(fileName); fileNumber += this->m_IncrementIndex; } } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::GenerateData(void) { itkDebugMacro(<< "Writing a series of files"); if ( m_FileNames.empty() ) { // this method will be deprecated. It is here only to maintain the old API this->GenerateNumericFileNamesAndWrite(); return; } this->WriteFiles(); } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::WriteFiles() { const InputImageType *inputImage = this->GetInput(); if ( !inputImage ) { itkExceptionMacro(<< "Input image is NULL"); } // We need two regions. One for the input, one for the output. ImageRegion< TInputImage::ImageDimension > inRegion = inputImage->GetRequestedRegion(); ImageRegion< TOutputImage::ImageDimension > outRegion; // The size of the output will match the input sizes, up to the // dimension of the input. for ( unsigned int i = 0; i < TOutputImage::ImageDimension; i++ ) { outRegion.SetSize(i, inputImage->GetRequestedRegion().GetSize()[i]); } // Allocate an image for output and create an iterator for it typename OutputImageType::Pointer outputImage = OutputImageType::New(); outputImage->SetRegions(outRegion); outputImage->Allocate(); ImageRegionIterator< OutputImageType > ot(outputImage, outRegion); // Set the origin and spacing of the output double spacing[TOutputImage::ImageDimension]; double origin[TOutputImage::ImageDimension]; typename TOutputImage::DirectionType direction; for ( unsigned int i = 0; i < TOutputImage::ImageDimension; i++ ) { origin[i] = inputImage->GetOrigin()[i]; spacing[i] = inputImage->GetSpacing()[i]; outRegion.SetSize(i, inputImage->GetRequestedRegion().GetSize()[i]); for ( unsigned int j = 0; j < TOutputImage::ImageDimension; j++ ) { direction[j][i] = inputImage->GetDirection()[j][i]; } } // // Address the fact that when taking a 2x2 sub-matrix from // the direction matrix we may obtain a singular matrix. // A 2x2 orientation can't represent a 3x3 orientation and // therefore, replacing the orientation with an identity // is as arbitrary as any other choice. // if ( vnl_determinant( direction.GetVnlMatrix() ) == 0.0 ) { direction.SetIdentity(); } outputImage->SetOrigin(origin); outputImage->SetSpacing(spacing); outputImage->SetDirection(direction); Index< TInputImage::ImageDimension > inIndex; Size< TInputImage::ImageDimension > inSize; SizeValueType pixelsPerFile = outputImage->GetRequestedRegion().GetNumberOfPixels(); inSize.Fill(1); for ( unsigned int ns = 0; ns < TOutputImage::ImageDimension; ns++ ) { inSize[ns] = outRegion.GetSize()[ns]; } unsigned int expectedNumberOfFiles = 1; for ( unsigned int n = TOutputImage::ImageDimension; n < TInputImage::ImageDimension; n++ ) { expectedNumberOfFiles *= inRegion.GetSize(n); } if ( m_FileNames.size() != expectedNumberOfFiles ) { itkExceptionMacro( << "The number of filenames passed is " << m_FileNames.size() << " but " << expectedNumberOfFiles << " were expected "); return; } itkDebugMacro( << "Number of files to write = " << m_FileNames.size() ); ProgressReporter progress(this, 0, expectedNumberOfFiles, expectedNumberOfFiles); // For each "slice" in the input, copy the region to the output, // build a filename and write the file. typename InputImageType::OffsetValueType offset = 0; for ( unsigned int slice = 0; slice < m_FileNames.size(); slice++ ) { // Select a "slice" of the image. inIndex = inputImage->ComputeIndex(offset); inRegion.SetIndex(inIndex); inRegion.SetSize(inSize); ImageRegionConstIterator< InputImageType > it (inputImage, inRegion); // Copy the selected "slice" into the output image. it.GoToBegin(); ot.GoToBegin(); while ( !ot.IsAtEnd() ) { ot.Set( it.Get() ); ++it; ++ot; } typename WriterType::Pointer writer = WriterType::New(); writer->UseInputMetaDataDictionaryOff(); // use the dictionary from the // ImageIO class writer->SetInput(outputImage); if ( m_ImageIO ) { writer->SetImageIO(m_ImageIO); } if ( m_MetaDataDictionaryArray ) { if ( m_ImageIO ) { if ( slice > m_MetaDataDictionaryArray->size() - 1 ) { itkExceptionMacro ( "The slice number: " << slice + 1 << " exceeds the size of the MetaDataDictionaryArray " << m_MetaDataDictionaryArray->size() << "."); } DictionaryRawPointer dictionary = ( *m_MetaDataDictionaryArray )[slice]; m_ImageIO->SetMetaDataDictionary( ( *dictionary ) ); } else { itkExceptionMacro(<< "Attempted to use a MetaDataDictionaryArray without specifying an ImageIO!"); } } else { if ( m_ImageIO ) { DictionaryType & dictionary = m_ImageIO->GetMetaDataDictionary(); typename InputImageType::SpacingType spacing2 = inputImage->GetSpacing(); // origin of the output slice in the // N-Dimensional space of the input image. typename InputImageType::PointType origin2; inputImage->TransformIndexToPhysicalPoint(inIndex, origin2); const unsigned int inputImageDimension = TInputImage::ImageDimension; typedef Array< double > DoubleArrayType; DoubleArrayType originArray(inputImageDimension); DoubleArrayType spacingArray(inputImageDimension); for ( unsigned int d = 0; d < inputImageDimension; d++ ) { originArray[d] = origin2[d]; spacingArray[d] = spacing2[d]; } EncapsulateMetaData< DoubleArrayType >(dictionary, ITK_Origin, originArray); EncapsulateMetaData< DoubleArrayType >(dictionary, ITK_Spacing, spacingArray); EncapsulateMetaData< unsigned int >(dictionary, ITK_NumberOfDimensions, inputImageDimension); typename InputImageType::DirectionType direction2 = inputImage->GetDirection(); typedef Matrix< double, inputImageDimension, inputImageDimension> DoubleMatrixType; DoubleMatrixType directionMatrix; for( unsigned int i = 0; i < inputImageDimension; i++ ) { for( unsigned int j = 0; j < inputImageDimension; j++ ) { directionMatrix[j][i] = direction2[i][j]; } } EncapsulateMetaData< DoubleMatrixType >( dictionary, ITK_ZDirection, directionMatrix ); } } writer->SetFileName( m_FileNames[slice].c_str() ); writer->SetUseCompression(m_UseCompression); writer->Update(); progress.CompletedPixel(); offset += pixelsPerFile; } } //--------------------------------------------------------- template< typename TInputImage, typename TOutputImage > void ImageSeriesWriter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Image IO: "; if ( m_ImageIO.IsNull() ) { os << "(none)\n"; } else { os << m_ImageIO << "\n"; } os << indent << "StartIndex: " << m_StartIndex << std::endl; os << indent << "IncrementIndex: " << m_IncrementIndex << std::endl; os << indent << "SeriesFormat: " << m_SeriesFormat << std::endl; os << indent << "MetaDataDictionaryArray: " << m_MetaDataDictionaryArray << std::endl; if ( m_UseCompression ) { os << indent << "Compression: On\n"; } else { os << indent << "Compression: Off\n"; } } } // end namespace itk #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CenterViewFocusModule.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2008-04-03 13:37:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_FRAMEWORK_CENTER_VIEW_FOCUS_MODULE_HXX #define SD_FRAMEWORK_CENTER_VIEW_FOCUS_MODULE_HXX #include "MutexOwner.hxx" #include <com/sun/star/drawing/framework/XConfigurationChangeListener.hpp> #include <com/sun/star/drawing/framework/XConfigurationController.hpp> #include <com/sun/star/frame/XController.hpp> #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _CPPUHELPER_COMPBASE1_HXX_ #include <cppuhelper/compbase1.hxx> #endif namespace { typedef ::cppu::WeakComponentImplHelper1 < ::com::sun::star::drawing::framework::XConfigurationChangeListener > CenterViewFocusModuleInterfaceBase; } // end of anonymous namespace. namespace sd { class ViewShellBase; } namespace sd { namespace framework { /** This module waits for new views to be created for the center pane and then moves the center view to the top most place on the shell stack. As we are moving away from the shell stack this module may become obsolete or has to be modified. */ class CenterViewFocusModule : private sd::MutexOwner, public CenterViewFocusModuleInterfaceBase { public: CenterViewFocusModule ( ::com::sun::star::uno::Reference<com::sun::star::frame::XController>& rxController); virtual ~CenterViewFocusModule (void); virtual void SAL_CALL disposing (void); // XConfigurationChangeListener virtual void SAL_CALL notifyConfigurationChange ( const com::sun::star::drawing::framework::ConfigurationChangeEvent& rEvent) throw (com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing ( const com::sun::star::lang::EventObject& rEvent) throw (com::sun::star::uno::RuntimeException); private: class ViewShellContainer; bool mbValid; ::com::sun::star::uno::Reference<com::sun::star::drawing::framework::XConfigurationController> mxConfigurationController; ViewShellBase* mpBase; /** This flag indicates whether in the last configuration change cycle a new view has been created and thus the center view has to be moved to the top of the shell stack. */ bool mbNewViewCreated; /** At the end of an update of the current configuration this method handles a new view in the center pane by moving the associated view shell to the top of the shell stack. */ void HandleNewView( const ::com::sun::star::uno::Reference< com::sun::star::drawing::framework::XConfiguration>& rxConfiguration); }; } } // end of namespace sd::framework #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.234); FILE MERGED 2008/04/01 15:34:27 thb 1.2.234.3: #i85898# Stripping all external header guards 2008/04/01 12:38:48 thb 1.2.234.2: #i85898# Stripping all external header guards 2008/03/31 13:58:01 rt 1.2.234.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: CenterViewFocusModule.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 SD_FRAMEWORK_CENTER_VIEW_FOCUS_MODULE_HXX #define SD_FRAMEWORK_CENTER_VIEW_FOCUS_MODULE_HXX #include "MutexOwner.hxx" #include <com/sun/star/drawing/framework/XConfigurationChangeListener.hpp> #include <com/sun/star/drawing/framework/XConfigurationController.hpp> #include <com/sun/star/frame/XController.hpp> #include <osl/mutex.hxx> #include <cppuhelper/compbase1.hxx> namespace { typedef ::cppu::WeakComponentImplHelper1 < ::com::sun::star::drawing::framework::XConfigurationChangeListener > CenterViewFocusModuleInterfaceBase; } // end of anonymous namespace. namespace sd { class ViewShellBase; } namespace sd { namespace framework { /** This module waits for new views to be created for the center pane and then moves the center view to the top most place on the shell stack. As we are moving away from the shell stack this module may become obsolete or has to be modified. */ class CenterViewFocusModule : private sd::MutexOwner, public CenterViewFocusModuleInterfaceBase { public: CenterViewFocusModule ( ::com::sun::star::uno::Reference<com::sun::star::frame::XController>& rxController); virtual ~CenterViewFocusModule (void); virtual void SAL_CALL disposing (void); // XConfigurationChangeListener virtual void SAL_CALL notifyConfigurationChange ( const com::sun::star::drawing::framework::ConfigurationChangeEvent& rEvent) throw (com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing ( const com::sun::star::lang::EventObject& rEvent) throw (com::sun::star::uno::RuntimeException); private: class ViewShellContainer; bool mbValid; ::com::sun::star::uno::Reference<com::sun::star::drawing::framework::XConfigurationController> mxConfigurationController; ViewShellBase* mpBase; /** This flag indicates whether in the last configuration change cycle a new view has been created and thus the center view has to be moved to the top of the shell stack. */ bool mbNewViewCreated; /** At the end of an update of the current configuration this method handles a new view in the center pane by moving the associated view shell to the top of the shell stack. */ void HandleNewView( const ::com::sun::star::uno::Reference< com::sun::star::drawing::framework::XConfiguration>& rxConfiguration); }; } } // end of namespace sd::framework #endif <|endoftext|>
<commit_before>#include <boost/filesystem/operations.hpp> #include <catch/catch.hpp> #include <pjsettings-pugixml.h> #include <pjsua2/endpoint.hpp> #include <iostream> #include "SimpleClass.h" using namespace pj; using namespace pjsettings; SCENARIO("pugixml from string") { const char *xmlString = "" "<?xml version=\"1.0\"?>\n" "<root intValue=\"14\"\n" " stringValue=\"string\"\n" " doubleValue=\"2.5\"\n" " trueBool=\"true\"\n" " falseBool=\"false\"\n" " >\n" " <simpleClass intValue=\"15\"\n" " stringValue=\"string\" />\n" " <stringsArray>\n" " <add>string</add>\n" " <add>other string</add>\n" " </stringsArray>\n" " <boolArray>" " <add>true</add>" " <add>false</add>" " </boolArray>\n" " <simpleClassArray>\n" " <add intValue=\"16\" />\n" " <add intValue=\"17\" />\n" " </simpleClassArray>\n" " <simpleContainer>\n" " <simpleClass intValue=\"18\" />\n" " </simpleContainer>\n" " <intArray>\n" " <add>19</add>\n" " <add>20</add>\n" " </intArray>\n" " <arrayOfStringVectors>\n" " <vector>\n" " <add>first</add>\n" " <add>second</add>\n" " </vector>\n" " <vector>\n" " <add>third</add>\n" " <add>fourth</add>\n" " </vector>\n" " </arrayOfStringVectors>\n" "</root>"; PjPugixmlDocument doc; try { doc.loadString(xmlString); } catch (Error &err) { std::cerr << err.info(true) << std::endl; throw; } SECTION("read simple data types") { ContainerNode &node = doc.getRootContainer(); SECTION("read integer") { int intValue; NODE_READ_INT(node, intValue); CHECK(14 == intValue); } SECTION("read double") { double doubleValue; NODE_READ_FLOAT(node, doubleValue); CHECK(2.5 == doubleValue); } SECTION("read string") { std::string stringValue; NODE_READ_STRING(node, stringValue); CHECK("string" == stringValue); } WHEN("read bool") { THEN("true bool") { bool trueBool = false; NODE_READ_BOOL(node, trueBool); CHECK(true == trueBool); } THEN("false bool") { bool falseBool = true; NODE_READ_BOOL(node, falseBool); CHECK(false == falseBool); } } SECTION("read string vector") { StringVector stringsArray; NODE_READ_STRINGV(node, stringsArray); REQUIRE(2 == stringsArray.size()); CHECK("string" == stringsArray[0]); CHECK("other string" == stringsArray[1]); } } SECTION("read from array") { SECTION("read array of objects") { ContainerNode arrayNode = doc.readArray("simpleClassArray"); std::vector<SimpleClass> data; while (arrayNode.hasUnread()) { SimpleClass obj("simpleClass"); arrayNode.readObject(obj); data.push_back(obj); } REQUIRE(2 == data.size()); CHECK(data[0].intValue == 16); CHECK(data[1].intValue == 17); } SECTION("read int array") { ContainerNode arrayNode = doc.readArray("intArray"); std::vector<int> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readInt()); } REQUIRE(2 == data.size()); CHECK(data[0] == 19); CHECK(data[1] == 20); } SECTION("read string array") { ContainerNode arrayNode = doc.readArray("stringsArray"); std::vector<std::string> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readString()); } REQUIRE(2 == data.size()); CHECK("string" == data[0]); CHECK("other string" == data[1]); } SECTION("read bool array") { ContainerNode arrayNode = doc.readArray("boolArray"); std::vector<bool> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readBool()); } REQUIRE(2 == data.size()); CHECK(true == data[0]); CHECK(false == data[1]); } SECTION("read StringVector array") { ContainerNode arrayNode = doc.readArray("arrayOfStringVectors"); std::vector<StringVector> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readStringVector()); } REQUIRE(2 == data.size()); CHECK(data[0].size() == 2); CHECK(data[0][0] == "first"); CHECK(data[0][1] == "second"); CHECK(data[1].size() == 2); CHECK(data[1][0] == "third"); CHECK(data[1][1] == "fourth"); } SECTION("read array in array") { ContainerNode arrayNode = doc.readArray("arrayOfStringVectors"); std::vector<std::string> data; while (arrayNode.hasUnread()) { ContainerNode subNode = arrayNode.readArray("vector"); while (subNode.hasUnread()) { data.push_back(subNode.readString("add")); } } REQUIRE(4 == data.size()); CHECK(data[0] == "first"); CHECK(data[1] == "second"); CHECK(data[2] == "third"); CHECK(data[3] == "fourth"); } } SECTION("read object") { SimpleClass simpleClass("simpleClass"); doc.readObject(simpleClass); CHECK(simpleClass.intValue == 15); CHECK(simpleClass.stringValue == "string"); } SECTION("read container") { ContainerNode node = doc.readContainer("simpleContainer"); SimpleClass simpleClass("simpleClass"); node.readObject(simpleClass); CHECK(simpleClass.intValue == 18); } } SCENARIO("pugixml read pjsip LogConfig") { SECTION("read ordered config values") { const char *xmlString = "" "<root>\n" " <LogConfig msgLogging=\"1\"\n" " level=\"5\"\n" " consoleLevel=\"4\"\n" " decor=\"25328\"\n" " filename=\"pjsip.log\"\n" " fileFlags=\"0\"\n" " >" " </LogConfig>" "</root>"; PjPugixmlDocument doc; doc.loadString(xmlString); LogConfig config; doc.readObject(config); CHECK(1 == config.msgLogging); CHECK(5 == config.level); CHECK(4 == config.consoleLevel); CHECK("pjsip.log" == config.filename); } SECTION("read unordered config values") { const char *xmlString = "<root>\n" " <LogConfig\n" " filename=\"pjsip.log\"\n" " level=\"5\"\n" " consoleLevel=\"4\"\n" " >" " </LogConfig>\n" "</root>"; PjPugixmlDocument doc; doc.loadString(xmlString); LogConfig config; doc.readObject(config); CHECK(5 == config.level); CHECK(4 == config.consoleLevel); CHECK("pjsip.log" == config.filename); } } SCENARIO("pugixml from file") { const char *filename = "test-config-pugixml.xml"; PjPugixmlDocument doc; doc.loadFile(filename); LogConfig config; doc.readObject(config); CHECK(5 == config.level); CHECK(4 == config.consoleLevel); CHECK("pjsip.log" == config.filename); } bool contains_string(PjPugixmlDocument &doc, const std::string &search) { std::string result = doc.saveString(); bool expression = result.find(search) != std::string::npos; if (!expression) { std::cout << "substring " << search << " not found in serialized document:" << std::endl << result << std::endl; } return expression; } SCENARIO("pugixml to string") { PjPugixmlDocument doc; SECTION("write simple data types") { ContainerNode &node = doc.getRootContainer(); SECTION("write integer") { int intValue = 14; NODE_WRITE_INT(node, intValue); CHECK(contains_string(doc, "intValue=\"14\"")); } SECTION("write double") { double doubleValue = 2.5; NODE_WRITE_FLOAT(node, doubleValue); CHECK(contains_string(doc, "doubleValue=\"2.5\"")); } SECTION("write string") { std::string stringValue = "string"; NODE_WRITE_STRING(node, stringValue); CHECK(contains_string(doc, "stringValue=\"string\"")); } WHEN("write bool") { THEN("true bool") { bool trueBool = true; NODE_WRITE_BOOL(node, trueBool); CHECK(contains_string(doc, "trueBool=\"true\"")); } THEN("false bool") { bool falseBool = false; NODE_WRITE_BOOL(node, falseBool); CHECK(contains_string(doc, "falseBool=\"false\"")); } } SECTION("write string vector") { StringVector stringsArray; stringsArray.push_back("string"); stringsArray.push_back("other string"); NODE_WRITE_STRINGV(node, stringsArray); CHECK(contains_string(doc, "<stringsArray>")); CHECK(contains_string(doc, "<item>string</item>")); CHECK(contains_string(doc, "<item>other string</item>")); CHECK(contains_string(doc, "</stringsArray>")); } SECTION("write container") { ContainerNode node = doc.writeNewContainer("simpleContainer"); WHEN("empty container") { CHECK(contains_string(doc, "<simpleContainer />")); } WHEN("one attribute") { node.writeInt("intValue", 21); CHECK(contains_string(doc, "<simpleContainer intValue=\"21\" />")); } WHEN("container inside") { node.writeNewContainer("subContainer"); CHECK(contains_string(doc, "<simpleContainer>")); CHECK(contains_string(doc, "<subContainer />")); CHECK(contains_string(doc, "</simpleContainer>")); } WHEN("array inside") { node.writeNewArray("subArray"); CHECK(contains_string(doc, "<simpleContainer>")); CHECK(contains_string(doc, "<subArray />")); CHECK(contains_string(doc, "</simpleContainer>")); } } SECTION("write object") { SimpleClass simpleClass("simpleClass", 15, "string"); doc.writeObject(simpleClass); CHECK(contains_string(doc, "<simpleClass")); CHECK(contains_string(doc, "intValue=\"15\"")); CHECK(contains_string(doc, "stringValue=\"string\"")); CHECK(contains_string(doc, "/>")); } } SECTION("write to array") { ContainerNode arrayNode = doc.writeNewArray("arrayNode"); SECTION("empty array") { CHECK(contains_string(doc, "<arrayNode />")); } SECTION("write int to array") { arrayNode.writeInt("int", 19); CHECK(contains_string(doc, "<item>19</item>")); } SECTION("write double to array") { arrayNode.writeNumber("float", 2.5); CHECK(contains_string(doc, "<item>2.5</item>")); } SECTION("write string to array") { arrayNode.writeString("string", "some string"); CHECK(contains_string(doc, "<item>some string</item>")); } SECTION("write bool to array") { WHEN("true bool") { arrayNode.writeBool("boolean", true); CHECK(contains_string(doc, "<item>true</item>")); } WHEN("false bool") { arrayNode.writeBool("boolean", false); CHECK(contains_string(doc, "<item>false</item>")); } } SECTION("write StringVector to array") { StringVector s1; s1.push_back("first"); s1.push_back("second"); arrayNode.writeStringVector("stringVector", s1); CHECK(contains_string(doc, "<stringVector>")); CHECK(contains_string(doc, "</stringVector>")); CHECK(contains_string(doc, "<item>first</item>")); CHECK(contains_string(doc, "<item>second</item>")); } SECTION("write container to array") { arrayNode.writeNewContainer("simple"); CHECK(contains_string(doc, "<simple />")); } SECTION("write object to array") { SimpleClass simpleClass("simple", 16); arrayNode.writeObject(simpleClass); CHECK(contains_string(doc, "<simple intValue=\"16\"")); } SECTION("write array in array") { ContainerNode subArray = arrayNode.writeNewArray("subArray"); subArray.writeInt("int", 20); CHECK(contains_string(doc, "<subArray>")); CHECK(contains_string(doc, "</subArray>")); CHECK(contains_string(doc, "<item>20</item>")); } } } SCENARIO("pugixml write pjsip LogConfig") { LogConfig config; config.filename = "pjsip.log"; config.consoleLevel = 1; config.level = 2; PjPugixmlDocument doc; doc.writeObject(config); SECTION("write to string") { std::string savedString = doc.saveString(); size_t npos = std::string::npos; CHECK(savedString.find("<root>") != npos); CHECK(savedString.find("</root>") != npos); CHECK(savedString.find("LogConfig") != npos); CHECK(savedString.find("filename=\"pjsip.log\"") != npos); CHECK(savedString.find("consoleLevel=\"1\"") != npos); CHECK(savedString.find("level=\"2\"") != npos); } SECTION("write to file") { using namespace boost::filesystem; char const *filename = "test-save-LogConfig-to-file.xml"; remove(filename); CHECK(!exists(filename)); doc.saveFile(filename); REQUIRE(exists(filename)); } } <commit_msg>add pugixml tag to tests with pugixml backend<commit_after>#include <boost/filesystem/operations.hpp> #include <catch/catch.hpp> #include <pjsettings-pugixml.h> #include <pjsua2/endpoint.hpp> #include <iostream> #include "SimpleClass.h" using namespace pj; using namespace pjsettings; SCENARIO("pugixml from string", "[pugixml]") { const char *xmlString = "" "<?xml version=\"1.0\"?>\n" "<root intValue=\"14\"\n" " stringValue=\"string\"\n" " doubleValue=\"2.5\"\n" " trueBool=\"true\"\n" " falseBool=\"false\"\n" " >\n" " <simpleClass intValue=\"15\"\n" " stringValue=\"string\" />\n" " <stringsArray>\n" " <add>string</add>\n" " <add>other string</add>\n" " </stringsArray>\n" " <boolArray>" " <add>true</add>" " <add>false</add>" " </boolArray>\n" " <simpleClassArray>\n" " <add intValue=\"16\" />\n" " <add intValue=\"17\" />\n" " </simpleClassArray>\n" " <simpleContainer>\n" " <simpleClass intValue=\"18\" />\n" " </simpleContainer>\n" " <intArray>\n" " <add>19</add>\n" " <add>20</add>\n" " </intArray>\n" " <arrayOfStringVectors>\n" " <vector>\n" " <add>first</add>\n" " <add>second</add>\n" " </vector>\n" " <vector>\n" " <add>third</add>\n" " <add>fourth</add>\n" " </vector>\n" " </arrayOfStringVectors>\n" "</root>"; PjPugixmlDocument doc; try { doc.loadString(xmlString); } catch (Error &err) { std::cerr << err.info(true) << std::endl; throw; } SECTION("read simple data types") { ContainerNode &node = doc.getRootContainer(); SECTION("read integer") { int intValue; NODE_READ_INT(node, intValue); CHECK(14 == intValue); } SECTION("read double") { double doubleValue; NODE_READ_FLOAT(node, doubleValue); CHECK(2.5 == doubleValue); } SECTION("read string") { std::string stringValue; NODE_READ_STRING(node, stringValue); CHECK("string" == stringValue); } WHEN("read bool") { THEN("true bool") { bool trueBool = false; NODE_READ_BOOL(node, trueBool); CHECK(true == trueBool); } THEN("false bool") { bool falseBool = true; NODE_READ_BOOL(node, falseBool); CHECK(false == falseBool); } } SECTION("read string vector") { StringVector stringsArray; NODE_READ_STRINGV(node, stringsArray); REQUIRE(2 == stringsArray.size()); CHECK("string" == stringsArray[0]); CHECK("other string" == stringsArray[1]); } } SECTION("read from array") { SECTION("read array of objects") { ContainerNode arrayNode = doc.readArray("simpleClassArray"); std::vector<SimpleClass> data; while (arrayNode.hasUnread()) { SimpleClass obj("simpleClass"); arrayNode.readObject(obj); data.push_back(obj); } REQUIRE(2 == data.size()); CHECK(data[0].intValue == 16); CHECK(data[1].intValue == 17); } SECTION("read int array") { ContainerNode arrayNode = doc.readArray("intArray"); std::vector<int> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readInt()); } REQUIRE(2 == data.size()); CHECK(data[0] == 19); CHECK(data[1] == 20); } SECTION("read string array") { ContainerNode arrayNode = doc.readArray("stringsArray"); std::vector<std::string> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readString()); } REQUIRE(2 == data.size()); CHECK("string" == data[0]); CHECK("other string" == data[1]); } SECTION("read bool array") { ContainerNode arrayNode = doc.readArray("boolArray"); std::vector<bool> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readBool()); } REQUIRE(2 == data.size()); CHECK(true == data[0]); CHECK(false == data[1]); } SECTION("read StringVector array") { ContainerNode arrayNode = doc.readArray("arrayOfStringVectors"); std::vector<StringVector> data; while (arrayNode.hasUnread()) { data.push_back(arrayNode.readStringVector()); } REQUIRE(2 == data.size()); CHECK(data[0].size() == 2); CHECK(data[0][0] == "first"); CHECK(data[0][1] == "second"); CHECK(data[1].size() == 2); CHECK(data[1][0] == "third"); CHECK(data[1][1] == "fourth"); } SECTION("read array in array") { ContainerNode arrayNode = doc.readArray("arrayOfStringVectors"); std::vector<std::string> data; while (arrayNode.hasUnread()) { ContainerNode subNode = arrayNode.readArray("vector"); while (subNode.hasUnread()) { data.push_back(subNode.readString("add")); } } REQUIRE(4 == data.size()); CHECK(data[0] == "first"); CHECK(data[1] == "second"); CHECK(data[2] == "third"); CHECK(data[3] == "fourth"); } } SECTION("read object") { SimpleClass simpleClass("simpleClass"); doc.readObject(simpleClass); CHECK(simpleClass.intValue == 15); CHECK(simpleClass.stringValue == "string"); } SECTION("read container") { ContainerNode node = doc.readContainer("simpleContainer"); SimpleClass simpleClass("simpleClass"); node.readObject(simpleClass); CHECK(simpleClass.intValue == 18); } } SCENARIO("pugixml read pjsip LogConfig", "[pugixml]") { SECTION("read ordered config values") { const char *xmlString = "" "<root>\n" " <LogConfig msgLogging=\"1\"\n" " level=\"5\"\n" " consoleLevel=\"4\"\n" " decor=\"25328\"\n" " filename=\"pjsip.log\"\n" " fileFlags=\"0\"\n" " >" " </LogConfig>" "</root>"; PjPugixmlDocument doc; doc.loadString(xmlString); LogConfig config; doc.readObject(config); CHECK(1 == config.msgLogging); CHECK(5 == config.level); CHECK(4 == config.consoleLevel); CHECK("pjsip.log" == config.filename); } SECTION("read unordered config values") { const char *xmlString = "<root>\n" " <LogConfig\n" " filename=\"pjsip.log\"\n" " level=\"5\"\n" " consoleLevel=\"4\"\n" " >" " </LogConfig>\n" "</root>"; PjPugixmlDocument doc; doc.loadString(xmlString); LogConfig config; doc.readObject(config); CHECK(5 == config.level); CHECK(4 == config.consoleLevel); CHECK("pjsip.log" == config.filename); } } SCENARIO("pugixml from file", "[pugixml]") { const char *filename = "test-config-pugixml.xml"; PjPugixmlDocument doc; doc.loadFile(filename); LogConfig config; doc.readObject(config); CHECK(5 == config.level); CHECK(4 == config.consoleLevel); CHECK("pjsip.log" == config.filename); } bool contains_string(PjPugixmlDocument &doc, const std::string &search) { std::string result = doc.saveString(); bool expression = result.find(search) != std::string::npos; if (!expression) { std::cout << "substring " << search << " not found in serialized document:" << std::endl << result << std::endl; } return expression; } SCENARIO("pugixml to string", "[pugixml]") { PjPugixmlDocument doc; SECTION("write simple data types") { ContainerNode &node = doc.getRootContainer(); SECTION("write integer") { int intValue = 14; NODE_WRITE_INT(node, intValue); CHECK(contains_string(doc, "intValue=\"14\"")); } SECTION("write double") { double doubleValue = 2.5; NODE_WRITE_FLOAT(node, doubleValue); CHECK(contains_string(doc, "doubleValue=\"2.5\"")); } SECTION("write string") { std::string stringValue = "string"; NODE_WRITE_STRING(node, stringValue); CHECK(contains_string(doc, "stringValue=\"string\"")); } WHEN("write bool") { THEN("true bool") { bool trueBool = true; NODE_WRITE_BOOL(node, trueBool); CHECK(contains_string(doc, "trueBool=\"true\"")); } THEN("false bool") { bool falseBool = false; NODE_WRITE_BOOL(node, falseBool); CHECK(contains_string(doc, "falseBool=\"false\"")); } } SECTION("write string vector") { StringVector stringsArray; stringsArray.push_back("string"); stringsArray.push_back("other string"); NODE_WRITE_STRINGV(node, stringsArray); CHECK(contains_string(doc, "<stringsArray>")); CHECK(contains_string(doc, "<item>string</item>")); CHECK(contains_string(doc, "<item>other string</item>")); CHECK(contains_string(doc, "</stringsArray>")); } SECTION("write container") { ContainerNode node = doc.writeNewContainer("simpleContainer"); WHEN("empty container") { CHECK(contains_string(doc, "<simpleContainer />")); } WHEN("one attribute") { node.writeInt("intValue", 21); CHECK(contains_string(doc, "<simpleContainer intValue=\"21\" />")); } WHEN("container inside") { node.writeNewContainer("subContainer"); CHECK(contains_string(doc, "<simpleContainer>")); CHECK(contains_string(doc, "<subContainer />")); CHECK(contains_string(doc, "</simpleContainer>")); } WHEN("array inside") { node.writeNewArray("subArray"); CHECK(contains_string(doc, "<simpleContainer>")); CHECK(contains_string(doc, "<subArray />")); CHECK(contains_string(doc, "</simpleContainer>")); } } SECTION("write object") { SimpleClass simpleClass("simpleClass", 15, "string"); doc.writeObject(simpleClass); CHECK(contains_string(doc, "<simpleClass")); CHECK(contains_string(doc, "intValue=\"15\"")); CHECK(contains_string(doc, "stringValue=\"string\"")); CHECK(contains_string(doc, "/>")); } } SECTION("write to array") { ContainerNode arrayNode = doc.writeNewArray("arrayNode"); SECTION("empty array") { CHECK(contains_string(doc, "<arrayNode />")); } SECTION("write int to array") { arrayNode.writeInt("int", 19); CHECK(contains_string(doc, "<item>19</item>")); } SECTION("write double to array") { arrayNode.writeNumber("float", 2.5); CHECK(contains_string(doc, "<item>2.5</item>")); } SECTION("write string to array") { arrayNode.writeString("string", "some string"); CHECK(contains_string(doc, "<item>some string</item>")); } SECTION("write bool to array") { WHEN("true bool") { arrayNode.writeBool("boolean", true); CHECK(contains_string(doc, "<item>true</item>")); } WHEN("false bool") { arrayNode.writeBool("boolean", false); CHECK(contains_string(doc, "<item>false</item>")); } } SECTION("write StringVector to array") { StringVector s1; s1.push_back("first"); s1.push_back("second"); arrayNode.writeStringVector("stringVector", s1); CHECK(contains_string(doc, "<stringVector>")); CHECK(contains_string(doc, "</stringVector>")); CHECK(contains_string(doc, "<item>first</item>")); CHECK(contains_string(doc, "<item>second</item>")); } SECTION("write container to array") { arrayNode.writeNewContainer("simple"); CHECK(contains_string(doc, "<simple />")); } SECTION("write object to array") { SimpleClass simpleClass("simple", 16); arrayNode.writeObject(simpleClass); CHECK(contains_string(doc, "<simple intValue=\"16\"")); } SECTION("write array in array") { ContainerNode subArray = arrayNode.writeNewArray("subArray"); subArray.writeInt("int", 20); CHECK(contains_string(doc, "<subArray>")); CHECK(contains_string(doc, "</subArray>")); CHECK(contains_string(doc, "<item>20</item>")); } } } SCENARIO("pugixml write pjsip LogConfig", "[pugixml]") { LogConfig config; config.filename = "pjsip.log"; config.consoleLevel = 1; config.level = 2; PjPugixmlDocument doc; doc.writeObject(config); SECTION("write to string") { std::string savedString = doc.saveString(); size_t npos = std::string::npos; CHECK(savedString.find("<root>") != npos); CHECK(savedString.find("</root>") != npos); CHECK(savedString.find("LogConfig") != npos); CHECK(savedString.find("filename=\"pjsip.log\"") != npos); CHECK(savedString.find("consoleLevel=\"1\"") != npos); CHECK(savedString.find("level=\"2\"") != npos); } SECTION("write to file") { using namespace boost::filesystem; char const *filename = "test-save-LogConfig-to-file.xml"; remove(filename); CHECK(!exists(filename)); doc.saveFile(filename); REQUIRE(exists(filename)); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsFocusManager.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 14:13:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "controller/SlsFocusManager.hxx" #include "controller/SlideSorterController.hxx" #include "model/SlideSorterModel.hxx" #include "model/SlsPageDescriptor.hxx" #include "view/SlideSorterView.hxx" #include "view/SlsLayouter.hxx" #include "Window.hxx" namespace sd { namespace slidesorter { namespace controller { FocusManager::FocusManager (SlideSorterController& rController) : mrController (rController), mnPageIndex (-1), mbPageIsFocused (false) { if (mrController.GetModel().GetPageCount() > 0) mnPageIndex = 0; } FocusManager::~FocusManager (void) { } void FocusManager::MoveFocus (FocusMoveDirection eDirection) { if (mnPageIndex >= 0 && mbPageIsFocused) { HideFocusIndicator (GetFocusedPageDescriptor()); int nColumnCount = mrController.GetView().GetLayouter().GetColumnCount(); switch (eDirection) { case FMD_NONE: if (mnPageIndex >= mrController.GetModel().GetPageCount()) mnPageIndex = mrController.GetModel().GetPageCount() - 1; break; case FMD_LEFT: mnPageIndex -= 1; if (mnPageIndex < 0) mnPageIndex = mrController.GetModel().GetPageCount() - 1; break; case FMD_RIGHT: mnPageIndex += 1; if (mnPageIndex >= mrController.GetModel().GetPageCount()) mnPageIndex = 0; break; case FMD_UP: { int nColumn = mnPageIndex % nColumnCount; mnPageIndex -= nColumnCount; if (mnPageIndex < 0) { // Wrap arround to the bottom row or the one above and // go to the correct column. int nCandidate = mrController.GetModel().GetPageCount()-1; int nCandidateColumn = nCandidate % nColumnCount; if (nCandidateColumn > nColumn) mnPageIndex = nCandidate - (nCandidateColumn-nColumn); else if (nCandidateColumn < nColumn) mnPageIndex = nCandidate - nColumnCount + (nColumn - nCandidateColumn); else mnPageIndex = nCandidate; } } break; case FMD_DOWN: { int nColumn = mnPageIndex % nColumnCount; mnPageIndex += nColumnCount; if (mnPageIndex >= mrController.GetModel().GetPageCount()) { // Wrap arround to the correct column. mnPageIndex = nColumn; } } break; } ShowFocusIndicator (GetFocusedPageDescriptor()); } } void FocusManager::ShowFocus (void) { mbPageIsFocused = true; ShowFocusIndicator (GetFocusedPageDescriptor()); } void FocusManager::HideFocus (void) { mbPageIsFocused = false; HideFocusIndicator (GetFocusedPageDescriptor()); } bool FocusManager::ToggleFocus (void) { if (mnPageIndex >= 0) { if (mbPageIsFocused) HideFocus (); else ShowFocus (); } return mbPageIsFocused; } bool FocusManager::HasFocus (void) const { return mrController.GetView().GetWindow()->HasFocus(); } model::PageDescriptor* FocusManager::GetFocusedPageDescriptor (void) const { return mrController.GetModel().GetPageDescriptor (mnPageIndex); } sal_Int32 FocusManager::GetFocusedPageIndex (void) const { return mnPageIndex; } bool FocusManager::IsFocusShowing (void) const { return HasFocus() && mbPageIsFocused; } void FocusManager::HideFocusIndicator (model::PageDescriptor* pDescriptor) { pDescriptor->RemoveFocus(); mrController.GetView().RequestRepaint (*pDescriptor); } void FocusManager::ShowFocusIndicator (model::PageDescriptor* pDescriptor) { if (pDescriptor != NULL) { pDescriptor->SetFocus (); // Scroll the focused page object into the visible area and repaint // it, so that the focus indicator becomes visible. view::SlideSorterView& rView (mrController.GetView()); mrController.MakeRectangleVisible ( rView.GetPageBoundingBox ( *GetFocusedPageDescriptor(), view::SlideSorterView::CS_MODEL, view::SlideSorterView::BBT_INFO)); mrController.GetView().RequestRepaint (*pDescriptor); } } FocusManager::FocusHider::FocusHider (FocusManager& rManager) : mrManager(rManager), mbFocusVisible(rManager.IsFocusShowing()) { mrManager.HideFocus(); } FocusManager::FocusHider::~FocusHider (void) { if (mbFocusVisible) mrManager.ShowFocus(); } } } } // end of namespace ::sd::slidesorter::controller <commit_msg>INTEGRATION: CWS impress26 (1.2.170); FILE MERGED 2004/12/15 13:15:10 af 1.2.170.1: #i39026# Added FocusPage() method.<commit_after>/************************************************************************* * * $RCSfile: SlsFocusManager.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-13 17:28:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "controller/SlsFocusManager.hxx" #include "controller/SlideSorterController.hxx" #include "model/SlideSorterModel.hxx" #include "model/SlsPageDescriptor.hxx" #include "view/SlideSorterView.hxx" #include "view/SlsLayouter.hxx" #include "Window.hxx" namespace sd { namespace slidesorter { namespace controller { FocusManager::FocusManager (SlideSorterController& rController) : mrController (rController), mnPageIndex (-1), mbPageIsFocused (false) { if (mrController.GetModel().GetPageCount() > 0) mnPageIndex = 0; } FocusManager::~FocusManager (void) { } void FocusManager::MoveFocus (FocusMoveDirection eDirection) { if (mnPageIndex >= 0 && mbPageIsFocused) { HideFocusIndicator (GetFocusedPageDescriptor()); int nColumnCount = mrController.GetView().GetLayouter().GetColumnCount(); switch (eDirection) { case FMD_NONE: if (mnPageIndex >= mrController.GetModel().GetPageCount()) mnPageIndex = mrController.GetModel().GetPageCount() - 1; break; case FMD_LEFT: mnPageIndex -= 1; if (mnPageIndex < 0) mnPageIndex = mrController.GetModel().GetPageCount() - 1; break; case FMD_RIGHT: mnPageIndex += 1; if (mnPageIndex >= mrController.GetModel().GetPageCount()) mnPageIndex = 0; break; case FMD_UP: { int nColumn = mnPageIndex % nColumnCount; mnPageIndex -= nColumnCount; if (mnPageIndex < 0) { // Wrap arround to the bottom row or the one above and // go to the correct column. int nCandidate = mrController.GetModel().GetPageCount()-1; int nCandidateColumn = nCandidate % nColumnCount; if (nCandidateColumn > nColumn) mnPageIndex = nCandidate - (nCandidateColumn-nColumn); else if (nCandidateColumn < nColumn) mnPageIndex = nCandidate - nColumnCount + (nColumn - nCandidateColumn); else mnPageIndex = nCandidate; } } break; case FMD_DOWN: { int nColumn = mnPageIndex % nColumnCount; mnPageIndex += nColumnCount; if (mnPageIndex >= mrController.GetModel().GetPageCount()) { // Wrap arround to the correct column. mnPageIndex = nColumn; } } break; } ShowFocusIndicator (GetFocusedPageDescriptor()); } } void FocusManager::ShowFocus (void) { mbPageIsFocused = true; ShowFocusIndicator (GetFocusedPageDescriptor()); } void FocusManager::HideFocus (void) { mbPageIsFocused = false; HideFocusIndicator (GetFocusedPageDescriptor()); } bool FocusManager::ToggleFocus (void) { if (mnPageIndex >= 0) { if (mbPageIsFocused) HideFocus (); else ShowFocus (); } return mbPageIsFocused; } bool FocusManager::HasFocus (void) const { return mrController.GetView().GetWindow()->HasFocus(); } model::PageDescriptor* FocusManager::GetFocusedPageDescriptor (void) const { return mrController.GetModel().GetPageDescriptor (mnPageIndex); } sal_Int32 FocusManager::GetFocusedPageIndex (void) const { return mnPageIndex; } void FocusManager::FocusPage (sal_Int32 nPageIndex) { if (nPageIndex != mnPageIndex) { // Hide the focus while switching it to the specified page. FocusHider aHider (*this); mnPageIndex = nPageIndex; } } bool FocusManager::IsFocusShowing (void) const { return HasFocus() && mbPageIsFocused; } void FocusManager::HideFocusIndicator (model::PageDescriptor* pDescriptor) { pDescriptor->RemoveFocus(); mrController.GetView().RequestRepaint (*pDescriptor); } void FocusManager::ShowFocusIndicator (model::PageDescriptor* pDescriptor) { if (pDescriptor != NULL) { pDescriptor->SetFocus (); // Scroll the focused page object into the visible area and repaint // it, so that the focus indicator becomes visible. view::SlideSorterView& rView (mrController.GetView()); mrController.MakeRectangleVisible ( rView.GetPageBoundingBox ( *GetFocusedPageDescriptor(), view::SlideSorterView::CS_MODEL, view::SlideSorterView::BBT_INFO)); mrController.GetView().RequestRepaint (*pDescriptor); } } FocusManager::FocusHider::FocusHider (FocusManager& rManager) : mrManager(rManager), mbFocusVisible(rManager.IsFocusShowing()) { mrManager.HideFocus(); } FocusManager::FocusHider::~FocusHider (void) { if (mbFocusVisible) mrManager.ShowFocus(); } } } } // end of namespace ::sd::slidesorter::controller <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsTransferable.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-01-24 14:43: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 SD_SLIDESORTER_TRANSFERABLE_HXX #define SD_SLIDESORTER_TRANSFERABLE_HXX #include "sdxfer.hxx" class SdDrawDocument; namespace sd { class pWorkView; namespace slidesorter { class SlideSorterViewShell; } } namespace sd { namespace slidesorter { namespace controller { /** This class exists to have DragFinished call the correct object: the SlideSorterViewShell instead of the old SlideView. */ class Transferable : public SdTransferable { public: Transferable ( SdDrawDocument* pSrcDoc, ::sd::View* pWorkView, BOOL bInitOnGetData, SlideSorterViewShell* pViewShell); virtual ~Transferable (void); virtual void DragFinished (sal_Int8 nDropAction); private: SlideSorterViewShell* mpViewShell; virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint); }; } } } // end of namespace ::sd::slidesorter::controller #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.536); FILE MERGED 2008/03/31 13:58:48 rt 1.4.536.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: SlsTransferable.hxx,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. * ************************************************************************/ #ifndef SD_SLIDESORTER_TRANSFERABLE_HXX #define SD_SLIDESORTER_TRANSFERABLE_HXX #include "sdxfer.hxx" class SdDrawDocument; namespace sd { class pWorkView; namespace slidesorter { class SlideSorterViewShell; } } namespace sd { namespace slidesorter { namespace controller { /** This class exists to have DragFinished call the correct object: the SlideSorterViewShell instead of the old SlideView. */ class Transferable : public SdTransferable { public: Transferable ( SdDrawDocument* pSrcDoc, ::sd::View* pWorkView, BOOL bInitOnGetData, SlideSorterViewShell* pViewShell); virtual ~Transferable (void); virtual void DragFinished (sal_Int8 nDropAction); private: SlideSorterViewShell* mpViewShell; virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint); }; } } } // end of namespace ::sd::slidesorter::controller #endif <|endoftext|>
<commit_before>#include "gtest/gtest.h" // GTest helpers #include "nomlib/tests/common/UnitTest.hpp" #include <nomlib/graphics.hpp> #include <nomlib/system.hpp> namespace nom { class FontCacheTest: public nom::UnitTest { public: FontCacheTest() { // Enable function call tracing of engine initialization // nom::SDL2Logger::set_logging_priority( NOM_LOG_CATEGORY_TRACE_SYSTEM, nom::LogPriority::NOM_LOG_PRIORITY_VERBOSE ); // Enable initialization status logging // nom::SDL2Logger::set_logging_priority( NOM_LOG_CATEGORY_SYSTEM, nom::LogPriority::NOM_LOG_PRIORITY_INFO ); // Hides non-critical messages that might be generated by functions when // running tests. Generally speaking, only tests that explicitly check for // invalid conditions should be subject to a desire for hiding the logged // messages (for sake of cleanliness). // nom::SDL2Logger::set_logging_priority(NOM_LOG_CATEGORY_APPLICATION, NOM_LOG_PRIORITY_CRITICAL); nom::SDL2Logger::set_logging_priority(NOM, NOM_LOG_PRIORITY_CRITICAL); } virtual ~FontCacheTest() { // ... } virtual void SetUp() override { std::string res_file = this->test_case() + ".json"; ASSERT_TRUE( res_bitmap.load_file(res_file, "bitmap") ) << "Could not resolve 'bitmap' from the resource path in file: " << res_file; ASSERT_TRUE( res_truetype.load_file(res_file, "truetype") ) << "Could not resolve 'truetype' from the resource path in file: " << res_file; ASSERT_TRUE( res_bm.load_file(res_file, "bm") ) << "Could not resolve 'bm' from the resource path in file: " << res_file; } protected: nom::SearchPath res_bitmap; nom::SearchPath res_truetype; nom::SearchPath res_bm; }; TEST_F( FontCacheTest, ResourceCacheAPI ) { ResourceCache<Font> fonts_; File fp; Path p; ASSERT_TRUE( fonts_.append_resource( ResourceFile("LiberationSerif", res_truetype.path() + "LiberationSerif-Regular.ttf", ResourceFile::Type::TrueTypeFont) ) ); ASSERT_TRUE( fonts_.append_resource( ResourceFile("LiberationSerif-Bold", res_truetype.path() + "LiberationSerif-Bold.ttf", ResourceFile::Type::TrueTypeFont) ) ); ASSERT_TRUE( fonts_.append_resource( ResourceFile("VIII", res_bitmap.path()+"VIII.png", ResourceFile::Type::BitmapFont) ) ); ASSERT_TRUE( fonts_.append_resource( ResourceFile("VIII_small", res_bitmap.path()+"VIII_small.png", ResourceFile::Type::BitmapFont) ) ); // Should not exist ASSERT_FALSE( fonts_.append_resource( ResourceFile("IX", res_bitmap.path()+"IX.png", ResourceFile::Type::BitmapFont) ) ); // Should already exist. ASSERT_FALSE( fonts_.append_resource( ResourceFile("VIII", res_bitmap.path()+"VIII.png", ResourceFile::Type::BitmapFont) ) ); ResourceFile res; ASSERT_TRUE( res == ResourceFile::null ); ASSERT_FALSE( res.exists() ); res = fonts_.find_resource("LiberationSerif"); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "LiberationSerif", res.name() ); res = fonts_.find_resource("LiberationSerif-Bold"); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "LiberationSerif-Bold", res.name() ); res = fonts_.find_resource( "VIII" ); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "VIII", res.name() ); res = fonts_.find_resource( "VIII_small" ); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "VIII_small", res.name() ); // Should not exist res = fonts_.find_resource( "IX" ); ASSERT_FALSE( res.exists() ); EXPECT_EQ( "", res.name() ); // NOTE: WindowsOS-specific error "unknown file : error : SEH exception with // code 0xc0000005 thrown in the test body." occurs here if the font cache // size does not match the expected value precisely. // // References: // // 1. https://www.assembla.com/spaces/OpenSurgSim/tickets/13#/activity/ticket: // 2. http://msdn.microsoft.com/library/vstudio/swezty51 // 3. See also: tests/CMakeLists.txt FIXME note regarding err when using 'test' // target under Windows from the command line. EXPECT_EQ( 4, fonts_.size() ); fonts_.clear(); EXPECT_EQ( 0, fonts_.size() ); } TEST_F( FontCacheTest, FontCacheAPI ) { Path p; File fp; nom::RenderWindow window; nom::FontCache cache; // We first need to ensure that the SDL2_ttf extension is initialized, // otherwise we will receive err messages upon trying to load TrueType fonts. nom::init_third_party(0); // Necessary for loading font resources ASSERT_TRUE( window.create( this->test_case(), 0, 0, SDL_WINDOW_HIDDEN ) == true ) << "Could not create nom::RenderWindow object for loading font resources from"; // cache.set_resource_handler( [&] (const ResourceFile& res, IFont* font) { // nom::create_font(res, font); // }); // Add two (2) bitmap fonts to the cache for testing use: ASSERT_TRUE( cache.append_resource( ResourceFile( "VIII", res_bitmap.path()+"VIII.png", ResourceFile::Type::BitmapFont ) ) ) << "Could not insert BitmapFont resource VIII"; ASSERT_TRUE( cache.append_resource( ResourceFile( "VIII_small", res_bitmap.path()+"VIII_small.png", ResourceFile::Type::BitmapFont ) ) ) << "Could not insert BitmapFont resource VIII_small"; // Add two (2) TrueType fonts to the cache for testing use: ASSERT_TRUE( cache.append_resource( ResourceFile( "LiberationSerif", res_truetype.path()+"LiberationSerif-Regular.ttf", ResourceFile::Type::TrueTypeFont ) ) ) << "Could not insert TrueType resource LiberationSerif"; ASSERT_TRUE( cache.append_resource( ResourceFile( "LiberationSerif-Bold", res_truetype.path()+"LiberationSerif-Bold.ttf", ResourceFile::Type::TrueTypeFont ) ) ) << "Could not insert TrueType resource LiberationSerif-Bold"; // Bitmap font tests: nom::Font bfont1 = *cache.load_resource( "VIII" ); nom::Font bfont2 = *cache.load_resource( "VIII_small" ); nom::Font bfont3 = *cache.load_resource( "VIII" ); ASSERT_TRUE( bfont1->valid() ) << "Font resource 1 should be valid"; ASSERT_TRUE( bfont2->valid() ) << "Font resource 2 should be valid"; ASSERT_TRUE( bfont3->valid() ) << "Font resource 3 should be valid"; ASSERT_TRUE( bfont1 == bfont3 ) << "Font resource 1 should be the same as font resource 3"; nom::Text label1; nom::Text label2; label1.set_font( bfont1 ); label2.set_font( bfont3->clone() ); ASSERT_FALSE( label1.font() == label2.font() ) << "bfont1 should **not** be the same as bfont3."; // TrueType font tests: nom::Font bfont4 = *cache.load_resource( "LiberationSerif" ); nom::Font bfont5 = *cache.load_resource( "LiberationSerif" ); ASSERT_TRUE( bfont4->valid() ) << "Font resource 4 should be valid"; ASSERT_TRUE( bfont5->valid() ) << "Font resource 5 should be valid"; ASSERT_TRUE( bfont4 == bfont5 ) << "Font resource 4 should be the same as font resource 5"; nom::Text label3; nom::Text label4; label3.set_font( bfont4 ); label4.set_font( bfont5->clone() ); ASSERT_FALSE( label3.font() == label4.font() ) << "bfont4 should **not** be the same as bfont5"; } } // namespace nom int main( int argc, char** argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); } <commit_msg>FontCacheTest: Fix running test from non-exe dir<commit_after>#include "gtest/gtest.h" // GTest helpers #include "nomlib/tests/common/UnitTest.hpp" #include <nomlib/graphics.hpp> #include <nomlib/system.hpp> namespace nom { class FontCacheTest: public nom::UnitTest { public: FontCacheTest() { // Enable function call tracing of engine initialization // nom::SDL2Logger::set_logging_priority( NOM_LOG_CATEGORY_TRACE_SYSTEM, nom::LogPriority::NOM_LOG_PRIORITY_VERBOSE ); // Enable initialization status logging // nom::SDL2Logger::set_logging_priority( NOM_LOG_CATEGORY_SYSTEM, nom::LogPriority::NOM_LOG_PRIORITY_INFO ); // Hides non-critical messages that might be generated by functions when // running tests. Generally speaking, only tests that explicitly check for // invalid conditions should be subject to a desire for hiding the logged // messages (for sake of cleanliness). // nom::SDL2Logger::set_logging_priority(NOM_LOG_CATEGORY_APPLICATION, NOM_LOG_PRIORITY_CRITICAL); nom::SDL2Logger::set_logging_priority(NOM, NOM_LOG_PRIORITY_CRITICAL); } virtual ~FontCacheTest() { // ... } virtual void SetUp() override { std::string res_file = this->test_case() + ".json"; ASSERT_TRUE( res_bitmap.load_file(res_file, "bitmap") ) << "Could not resolve 'bitmap' from the resource path in file: " << res_file; ASSERT_TRUE( res_truetype.load_file(res_file, "truetype") ) << "Could not resolve 'truetype' from the resource path in file: " << res_file; ASSERT_TRUE( res_bm.load_file(res_file, "bm") ) << "Could not resolve 'bm' from the resource path in file: " << res_file; } protected: nom::SearchPath res_bitmap; nom::SearchPath res_truetype; nom::SearchPath res_bm; }; TEST_F( FontCacheTest, ResourceCacheAPI ) { ResourceCache<Font> fonts_; File fp; Path p; ASSERT_TRUE( fonts_.append_resource( ResourceFile("LiberationSerif", res_truetype.path() + "LiberationSerif-Regular.ttf", ResourceFile::Type::TrueTypeFont) ) ); ASSERT_TRUE( fonts_.append_resource( ResourceFile("LiberationSerif-Bold", res_truetype.path() + "LiberationSerif-Bold.ttf", ResourceFile::Type::TrueTypeFont) ) ); ASSERT_TRUE( fonts_.append_resource( ResourceFile("VIII", res_bitmap.path()+"VIII.png", ResourceFile::Type::BitmapFont) ) ); ASSERT_TRUE( fonts_.append_resource( ResourceFile("VIII_small", res_bitmap.path()+"VIII_small.png", ResourceFile::Type::BitmapFont) ) ); // Should not exist ASSERT_FALSE( fonts_.append_resource( ResourceFile("IX", res_bitmap.path()+"IX.png", ResourceFile::Type::BitmapFont) ) ); // Should already exist. ASSERT_FALSE( fonts_.append_resource( ResourceFile("VIII", res_bitmap.path()+"VIII.png", ResourceFile::Type::BitmapFont) ) ); ResourceFile res; ASSERT_TRUE( res == ResourceFile::null ); ASSERT_FALSE( res.exists() ); res = fonts_.find_resource("LiberationSerif"); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "LiberationSerif", res.name() ); res = fonts_.find_resource("LiberationSerif-Bold"); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "LiberationSerif-Bold", res.name() ); res = fonts_.find_resource( "VIII" ); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "VIII", res.name() ); res = fonts_.find_resource( "VIII_small" ); ASSERT_TRUE( res.exists() ); EXPECT_EQ( "VIII_small", res.name() ); // Should not exist res = fonts_.find_resource( "IX" ); ASSERT_FALSE( res.exists() ); EXPECT_EQ( "", res.name() ); // NOTE: WindowsOS-specific error "unknown file : error : SEH exception with // code 0xc0000005 thrown in the test body." occurs here if the font cache // size does not match the expected value precisely. // // References: // // 1. https://www.assembla.com/spaces/OpenSurgSim/tickets/13#/activity/ticket: // 2. http://msdn.microsoft.com/library/vstudio/swezty51 // 3. See also: tests/CMakeLists.txt FIXME note regarding err when using 'test' // target under Windows from the command line. EXPECT_EQ( 4, fonts_.size() ); fonts_.clear(); EXPECT_EQ( 0, fonts_.size() ); } TEST_F( FontCacheTest, FontCacheAPI ) { Path p; File fp; nom::RenderWindow window; nom::FontCache cache; // We first need to ensure that the SDL2_ttf extension is initialized, // otherwise we will receive err messages upon trying to load TrueType fonts. nom::init_third_party(0); // Necessary for loading font resources ASSERT_TRUE( window.create( this->test_case(), 0, 0, SDL_WINDOW_HIDDEN ) == true ) << "Could not create nom::RenderWindow object for loading font resources from"; // cache.set_resource_handler( [&] (const ResourceFile& res, IFont* font) { // nom::create_font(res, font); // }); // Add two (2) bitmap fonts to the cache for testing use: ASSERT_TRUE( cache.append_resource( ResourceFile( "VIII", res_bitmap.path()+"VIII.png", ResourceFile::Type::BitmapFont ) ) ) << "Could not insert BitmapFont resource VIII"; ASSERT_TRUE( cache.append_resource( ResourceFile( "VIII_small", res_bitmap.path()+"VIII_small.png", ResourceFile::Type::BitmapFont ) ) ) << "Could not insert BitmapFont resource VIII_small"; // Add two (2) TrueType fonts to the cache for testing use: ASSERT_TRUE( cache.append_resource( ResourceFile( "LiberationSerif", res_truetype.path()+"LiberationSerif-Regular.ttf", ResourceFile::Type::TrueTypeFont ) ) ) << "Could not insert TrueType resource LiberationSerif"; ASSERT_TRUE( cache.append_resource( ResourceFile( "LiberationSerif-Bold", res_truetype.path()+"LiberationSerif-Bold.ttf", ResourceFile::Type::TrueTypeFont ) ) ) << "Could not insert TrueType resource LiberationSerif-Bold"; // Bitmap font tests: nom::Font bfont1 = *cache.load_resource( "VIII" ); nom::Font bfont2 = *cache.load_resource( "VIII_small" ); nom::Font bfont3 = *cache.load_resource( "VIII" ); ASSERT_TRUE( bfont1->valid() ) << "Font resource 1 should be valid"; ASSERT_TRUE( bfont2->valid() ) << "Font resource 2 should be valid"; ASSERT_TRUE( bfont3->valid() ) << "Font resource 3 should be valid"; ASSERT_TRUE( bfont1 == bfont3 ) << "Font resource 1 should be the same as font resource 3"; nom::Text label1; nom::Text label2; label1.set_font( bfont1 ); label2.set_font( bfont3->clone() ); ASSERT_FALSE( label1.font() == label2.font() ) << "bfont1 should **not** be the same as bfont3."; // TrueType font tests: nom::Font bfont4 = *cache.load_resource( "LiberationSerif" ); nom::Font bfont5 = *cache.load_resource( "LiberationSerif" ); ASSERT_TRUE( bfont4->valid() ) << "Font resource 4 should be valid"; ASSERT_TRUE( bfont5->valid() ) << "Font resource 5 should be valid"; ASSERT_TRUE( bfont4 == bfont5 ) << "Font resource 4 should be the same as font resource 5"; nom::Text label3; nom::Text label4; label3.set_font( bfont4 ); label4.set_font( bfont5->clone() ); ASSERT_FALSE( label3.font() == label4.font() ) << "bfont4 should **not** be the same as bfont5"; } } // namespace nom int main( int argc, char** argv ) { ::testing::InitGoogleTest( &argc, argv ); // Set the current working directory path to the path leading to this // executable file; used for unit tests that require file-system I/O. if( nom::init( argc, argv ) == false ) { NOM_LOG_CRIT(NOM_LOG_CATEGORY_APPLICATION, "Could not initialize nomlib."); return NOM_EXIT_FAILURE; } atexit(nom::quit); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/gl_surface.h" #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/threading/thread_local.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_implementation.h" namespace gfx { namespace { base::LazyInstance<base::ThreadLocalPointer<GLSurface> >::Leaky current_surface_ = LAZY_INSTANCE_INITIALIZER; } // namespace // static bool GLSurface::InitializeOneOff() { static bool initialized = false; if (initialized) return true; TRACE_EVENT0("gpu", "GLSurface::InitializeOneOff"); std::vector<GLImplementation> allowed_impls; GetAllowedGLImplementations(&allowed_impls); DCHECK(!allowed_impls.empty()); // The default implementation is always the first one in list. GLImplementation impl = allowed_impls[0]; bool fallback_to_osmesa = false; if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseGL)) { std::string requested_implementation_name = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL); if (requested_implementation_name == "any") { fallback_to_osmesa = true; } else if (requested_implementation_name == "swiftshader") { impl = kGLImplementationEGLGLES2; } else { impl = GetNamedGLImplementation(requested_implementation_name); if (std::find(allowed_impls.begin(), allowed_impls.end(), impl) == allowed_impls.end()) { LOG(ERROR) << "Requested GL implementation is not available."; return false; } } } initialized = InitializeGLBindings(impl) && InitializeOneOffInternal(); if (!initialized && fallback_to_osmesa) { ClearGLBindings(); initialized = InitializeGLBindings(kGLImplementationOSMesaGL) && InitializeOneOffInternal(); } if (initialized) { DVLOG(1) << "Using " << GetGLImplementationName(GetGLImplementation()) << " GL implementation."; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableGPUServiceLogging)) InitializeDebugGLBindings(); } return initialized; } GLSurface::GLSurface() {} bool GLSurface::Initialize() { return true; } bool GLSurface::Resize(const gfx::Size& size) { NOTIMPLEMENTED(); return false; } bool GLSurface::DeferDraws() { return false; } std::string GLSurface::GetExtensions() { // Use of GLSurfaceAdapter class means that we can't compare // GetCurrent() and this directly. DCHECK(GetCurrent()->GetHandle() == GetHandle() || GetBackingFrameBufferObject()); return std::string(""); } bool GLSurface::HasExtension(const char* name) { std::string extensions = GetExtensions(); extensions += " "; std::string delimited_name(name); delimited_name += " "; return extensions.find(delimited_name) != std::string::npos; } unsigned int GLSurface::GetBackingFrameBufferObject() { return 0; } bool GLSurface::PostSubBuffer(int x, int y, int width, int height) { return false; } bool GLSurface::OnMakeCurrent(GLContext* context) { return true; } bool GLSurface::SetBackbufferAllocation(bool allocated) { return true; } void GLSurface::SetFrontbufferAllocation(bool allocated) { } void* GLSurface::GetShareHandle() { NOTIMPLEMENTED(); return NULL; } void* GLSurface::GetDisplay() { NOTIMPLEMENTED(); return NULL; } void* GLSurface::GetConfig() { NOTIMPLEMENTED(); return NULL; } unsigned GLSurface::GetFormat() { NOTIMPLEMENTED(); return 0; } VSyncProvider* GLSurface::GetVSyncProvider() { return NULL; } GLSurface* GLSurface::GetCurrent() { return current_surface_.Pointer()->Get(); } GLSurface::~GLSurface() { if (GetCurrent() == this) SetCurrent(NULL); } void GLSurface::SetCurrent(GLSurface* surface) { current_surface_.Pointer()->Set(surface); } bool GLSurface::ExtensionsContain(const char* c_extensions, const char* name) { DCHECK(name); if (!c_extensions) return false; std::string extensions(c_extensions); extensions += " "; std::string delimited_name(name); delimited_name += " "; return extensions.find(delimited_name) != std::string::npos; } GLSurfaceAdapter::GLSurfaceAdapter(GLSurface* surface) : surface_(surface) {} bool GLSurfaceAdapter::Initialize() { return surface_->Initialize(); } void GLSurfaceAdapter::Destroy() { surface_->Destroy(); } bool GLSurfaceAdapter::Resize(const gfx::Size& size) { return surface_->Resize(size); } bool GLSurfaceAdapter::DeferDraws() { return surface_->DeferDraws(); } bool GLSurfaceAdapter::IsOffscreen() { return surface_->IsOffscreen(); } bool GLSurfaceAdapter::SwapBuffers() { return surface_->SwapBuffers(); } bool GLSurfaceAdapter::PostSubBuffer(int x, int y, int width, int height) { return surface_->PostSubBuffer(x, y, width, height); } std::string GLSurfaceAdapter::GetExtensions() { return surface_->GetExtensions(); } gfx::Size GLSurfaceAdapter::GetSize() { return surface_->GetSize(); } void* GLSurfaceAdapter::GetHandle() { return surface_->GetHandle(); } unsigned int GLSurfaceAdapter::GetBackingFrameBufferObject() { return surface_->GetBackingFrameBufferObject(); } bool GLSurfaceAdapter::OnMakeCurrent(GLContext* context) { return surface_->OnMakeCurrent(context); } bool GLSurfaceAdapter::SetBackbufferAllocation(bool allocated) { return surface_->SetBackbufferAllocation(allocated); } void GLSurfaceAdapter::SetFrontbufferAllocation(bool allocated) { surface_->SetFrontbufferAllocation(allocated); } void* GLSurfaceAdapter::GetShareHandle() { return surface_->GetShareHandle(); } void* GLSurfaceAdapter::GetDisplay() { return surface_->GetDisplay(); } void* GLSurfaceAdapter::GetConfig() { return surface_->GetConfig(); } unsigned GLSurfaceAdapter::GetFormat() { return surface_->GetFormat(); } VSyncProvider* GLSurfaceAdapter::GetVSyncProvider() { return surface_->GetVSyncProvider(); } GLSurfaceAdapter::~GLSurfaceAdapter() {} } // namespace gfx <commit_msg>Adjust DCHECK() for being current in GLSurface::GetExtensions().<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/gl_surface.h" #include <algorithm> #include <vector> #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/threading/thread_local.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_implementation.h" namespace gfx { namespace { base::LazyInstance<base::ThreadLocalPointer<GLSurface> >::Leaky current_surface_ = LAZY_INSTANCE_INITIALIZER; } // namespace // static bool GLSurface::InitializeOneOff() { static bool initialized = false; if (initialized) return true; TRACE_EVENT0("gpu", "GLSurface::InitializeOneOff"); std::vector<GLImplementation> allowed_impls; GetAllowedGLImplementations(&allowed_impls); DCHECK(!allowed_impls.empty()); // The default implementation is always the first one in list. GLImplementation impl = allowed_impls[0]; bool fallback_to_osmesa = false; if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseGL)) { std::string requested_implementation_name = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL); if (requested_implementation_name == "any") { fallback_to_osmesa = true; } else if (requested_implementation_name == "swiftshader") { impl = kGLImplementationEGLGLES2; } else { impl = GetNamedGLImplementation(requested_implementation_name); if (std::find(allowed_impls.begin(), allowed_impls.end(), impl) == allowed_impls.end()) { LOG(ERROR) << "Requested GL implementation is not available."; return false; } } } initialized = InitializeGLBindings(impl) && InitializeOneOffInternal(); if (!initialized && fallback_to_osmesa) { ClearGLBindings(); initialized = InitializeGLBindings(kGLImplementationOSMesaGL) && InitializeOneOffInternal(); } if (initialized) { DVLOG(1) << "Using " << GetGLImplementationName(GetGLImplementation()) << " GL implementation."; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableGPUServiceLogging)) InitializeDebugGLBindings(); } return initialized; } GLSurface::GLSurface() {} bool GLSurface::Initialize() { return true; } bool GLSurface::Resize(const gfx::Size& size) { NOTIMPLEMENTED(); return false; } bool GLSurface::DeferDraws() { return false; } std::string GLSurface::GetExtensions() { DCHECK(GLContext::GetCurrent()); DCHECK(GLContext::GetCurrent()->IsCurrent(this)); return std::string(""); } bool GLSurface::HasExtension(const char* name) { std::string extensions = GetExtensions(); extensions += " "; std::string delimited_name(name); delimited_name += " "; return extensions.find(delimited_name) != std::string::npos; } unsigned int GLSurface::GetBackingFrameBufferObject() { return 0; } bool GLSurface::PostSubBuffer(int x, int y, int width, int height) { return false; } bool GLSurface::OnMakeCurrent(GLContext* context) { return true; } bool GLSurface::SetBackbufferAllocation(bool allocated) { return true; } void GLSurface::SetFrontbufferAllocation(bool allocated) { } void* GLSurface::GetShareHandle() { NOTIMPLEMENTED(); return NULL; } void* GLSurface::GetDisplay() { NOTIMPLEMENTED(); return NULL; } void* GLSurface::GetConfig() { NOTIMPLEMENTED(); return NULL; } unsigned GLSurface::GetFormat() { NOTIMPLEMENTED(); return 0; } VSyncProvider* GLSurface::GetVSyncProvider() { return NULL; } GLSurface* GLSurface::GetCurrent() { return current_surface_.Pointer()->Get(); } GLSurface::~GLSurface() { if (GetCurrent() == this) SetCurrent(NULL); } void GLSurface::SetCurrent(GLSurface* surface) { current_surface_.Pointer()->Set(surface); } bool GLSurface::ExtensionsContain(const char* c_extensions, const char* name) { DCHECK(name); if (!c_extensions) return false; std::string extensions(c_extensions); extensions += " "; std::string delimited_name(name); delimited_name += " "; return extensions.find(delimited_name) != std::string::npos; } GLSurfaceAdapter::GLSurfaceAdapter(GLSurface* surface) : surface_(surface) {} bool GLSurfaceAdapter::Initialize() { return surface_->Initialize(); } void GLSurfaceAdapter::Destroy() { surface_->Destroy(); } bool GLSurfaceAdapter::Resize(const gfx::Size& size) { return surface_->Resize(size); } bool GLSurfaceAdapter::DeferDraws() { return surface_->DeferDraws(); } bool GLSurfaceAdapter::IsOffscreen() { return surface_->IsOffscreen(); } bool GLSurfaceAdapter::SwapBuffers() { return surface_->SwapBuffers(); } bool GLSurfaceAdapter::PostSubBuffer(int x, int y, int width, int height) { return surface_->PostSubBuffer(x, y, width, height); } std::string GLSurfaceAdapter::GetExtensions() { return surface_->GetExtensions(); } gfx::Size GLSurfaceAdapter::GetSize() { return surface_->GetSize(); } void* GLSurfaceAdapter::GetHandle() { return surface_->GetHandle(); } unsigned int GLSurfaceAdapter::GetBackingFrameBufferObject() { return surface_->GetBackingFrameBufferObject(); } bool GLSurfaceAdapter::OnMakeCurrent(GLContext* context) { return surface_->OnMakeCurrent(context); } bool GLSurfaceAdapter::SetBackbufferAllocation(bool allocated) { return surface_->SetBackbufferAllocation(allocated); } void GLSurfaceAdapter::SetFrontbufferAllocation(bool allocated) { surface_->SetFrontbufferAllocation(allocated); } void* GLSurfaceAdapter::GetShareHandle() { return surface_->GetShareHandle(); } void* GLSurfaceAdapter::GetDisplay() { return surface_->GetDisplay(); } void* GLSurfaceAdapter::GetConfig() { return surface_->GetConfig(); } unsigned GLSurfaceAdapter::GetFormat() { return surface_->GetFormat(); } VSyncProvider* GLSurfaceAdapter::GetVSyncProvider() { return surface_->GetVSyncProvider(); } GLSurfaceAdapter::~GLSurfaceAdapter() {} } // namespace gfx <|endoftext|>
<commit_before>#include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/display.h> #include <wx/filefn.h> #include <string> #include "MainFrame.hpp" #include "GUI.hpp" #include "misc_ui.hpp" #include "Preset.hpp" // Logging mechanism #include "Log.hpp" namespace Slic3r { namespace GUI { /// Primary initialization and point of entry into the GUI application. /// Calls MainFrame and handles preset loading, etc. bool App::OnInit() { this->SetAppName("Slic3r"); // TODO: Call a logging function with channel GUI, severity info this->notifier = std::unique_ptr<Notifier>(); datadir = decode_path(wxStandardPaths::Get().GetUserDataDir()); wxString enc_datadir = encode_path(datadir); const wxString& slic3r_ini {datadir + "/slic3r.ini"}; const wxString& print_ini {datadir + "/print"}; const wxString& printer_ini {datadir + "/printer"}; const wxString& material_ini {datadir + "/filament"}; // if we don't have a datadir or a slic3r.ini, prompt for wizard. bool run_wizard = (wxDirExists(datadir) && wxFileExists(slic3r_ini)); /* Check to make sure if datadir exists */ for (auto& dir : std::vector<wxString> { enc_datadir, print_ini, printer_ini, material_ini }) { if (wxDirExists(dir)) continue; if (!wxMkdir(dir)) { Slic3r::Log::fatal_error(LogChannel, (_("Slic3r was unable to create its data directory at ")+ dir).ToStdWstring()); } } // TODO: Call a logging function with channel GUI, severity info for datadir path Slic3r::Log::info(LogChannel, (_("Data dir: ") + datadir).ToStdWstring()); if (wxFileExists(slic3r_ini)) { /* my $ini = eval { Slic3r::Config->read_ini("$datadir/slic3r.ini") }; if ($ini) { $last_version = $ini->{_}{version}; $ini->{_}{$_} = $Settings->{_}{$_} for grep !exists $ini->{_}{$_}, keys %{$Settings->{_}}; $Settings = $ini; } delete $Settings->{_}{mode}; # handle legacy */ } this->gui_config->save_settings(); // Load presets this->load_presets(); wxImage::AddHandler(new wxPNGHandler()); MainFrame *frame = new MainFrame( "Slic3r", wxDefaultPosition, wxDefaultSize, this->gui_config); this->SetTopWindow(frame); // Load init bundle // // Run the wizard if we don't have an initial config /* $self->check_version if $self->have_version_check && ($Settings->{_}{version_check} // 1) && (!$Settings->{_}{last_version_check} || (time - $Settings->{_}{last_version_check}) >= 86400); */ // run callback functions during idle on the main frame /* EVT_IDLE($frame, sub { while (my $cb = shift @cb) { $cb->(); } }); */ // Handle custom version check event /* EVT_COMMAND($self, -1, $VERSION_CHECK_EVENT, sub { my ($self, $event) = @_; my ($success, $response, $manual_check) = @{$event->GetData}; if ($success) { if ($response =~ /^obsolete ?= ?([a-z0-9.-]+,)*\Q$Slic3r::VERSION\E(?:,|$)/) { my $res = Wx::MessageDialog->new(undef, "A new version is available. Do you want to open the Slic3r website now?", 'Update', wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_INFORMATION | wxICON_ERROR)->ShowModal; Wx::LaunchDefaultBrowser('http://slic3r.org/') if $res == wxID_YES; } else { Slic3r::GUI::show_info(undef, "You're using the latest version. No updates are available.") if $manual_check; } $Settings->{_}{last_version_check} = time(); $self->save_settings; } else { Slic3r::GUI::show_error(undef, "Failed to check for updates. Try later.") if $manual_check; } }); */ return true; } void App::save_window_pos(const wxTopLevelWindow* window, const wxString& name ) { this->gui_config->window_pos[name] = std::make_tuple<wxPoint, wxSize, bool>( window->GetScreenPosition(), window->GetSize(), window->IsMaximized()); this->gui_config->save_settings(); } void App::restore_window_pos(wxTopLevelWindow* window, const wxString& name ) { try { auto tmp = gui_config->window_pos[name]; const auto& size = std::get<1>(tmp); const auto& pos = std::get<0>(tmp); window->SetSize(size); auto display = wxDisplay().GetClientArea(); if (((pos.x + size.x / 2) < display.GetRight()) && (pos.y + size.y/2 < display.GetBottom())) window->Move(pos); window->Maximize(std::get<2>(tmp)); } catch (std::out_of_range e) { // config was empty } } void App::load_presets() { /* for my $group (qw(printer filament print)) { my $presets = $self->{presets}{$group}; # keep external or dirty presets @$presets = grep { ($_->external && $_->file_exists) || $_->dirty } @$presets; my $dir = "$Slic3r::GUI::datadir/$group"; opendir my $dh, Slic3r::encode_path($dir) or die "Failed to read directory $dir (errno: $!)\n"; foreach my $file (grep /\.ini$/i, readdir $dh) { $file = Slic3r::decode_path($file); my $name = basename($file); $name =~ s/\.ini$//i; # skip if we already have it next if any { $_->name eq $name } @$presets; push @$presets, Slic3r::GUI::Preset->new( group => $group, name => $name, file => "$dir/$file", ); } closedir $dh; @$presets = sort { $a->name cmp $b->name } @$presets; unshift @$presets, Slic3r::GUI::Preset->new( group => $group, default => 1, name => '- default -', ); } */ } }} // namespace Slic3r::GUI <commit_msg>added descriptive comment to GUI<commit_after>#include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/display.h> #include <wx/filefn.h> #include <string> #include "MainFrame.hpp" #include "GUI.hpp" #include "misc_ui.hpp" #include "Preset.hpp" // Logging mechanism #include "Log.hpp" namespace Slic3r { namespace GUI { /// Primary initialization and point of entry into the GUI application. /// Calls MainFrame and handles preset loading, etc. bool App::OnInit() { this->SetAppName("Slic3r"); // TODO: Call a logging function with channel GUI, severity info this->notifier = std::unique_ptr<Notifier>(); datadir = decode_path(wxStandardPaths::Get().GetUserDataDir()); wxString enc_datadir = encode_path(datadir); const wxString& slic3r_ini {datadir + "/slic3r.ini"}; const wxString& print_ini {datadir + "/print"}; const wxString& printer_ini {datadir + "/printer"}; const wxString& material_ini {datadir + "/filament"}; // if we don't have a datadir or a slic3r.ini, prompt for wizard. bool run_wizard = (wxDirExists(datadir) && wxFileExists(slic3r_ini)); /* Check to make sure if datadir exists */ for (auto& dir : std::vector<wxString> { enc_datadir, print_ini, printer_ini, material_ini }) { if (wxDirExists(dir)) continue; if (!wxMkdir(dir)) { Slic3r::Log::fatal_error(LogChannel, (_("Slic3r was unable to create its data directory at ")+ dir).ToStdWstring()); } } // TODO: Call a logging function with channel GUI, severity info for datadir path Slic3r::Log::info(LogChannel, (_("Data dir: ") + datadir).ToStdWstring()); // Load gui settings from slic3r.ini if (wxFileExists(slic3r_ini)) { /* my $ini = eval { Slic3r::Config->read_ini("$datadir/slic3r.ini") }; if ($ini) { $last_version = $ini->{_}{version}; $ini->{_}{$_} = $Settings->{_}{$_} for grep !exists $ini->{_}{$_}, keys %{$Settings->{_}}; $Settings = $ini; } delete $Settings->{_}{mode}; # handle legacy */ } this->gui_config->save_settings(); // Load presets this->load_presets(); wxImage::AddHandler(new wxPNGHandler()); MainFrame *frame = new MainFrame( "Slic3r", wxDefaultPosition, wxDefaultSize, this->gui_config); this->SetTopWindow(frame); // Load init bundle // // Run the wizard if we don't have an initial config /* $self->check_version if $self->have_version_check && ($Settings->{_}{version_check} // 1) && (!$Settings->{_}{last_version_check} || (time - $Settings->{_}{last_version_check}) >= 86400); */ // run callback functions during idle on the main frame /* EVT_IDLE($frame, sub { while (my $cb = shift @cb) { $cb->(); } }); */ // Handle custom version check event /* EVT_COMMAND($self, -1, $VERSION_CHECK_EVENT, sub { my ($self, $event) = @_; my ($success, $response, $manual_check) = @{$event->GetData}; if ($success) { if ($response =~ /^obsolete ?= ?([a-z0-9.-]+,)*\Q$Slic3r::VERSION\E(?:,|$)/) { my $res = Wx::MessageDialog->new(undef, "A new version is available. Do you want to open the Slic3r website now?", 'Update', wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_INFORMATION | wxICON_ERROR)->ShowModal; Wx::LaunchDefaultBrowser('http://slic3r.org/') if $res == wxID_YES; } else { Slic3r::GUI::show_info(undef, "You're using the latest version. No updates are available.") if $manual_check; } $Settings->{_}{last_version_check} = time(); $self->save_settings; } else { Slic3r::GUI::show_error(undef, "Failed to check for updates. Try later.") if $manual_check; } }); */ return true; } void App::save_window_pos(const wxTopLevelWindow* window, const wxString& name ) { this->gui_config->window_pos[name] = std::make_tuple<wxPoint, wxSize, bool>( window->GetScreenPosition(), window->GetSize(), window->IsMaximized()); this->gui_config->save_settings(); } void App::restore_window_pos(wxTopLevelWindow* window, const wxString& name ) { try { auto tmp = gui_config->window_pos[name]; const auto& size = std::get<1>(tmp); const auto& pos = std::get<0>(tmp); window->SetSize(size); auto display = wxDisplay().GetClientArea(); if (((pos.x + size.x / 2) < display.GetRight()) && (pos.y + size.y/2 < display.GetBottom())) window->Move(pos); window->Maximize(std::get<2>(tmp)); } catch (std::out_of_range e) { // config was empty } } void App::load_presets() { /* for my $group (qw(printer filament print)) { my $presets = $self->{presets}{$group}; # keep external or dirty presets @$presets = grep { ($_->external && $_->file_exists) || $_->dirty } @$presets; my $dir = "$Slic3r::GUI::datadir/$group"; opendir my $dh, Slic3r::encode_path($dir) or die "Failed to read directory $dir (errno: $!)\n"; foreach my $file (grep /\.ini$/i, readdir $dh) { $file = Slic3r::decode_path($file); my $name = basename($file); $name =~ s/\.ini$//i; # skip if we already have it next if any { $_->name eq $name } @$presets; push @$presets, Slic3r::GUI::Preset->new( group => $group, name => $name, file => "$dir/$file", ); } closedir $dh; @$presets = sort { $a->name cmp $b->name } @$presets; unshift @$presets, Slic3r::GUI::Preset->new( group => $group, default => 1, name => '- default -', ); } */ } }} // namespace Slic3r::GUI <|endoftext|>
<commit_before><commit_msg>Trace RenderWidget methods triggered by WillBeginCompositorFrame<commit_after><|endoftext|>
<commit_before>#include "catalog_counters.h" #include "directory_entry.h" using namespace catalog; void DeltaCounters::ApplyDelta(const DirectoryEntry &dirent, const int delta) { if (dirent.IsRegular()) { self.regular_files += delta; if (dirent.IsChunkedFile()) { self.chunked_files += delta; } } else if (dirent.IsLink()) self.symlinks += delta; else if (dirent.IsDirectory()) self.directories += delta; else assert(false); } void DeltaCounters::PopulateToParent(DeltaCounters &parent) const { parent.subtree.Add(self); parent.subtree.Add(subtree); } void Counters::ApplyDelta(const DeltaCounters &delta) { self.Add(delta.self); subtree.Add(delta.subtree); } void Counters::AddAsSubtree(DeltaCounters &delta) const { delta.subtree.Add(self); delta.subtree.Add(subtree); } void Counters::MergeIntoParent(DeltaCounters &parent_delta) const { parent_delta.self.Add(self); parent_delta.subtree.Subtract(self); } uint64_t Counters::GetSelfEntries() const { return self.regular_files + self.symlinks + self.directories; } uint64_t Counters::GetSubtreeEntries() const { return subtree.regular_files + subtree.symlinks + subtree.directories; } uint64_t Counters::GetAllEntries() const { return GetSelfEntries() + GetSubtreeEntries(); } <commit_msg>add missing file header<commit_after>/** * This file is part of the CernVM File System. */ #include "catalog_counters.h" #include "directory_entry.h" using namespace catalog; void DeltaCounters::ApplyDelta(const DirectoryEntry &dirent, const int delta) { if (dirent.IsRegular()) { self.regular_files += delta; if (dirent.IsChunkedFile()) { self.chunked_files += delta; } } else if (dirent.IsLink()) self.symlinks += delta; else if (dirent.IsDirectory()) self.directories += delta; else assert(false); } void DeltaCounters::PopulateToParent(DeltaCounters &parent) const { parent.subtree.Add(self); parent.subtree.Add(subtree); } void Counters::ApplyDelta(const DeltaCounters &delta) { self.Add(delta.self); subtree.Add(delta.subtree); } void Counters::AddAsSubtree(DeltaCounters &delta) const { delta.subtree.Add(self); delta.subtree.Add(subtree); } void Counters::MergeIntoParent(DeltaCounters &parent_delta) const { parent_delta.self.Add(self); parent_delta.subtree.Subtract(self); } uint64_t Counters::GetSelfEntries() const { return self.regular_files + self.symlinks + self.directories; } uint64_t Counters::GetSubtreeEntries() const { return subtree.regular_files + subtree.symlinks + subtree.directories; } uint64_t Counters::GetAllEntries() const { return GetSelfEntries() + GetSubtreeEntries(); } <|endoftext|>
<commit_before>#pragma once #include "privileged.h" #include "serialize.hpp" #include "types.h" namespace eosio { struct blockchain_parameters { uint32_t base_per_transaction_net_usage; uint32_t base_per_transaction_cpu_usage; uint32_t base_per_action_cpu_usage; uint32_t base_setcode_cpu_usage; uint32_t per_signature_cpu_usage; uint32_t per_lock_net_usage; uint64_t context_free_discount_cpu_usage_num; uint64_t context_free_discount_cpu_usage_den; uint32_t max_transaction_cpu_usage; uint32_t max_transaction_net_usage; uint64_t max_block_cpu_usage; uint32_t target_block_cpu_usage_pct; uint64_t max_block_net_usage; uint32_t target_block_net_usage_pct; uint32_t max_transaction_lifetime; uint32_t max_transaction_exec_time; uint16_t max_authority_depth; uint16_t max_inline_depth; uint32_t max_inline_action_size; uint32_t max_generated_transaction_count; uint32_t max_transaction_delay; EOSLIB_SERIALIZE( blockchain_parameters, (base_per_transaction_net_usage)(base_per_transaction_cpu_usage)(base_per_action_cpu_usage) (base_setcode_cpu_usage)(per_signature_cpu_usage)(per_lock_net_usage) (context_free_discount_cpu_usage_num)(context_free_discount_cpu_usage_den) (max_transaction_cpu_usage)(max_transaction_net_usage) (max_block_cpu_usage)(target_block_cpu_usage_pct) (max_block_net_usage)(target_block_net_usage_pct) (max_transaction_lifetime)(max_transaction_exec_time)(max_authority_depth) (max_inline_depth)(max_inline_action_size)(max_generated_transaction_count) (max_transaction_delay) ) }; void set_blockchain_parameters(const eosio::blockchain_parameters& params); void get_blockchain_parameters(eosio::blockchain_parameters& params); struct producer_key { account_name producer_name; public_key block_signing_key; EOSLIB_SERIALIZE( producer_key, (producer_name)(block_signing_key) ) }; struct producer_schedule { uint32_t version = 0; ///< sequentially incrementing version number std::vector<producer_key> producers; EOSLIB_SERIALIZE( producer_schedule, (version)(producers) ) }; } <commit_msg>Add docs for privileged c++ api<commit_after>#pragma once #include "privileged.h" #include "serialize.hpp" #include "types.h" namespace eosio { /** * @defgroup privilegedcppapi Privileged C++ API * @ingroup privilegedapi * @brief Define C++ Privileged API * * @{ */ /** * Tunable blockchain configuration that can be changed via consensus * * @brief Tunable blockchain configuration that can be changed via consensus */ struct blockchain_parameters { /** * The base amount of net usage billed for a transaction to cover incidentals * @brief The base amount of net usage billed for a transaction to cover incidentals */ uint32_t base_per_transaction_net_usage; /** * The base amount of cpu usage billed for a transaction to cover incidentals * * @brief The base amount of cpu usage billed for a transaction to cover incidentals */ uint32_t base_per_transaction_cpu_usage; /** * The base amount of cpu usage billed for an action to cover incidentals * * @brief The base amount of cpu usage billed for an action to cover incidentals */ uint32_t base_per_action_cpu_usage; /** * The base amount of cpu usage billed for a setcode action to cover compilation/etc * * @brief The base amount of cpu usage billed for a setcode action to cover compilation/etc */ uint32_t base_setcode_cpu_usage; /** * The cpu usage billed for every signature on a transaction * * @brief The cpu usage billed for every signature on a transaction */ uint32_t per_signature_cpu_usage; /** * The net usage billed for every lock on a transaction to cover overhead in the block shards * * @brief The net usage billed for every lock on a transaction to cover overhead in the block shards */ uint32_t per_lock_net_usage; /** * The numerator for the discount on cpu usage for CFA's * * @brief The numerator for the discount on cpu usage for CFA's */ uint64_t context_free_discount_cpu_usage_num; /** * The denominator for the discount on cpu usage for CFA's * * @brief The denominator for the discount on cpu usage for CFA's */ uint64_t context_free_discount_cpu_usage_den; /** * The maximum objectively measured cpu usage that the chain will allow regardless of account limits * * @brief The maximum objectively measured cpu usage that the chain will allow regardless of account limits */ uint32_t max_transaction_cpu_usage; /** * The maximum objectively measured net usage that the chain will allow regardless of account limits * * @brief The maximum objectively measured net usage that the chain will allow regardless of account limits */ uint32_t max_transaction_net_usage; /** * The maxiumum cpu usage in instructions for a block * * @brief The maxiumum cpu usage in instructions for a block */ uint64_t max_block_cpu_usage; /** * The target percent (1% == 100, 100%= 10,000) of maximum cpu usage; exceeding this triggers congestion handling * * @brief The target percent (1% == 100, 100%= 10,000) of maximum cpu usage; exceeding this triggers congestion handling */ uint32_t target_block_cpu_usage_pct; /** * The maxiumum net usage in instructions for a block * * @brief The maxiumum net usage in instructions for a block */ uint64_t max_block_net_usage; /** * The target percent (1% == 100, 100%= 10,000) of maximum net usage; exceeding this triggers congestion handling * * @brief The target percent (1% == 100, 100%= 10,000) of maximum net usage; exceeding this triggers congestion handling */ uint32_t target_block_net_usage_pct; /** * Maximum lifetime of a transacton * * @brief Maximum lifetime of a transacton */ uint32_t max_transaction_lifetime; /** * Maximum execution time of a transaction * * @brief Maximum execution time of a transaction */ uint32_t max_transaction_exec_time; /** * Maximum authority depth * * @brief Maximum authority depth */ uint16_t max_authority_depth; /** * Maximum depth of inline action * * @brief Maximum depth of inline action */ uint16_t max_inline_depth; /** * Maximum size of inline action * * @brief Maximum size of inline action */ uint32_t max_inline_action_size; /** * Maximum number of generated transaction * * @brief Maximum number of generated transaction */ uint32_t max_generated_transaction_count; /** * Maximum delay of a transaction * * @brief Maximum delay of a transaction */ uint32_t max_transaction_delay; EOSLIB_SERIALIZE( blockchain_parameters, (base_per_transaction_net_usage)(base_per_transaction_cpu_usage)(base_per_action_cpu_usage) (base_setcode_cpu_usage)(per_signature_cpu_usage)(per_lock_net_usage) (context_free_discount_cpu_usage_num)(context_free_discount_cpu_usage_den) (max_transaction_cpu_usage)(max_transaction_net_usage) (max_block_cpu_usage)(target_block_cpu_usage_pct) (max_block_net_usage)(target_block_net_usage_pct) (max_transaction_lifetime)(max_transaction_exec_time)(max_authority_depth) (max_inline_depth)(max_inline_action_size)(max_generated_transaction_count) (max_transaction_delay) ) }; /** * @brief Set the blockchain parameters * Set the blockchain parameters * @param params - New blockchain parameters to set */ void set_blockchain_parameters(const eosio::blockchain_parameters& params); /** * @brief Retrieve the blolckchain parameters * Retrieve the blolckchain parameters * @param params - It will be replaced with the retrieved blockchain params */ void get_blockchain_parameters(eosio::blockchain_parameters& params); ///@} priviledgedcppapi struct producer_key { account_name producer_name; public_key block_signing_key; EOSLIB_SERIALIZE( producer_key, (producer_name)(block_signing_key) ) }; struct producer_schedule { uint32_t version = 0; ///< sequentially incrementing version number std::vector<producer_key> producers; EOSLIB_SERIALIZE( producer_schedule, (version)(producers) ) }; } <|endoftext|>
<commit_before>/* dlloader.cpp * * cxxtools - general purpose C++-toolbox * Copyright (C) 2003 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "cxxtools/dlloader.h" #include "cxxtools/log.h" #include "config.h" #ifdef USE_LIBTOOL #include <ltdl.h> #define DLERROR() lt_dlerror() #define DLINIT() lt_dlinit() #define DLOPEN(name) lt_dlopenext(name) #define DLCLOSE(handle) lt_dlclose(static_cast<lt_dlhandle>(handle)) #define DLEXIT() lt_dlexit() #define DLSYM(handle, name) lt_dlsym(static_cast<lt_dlhandle>(handle), const_cast<char*>(name)) #else // no LIBTOOL #include <dlfcn.h> #define DLERROR() dlerror() #define DLINIT() #define DLOPEN(name) cxx_dlopen(name) #define DLCLOSE(handle) dlclose(handle) #define DLEXIT() #define DLSYM(handle, name) dlsym(handle, const_cast<char*>(name)) static void* cxx_dlopen(const char* name) { return dlopen((std::string(name) + ".so").c_str(), RTLD_NOW|RTLD_GLOBAL); } #endif log_define("cxxtools.dlloader"); namespace cxxtools { namespace dl { namespace { std::string errorString() { const char* msg = DLERROR(); return msg ? std::string(msg) : "unknown error in dlloader"; } } Error::Error() : std::runtime_error(errorString()) { } Error::Error(const std::string& msg) : std::runtime_error(msg + ": " + errorString()) { } DlopenError::DlopenError(const std::string& l) : Error("library \"" + l + '"'), libname(l) { } SymbolNotFound::SymbolNotFound(const std::string& s) : Error("symbol \"" + s + '"'), symbol(s) { } Library::Library(const Library& src) : handle(src.handle), prev(&src), next(src.next) { src.next = this; next->prev = this; } Library& Library::operator=(const Library& src) { if (handle == src.handle) return *this; close(); handle = src.handle; if (handle) { prev = const_cast<Library*>(&src); next = src.next; const_cast<Library&>(src).next = this; next->prev = this; } return *this; } void Library::open(const char* name) { close(); log_debug("dlinit"); DLINIT(); log_debug("dlopen(\"" << name << "\")"); handle = DLOPEN(name); if (!handle) { log_debug("dlopen(\"" << name << "\") failed"); DLEXIT(); throw DlopenError(name); } log_debug("dlopen => " << handle); } void Library::close() { if (handle) { if (prev == this) { log_debug("dlclose " << handle); DLCLOSE(handle); DLEXIT(); } else { prev->next = next; next->prev = prev; } handle = 0; next = prev = this; } } Symbol Library::sym(const char* name) const { log_debug("dlsym(" << handle << ", \"" << name << "\")"); void* sym = DLSYM(handle, name); if (sym == 0) { log_debug("dlsym: symbol \"" << name << "\" not found"); throw SymbolNotFound(name); } log_debug("dlsym => " << sym); return Symbol(*this, sym); } } // namespace dl } // namespace cxxtools <commit_msg>add locks to library-loader<commit_after>/* dlloader.cpp * * cxxtools - general purpose C++-toolbox * Copyright (C) 2003 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "cxxtools/dlloader.h" #include "cxxtools/log.h" #include "config.h" #include <cxxtools/thread.h> #ifdef USE_LIBTOOL #include <ltdl.h> #define DLERROR() lt_dlerror() #define DLINIT() lt_dlinit() #define DLOPEN(name) lt_dlopenext(name) #define DLCLOSE(handle) lt_dlclose(static_cast<lt_dlhandle>(handle)) #define DLEXIT() lt_dlexit() #define DLSYM(handle, name) lt_dlsym(static_cast<lt_dlhandle>(handle), const_cast<char*>(name)) #else // no LIBTOOL #include <dlfcn.h> #define DLERROR() dlerror() #define DLINIT() #define DLOPEN(name) cxx_dlopen(name) #define DLCLOSE(handle) dlclose(handle) #define DLEXIT() #define DLSYM(handle, name) dlsym(handle, const_cast<char*>(name)) static void* cxx_dlopen(const char* name) { return dlopen((std::string(name) + ".so").c_str(), RTLD_NOW|RTLD_GLOBAL); } #endif log_define("cxxtools.dlloader") static cxxtools::Mutex mutex; namespace cxxtools { namespace dl { namespace { std::string errorString() { const char* msg = DLERROR(); return msg ? std::string(msg) : "unknown error in dlloader"; } } Error::Error() : std::runtime_error(errorString()) { } Error::Error(const std::string& msg) : std::runtime_error(msg + ": " + errorString()) { } DlopenError::DlopenError(const std::string& l) : Error("library \"" + l + '"'), libname(l) { } SymbolNotFound::SymbolNotFound(const std::string& s) : Error("symbol \"" + s + '"'), symbol(s) { } Library::Library(const Library& src) : handle(src.handle), prev(&src), next(src.next) { src.next = this; next->prev = this; } Library& Library::operator=(const Library& src) { if (handle == src.handle) return *this; close(); cxxtools::MutexLock lock(mutex); handle = src.handle; if (handle) { prev = const_cast<Library*>(&src); next = src.next; const_cast<Library&>(src).next = this; next->prev = this; } return *this; } void Library::open(const char* name) { close(); cxxtools::MutexLock lock(mutex); log_debug("dlinit"); DLINIT(); log_debug("dlopen(\"" << name << "\")"); handle = DLOPEN(name); if (!handle) { log_debug("dlopen(\"" << name << "\") failed"); DLEXIT(); throw DlopenError(name); } log_debug("dlopen => " << handle); } void Library::close() { cxxtools::MutexLock lock(mutex); if (handle) { if (prev == this) { log_debug("dlclose " << handle); DLCLOSE(handle); DLEXIT(); } else { prev->next = next; next->prev = prev; } handle = 0; next = prev = this; } } Symbol Library::sym(const char* name) const { log_debug("dlsym(" << handle << ", \"" << name << "\")"); void* sym = DLSYM(handle, name); if (sym == 0) { log_debug("dlsym: symbol \"" << name << "\" not found"); throw SymbolNotFound(name); } log_debug("dlsym => " << sym); return Symbol(*this, sym); } } // namespace dl } // namespace cxxtools <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: DataFmtTransl.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: tra $ $Date: 2001-03-09 08:46:46 $ * * 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): _______________________________________ * * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _DATAFMTTRANSL_HXX_ #include "DataFmtTransl.hxx" #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _IMPLHELPER_HXX_ #include "..\misc\ImplHelper.hxx" #endif #ifndef _WINCLIP_HXX_ #include "..\misc\WinClip.hxx" #endif #ifndef _MIMEATTRIB_HXX_ #include "MimeAttrib.hxx" #endif #ifndef _DTRANSHELPER_HXX_ #include "DTransHelper.hxx" #endif #ifndef _RTL_STRING_H_ #include <rtl/string.h> #endif #ifndef _FETC_HXX_ #include "Fetc.hxx" #endif #include <systools/win32/user9x.h> #include <windows.h> #include <olestd.h> //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace rtl; using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; //------------------------------------------------------------------------ // const //------------------------------------------------------------------------ const Type CPPUTYPE_SALINT32 = getCppuType((sal_Int32*)0); const Type CPPUTYPE_SALINT8 = getCppuType((sal_Int8*)0); const Type CPPUTYPE_OUSTRING = getCppuType((OUString*)0); const Type CPPUTYPE_SEQSALINT8 = getCppuType((Sequence< sal_Int8>*)0); const sal_Int32 MAX_CLIPFORMAT_NAME = 256; //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CDataFormatTranslator::CDataFormatTranslator( const Reference< XMultiServiceFactory >& aServiceManager ) : m_SrvMgr( aServiceManager ) { m_XDataFormatTranslator = Reference< XDataFormatTranslator >( m_SrvMgr->createInstance( OUString::createFromAscii( "com.sun.star.datatransfer.DataFormatTranslator" ) ), UNO_QUERY ); OSL_ASSERT( m_XDataFormatTranslator.is( ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc CDataFormatTranslator::getFormatEtcFromDataFlavor( const DataFlavor& aDataFlavor ) const { sal_Int32 cf = CF_INVALID; try { Any aFormat = m_XDataFormatTranslator->getSystemDataTypeFromDataFlavor( aDataFlavor ); if ( aFormat.getValueType( ) == CPPUTYPE_SALINT32 ) { aFormat >>= cf; OSL_ENSURE( CF_INVALID != cf, "Invalid Clipboard format delivered" ); } else if ( aFormat.getValueType( ) == CPPUTYPE_OUSTRING ) { OUString aClipFmtName; aFormat >>= aClipFmtName; OSL_ASSERT( aClipFmtName.getLength( ) ); cf = RegisterClipboardFormatW( aClipFmtName.getStr( ) ); OSL_ENSURE( CF_INVALID != cf, "RegisterClipboardFormat failed" ); } else OSL_ENSURE( sal_False, "Wrong Any-Type detected" ); } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return getFormatEtcForClipformat( cf ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ DataFlavor CDataFormatTranslator::getDataFlavorFromFormatEtc( const Reference< XTransferable >& refXTransferable, const FORMATETC& aFormatEtc ) const { DataFlavor aFlavor; try { CLIPFORMAT aClipformat = aFormatEtc.cfFormat; Any aAny; aAny <<= static_cast< sal_Int32 >( aClipformat ); if ( isOemOrAnsiTextClipformat( aClipformat ) ) { aFlavor.MimeType = OUString::createFromAscii( "text/plain;charset=" ); aFlavor.MimeType += getTextCharsetFromClipboard( refXTransferable, aClipformat ); aFlavor.HumanPresentableName = OUString::createFromAscii( "OEM/ANSI Text" ); aFlavor.DataType = CPPUTYPE_SEQSALINT8; } else { aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); if ( !aFlavor.MimeType.getLength( ) ) { // lookup of DataFlavor from clipboard format id // failed, so we try to resolve via clipboard // format name OUString clipFormatName = getClipboardFormatName( aClipformat ); // if we could not get a clipboard format name an // error must have occured or it is a standard // clipboard format that we don't translate, e.g. // CF_BITMAP (the office only uses CF_DIB) if ( clipFormatName.getLength( ) ) { aAny <<= clipFormatName; aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); } } } } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return aFlavor; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString CDataFormatTranslator::getClipboardFormatName( CLIPFORMAT aClipformat ) const { OSL_PRECOND( CF_INVALID != aClipformat, "Invalid clipboard format" ); sal_Unicode wBuff[ MAX_CLIPFORMAT_NAME ]; sal_Int32 nLen = GetClipboardFormatNameW( aClipformat, wBuff, MAX_CLIPFORMAT_NAME ); return OUString( wBuff, nLen ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformat( CLIPFORMAT cf ) const { CFormatEtc fetc( cf, TYMED_NULL, NULL, DVASPECT_CONTENT );; switch( cf ) { case CF_METAFILEPICT: fetc.setTymed( TYMED_MFPICT ); break; case CF_ENHMETAFILE: fetc.setTymed( TYMED_ENHMF ); break; default: fetc.setTymed( TYMED_HGLOBAL | TYMED_ISTREAM ); } return fetc; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ inline sal_Bool SAL_CALL CDataFormatTranslator::isOemOrAnsiTextClipformat( CLIPFORMAT aClipformat ) const { return ( (aClipformat == CF_TEXT) || (aClipformat == CF_OEMTEXT) ); } //------------------------------------------------------------------------ // should be called only if there is realy text on the clipboard //------------------------------------------------------------------------ LCID SAL_CALL CDataFormatTranslator::getCurrentLocaleFromClipboard( const Reference< XTransferable >& refXTransferable ) const { Any aAny; CFormatEtc fetc = getFormatEtcForClipformat( CF_LOCALE ); DataFlavor aFlavor = getDataFlavorFromFormatEtc( refXTransferable, fetc ); OSL_ASSERT( aFlavor.MimeType.getLength( ) ); LCID lcid; try { aAny = refXTransferable->getTransferData( aFlavor ); if ( aAny.hasValue( ) ) { OSL_ASSERT( aAny.getValueType( ) == CPPUTYPE_SEQSALINT8 ); Sequence< sal_Int8 > byteStream; aAny >>= byteStream; lcid = *reinterpret_cast< LCID* >( byteStream.getArray( ) ); } } catch( UnsupportedFlavorException& ) { lcid = GetThreadLocale( ); } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } if ( !IsValidLocale( lcid, LCID_SUPPORTED ) ) lcid = GetThreadLocale( ); return lcid; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CDataFormatTranslator::getTextCharsetFromClipboard( const Reference< XTransferable >& refXTransferable, CLIPFORMAT aClipformat ) const { OSL_ASSERT( isOemOrAnsiTextClipformat( aClipformat ) ); OUString charset; if ( CF_TEXT == aClipformat ) { LCID lcid = getCurrentLocaleFromClipboard( refXTransferable ); charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE, PRE_WINDOWS_CODEPAGE ); } else if ( CF_OEMTEXT == aClipformat ) { LCID lcid = getCurrentLocaleFromClipboard( refXTransferable ); charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE, PRE_OEM_CODEPAGE ); } else // CF_UNICODE OSL_ASSERT( sal_False ); return charset; }<commit_msg>support for IStream currently removed because of strange notepad problems under W2K<commit_after>/************************************************************************* * * $RCSfile: DataFmtTransl.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: tra $ $Date: 2001-03-09 15:21:17 $ * * 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): _______________________________________ * * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _DATAFMTTRANSL_HXX_ #include "DataFmtTransl.hxx" #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _IMPLHELPER_HXX_ #include "..\misc\ImplHelper.hxx" #endif #ifndef _WINCLIP_HXX_ #include "..\misc\WinClip.hxx" #endif #ifndef _MIMEATTRIB_HXX_ #include "MimeAttrib.hxx" #endif #ifndef _DTRANSHELPER_HXX_ #include "DTransHelper.hxx" #endif #ifndef _RTL_STRING_H_ #include <rtl/string.h> #endif #ifndef _FETC_HXX_ #include "Fetc.hxx" #endif #include <systools/win32/user9x.h> #include <windows.h> #include <olestd.h> //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace rtl; using namespace std; using namespace com::sun::star::uno; using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; //------------------------------------------------------------------------ // const //------------------------------------------------------------------------ const Type CPPUTYPE_SALINT32 = getCppuType((sal_Int32*)0); const Type CPPUTYPE_SALINT8 = getCppuType((sal_Int8*)0); const Type CPPUTYPE_OUSTRING = getCppuType((OUString*)0); const Type CPPUTYPE_SEQSALINT8 = getCppuType((Sequence< sal_Int8>*)0); const sal_Int32 MAX_CLIPFORMAT_NAME = 256; //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CDataFormatTranslator::CDataFormatTranslator( const Reference< XMultiServiceFactory >& aServiceManager ) : m_SrvMgr( aServiceManager ) { m_XDataFormatTranslator = Reference< XDataFormatTranslator >( m_SrvMgr->createInstance( OUString::createFromAscii( "com.sun.star.datatransfer.DataFormatTranslator" ) ), UNO_QUERY ); OSL_ASSERT( m_XDataFormatTranslator.is( ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc CDataFormatTranslator::getFormatEtcFromDataFlavor( const DataFlavor& aDataFlavor ) const { sal_Int32 cf = CF_INVALID; try { Any aFormat = m_XDataFormatTranslator->getSystemDataTypeFromDataFlavor( aDataFlavor ); if ( aFormat.getValueType( ) == CPPUTYPE_SALINT32 ) { aFormat >>= cf; OSL_ENSURE( CF_INVALID != cf, "Invalid Clipboard format delivered" ); } else if ( aFormat.getValueType( ) == CPPUTYPE_OUSTRING ) { OUString aClipFmtName; aFormat >>= aClipFmtName; OSL_ASSERT( aClipFmtName.getLength( ) ); cf = RegisterClipboardFormatW( aClipFmtName.getStr( ) ); OSL_ENSURE( CF_INVALID != cf, "RegisterClipboardFormat failed" ); } else OSL_ENSURE( sal_False, "Wrong Any-Type detected" ); } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return getFormatEtcForClipformat( cf ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ DataFlavor CDataFormatTranslator::getDataFlavorFromFormatEtc( const Reference< XTransferable >& refXTransferable, const FORMATETC& aFormatEtc ) const { DataFlavor aFlavor; try { CLIPFORMAT aClipformat = aFormatEtc.cfFormat; Any aAny; aAny <<= static_cast< sal_Int32 >( aClipformat ); if ( isOemOrAnsiTextClipformat( aClipformat ) ) { aFlavor.MimeType = OUString::createFromAscii( "text/plain;charset=" ); aFlavor.MimeType += getTextCharsetFromClipboard( refXTransferable, aClipformat ); aFlavor.HumanPresentableName = OUString::createFromAscii( "OEM/ANSI Text" ); aFlavor.DataType = CPPUTYPE_SEQSALINT8; } else { aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); if ( !aFlavor.MimeType.getLength( ) ) { // lookup of DataFlavor from clipboard format id // failed, so we try to resolve via clipboard // format name OUString clipFormatName = getClipboardFormatName( aClipformat ); // if we could not get a clipboard format name an // error must have occured or it is a standard // clipboard format that we don't translate, e.g. // CF_BITMAP (the office only uses CF_DIB) if ( clipFormatName.getLength( ) ) { aAny <<= clipFormatName; aFlavor = m_XDataFormatTranslator->getDataFlavorFromSystemDataType( aAny ); } } } } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } return aFlavor; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString CDataFormatTranslator::getClipboardFormatName( CLIPFORMAT aClipformat ) const { OSL_PRECOND( CF_INVALID != aClipformat, "Invalid clipboard format" ); sal_Unicode wBuff[ MAX_CLIPFORMAT_NAME ]; sal_Int32 nLen = GetClipboardFormatNameW( aClipformat, wBuff, MAX_CLIPFORMAT_NAME ); return OUString( wBuff, nLen ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ CFormatEtc SAL_CALL CDataFormatTranslator::getFormatEtcForClipformat( CLIPFORMAT cf ) const { CFormatEtc fetc( cf, TYMED_NULL, NULL, DVASPECT_CONTENT );; switch( cf ) { case CF_METAFILEPICT: fetc.setTymed( TYMED_MFPICT ); break; case CF_ENHMETAFILE: fetc.setTymed( TYMED_ENHMF ); break; default: fetc.setTymed( TYMED_HGLOBAL /*| TYMED_ISTREAM*/ ); } return fetc; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ inline sal_Bool SAL_CALL CDataFormatTranslator::isOemOrAnsiTextClipformat( CLIPFORMAT aClipformat ) const { return ( (aClipformat == CF_TEXT) || (aClipformat == CF_OEMTEXT) ); } //------------------------------------------------------------------------ // should be called only if there is realy text on the clipboard //------------------------------------------------------------------------ LCID SAL_CALL CDataFormatTranslator::getCurrentLocaleFromClipboard( const Reference< XTransferable >& refXTransferable ) const { Any aAny; CFormatEtc fetc = getFormatEtcForClipformat( CF_LOCALE ); DataFlavor aFlavor = getDataFlavorFromFormatEtc( refXTransferable, fetc ); OSL_ASSERT( aFlavor.MimeType.getLength( ) ); LCID lcid; try { aAny = refXTransferable->getTransferData( aFlavor ); if ( aAny.hasValue( ) ) { OSL_ASSERT( aAny.getValueType( ) == CPPUTYPE_SEQSALINT8 ); Sequence< sal_Int8 > byteStream; aAny >>= byteStream; lcid = *reinterpret_cast< LCID* >( byteStream.getArray( ) ); } } catch( UnsupportedFlavorException& ) { lcid = GetThreadLocale( ); } catch( ... ) { OSL_ENSURE( sal_False, "Unexpected error" ); } if ( !IsValidLocale( lcid, LCID_SUPPORTED ) ) lcid = GetThreadLocale( ); return lcid; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CDataFormatTranslator::getTextCharsetFromClipboard( const Reference< XTransferable >& refXTransferable, CLIPFORMAT aClipformat ) const { OSL_ASSERT( isOemOrAnsiTextClipformat( aClipformat ) ); OUString charset; if ( CF_TEXT == aClipformat ) { LCID lcid = getCurrentLocaleFromClipboard( refXTransferable ); charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTANSICODEPAGE, PRE_WINDOWS_CODEPAGE ); } else if ( CF_OEMTEXT == aClipformat ) { LCID lcid = getCurrentLocaleFromClipboard( refXTransferable ); charset = getMimeCharsetFromLocaleId( lcid, LOCALE_IDEFAULTCODEPAGE, PRE_OEM_CODEPAGE ); } else // CF_UNICODE OSL_ASSERT( sal_False ); return charset; }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkBridgeDataSet.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkBridgeDataSet - Implementation of vtkGenericDataSet. // .SECTION Description // It is just an example that show how to implement the Generic. It is also // used for testing and evaluating the Generic. #include "vtkBridgeDataSet.h" #include <assert.h> #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkCellTypes.h" #include "vtkCell.h" #include "vtkBridgeCellIterator.h" #include "vtkBridgePointIterator.h" #include "vtkBridgeCell.h" #include "vtkGenericCell.h" #include "vtkMath.h" #include "vtkGenericAttributeCollection.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkBridgeAttribute.h" #include "vtkGenericCellTessellator.h" #include "vtkGenericEdgeTable.h" #include "vtkSimpleCellTessellator.h" vtkCxxRevisionMacro(vtkBridgeDataSet, "1.4"); vtkStandardNewMacro(vtkBridgeDataSet); //---------------------------------------------------------------------------- // Default constructor. vtkBridgeDataSet::vtkBridgeDataSet( ) { this->Implementation = 0; this->Types=vtkCellTypes::New(); this->Tessellator=vtkSimpleCellTessellator::New(); } //---------------------------------------------------------------------------- vtkBridgeDataSet::~vtkBridgeDataSet( ) { if(this->Implementation!=0) { this->Implementation->Delete(); } this->Types->Delete(); } //---------------------------------------------------------------------------- void vtkBridgeDataSet::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "implementation: "; if(this->Implementation==0) { os << 0 << endl; } else { os << endl; this->Implementation->PrintSelf(os,indent.GetNextIndent()); } } //---------------------------------------------------------------------------- // Description: // Set the dataset that will be manipulated through the adaptor interface. // \pre ds_exists: ds!=0 void vtkBridgeDataSet::SetDataSet(vtkDataSet *ds) { int i; int c; vtkPointData *pd; vtkCellData *cd; vtkBridgeAttribute *a; vtkSetObjectBodyMacro(Implementation,vtkDataSet,ds); // refresh the attribute collection this->Attributes->Reset(); if(ds!=0) { // point data pd=ds->GetPointData(); c=pd->GetNumberOfArrays(); i=0; while(i<c) { a=vtkBridgeAttribute::New(); a->InitWithPointData(pd,i); this->Attributes->InsertNextAttribute(a); ++i; } // same thing for cell data. cd=ds->GetCellData(); c=cd->GetNumberOfArrays(); i=0; while(i<c) { a=vtkBridgeAttribute::New(); a->InitWithCellData(cd,i); this->Attributes->InsertNextAttribute(a); ++i; } this->Tessellator->Initialize(this); } this->Modified(); } //---------------------------------------------------------------------------- // Description: // Number of points composing the dataset. See NewPointIterator for more // details. // \post positive_result: result>=0 vtkIdType vtkBridgeDataSet::GetNumberOfPoints() { vtkIdType result=0; if(this->Implementation!=0) { result=Implementation->GetNumberOfPoints(); } assert("post: positive_result" && result>=0); return result; } //---------------------------------------------------------------------------- // Description: // Compute the number of cells for each dimension and the list of types of // cells. // \pre implementation_exists: this->Implementation!=0 void vtkBridgeDataSet::ComputeNumberOfCellsAndTypes() { unsigned char type; vtkIdType cellId; vtkIdType numCells; vtkCell *c; if ( this->GetMTime() > this->ComputeNumberOfCellsTime ) // cache is obsolete { numCells=this->GetNumberOfCells(); this->NumberOf0DCells=0; this->NumberOf1DCells=0; this->NumberOf2DCells=0; this->NumberOf3DCells=0; this->Types->Reset(); if(this->Implementation!=0) { cellId=0; while(cellId<numCells) { c=this->Implementation->GetCell(cellId); switch(c->GetCellDimension()) { case 0: this->NumberOf0DCells++; break; case 1: this->NumberOf1DCells++; break; case 2: this->NumberOf2DCells++; break; case 3: this->NumberOf3DCells++; break; } type=c->GetCellType(); if(!Types->IsType(type)) { Types->InsertNextType(type); } cellId++; } } this->ComputeNumberOfCellsTime.Modified(); // cache is up-to-date assert("check: positive_dim0" && this->NumberOf0DCells>=0); assert("check: valid_dim0" && this->NumberOf0DCells<=numCells); assert("check: positive_dim1" && this->NumberOf1DCells>=0); assert("check: valid_dim1" && this->NumberOf1DCells<=numCells); assert("check: positive_dim2" && this->NumberOf2DCells>=0); assert("check: valid_dim2" && this->NumberOf2DCells<=numCells); assert("check: positive_dim3" && this->NumberOf3DCells>=0); assert("check: valid_dim3" && this->NumberOf3DCells<=numCells); } } //---------------------------------------------------------------------------- // Description: // Number of cells that explicitly define the dataset. See NewCellIterator // for more details. // \pre valid_dim_range: (dim>=-1) && (dim<=3) // \post positive_result: result>=0 vtkIdType vtkBridgeDataSet::GetNumberOfCells(int dim) { assert("pre: valid_dim_range" && (dim>=-1) && (dim<=3)); vtkIdType result=0; if(this->Implementation!=0) { if(dim==-1) { result=this->Implementation->GetNumberOfCells(); } else { ComputeNumberOfCellsAndTypes(); switch(dim) { case 0: result=this->NumberOf0DCells; break; case 1: result=this->NumberOf1DCells; break; case 2: result=this->NumberOf2DCells; break; case 3: result=this->NumberOf3DCells; break; } } } assert("post: positive_result" && result>=0); return result; } //---------------------------------------------------------------------------- // Description: // Return -1 if the dataset is explicitly defined by cells of several // dimensions or if there is no cell. If the dataset is explicitly defined by // cells of a unique dimension, return this dimension. // \post valid_range: (result>=-1) && (result<=3) int vtkBridgeDataSet::GetCellDimension() { int result=0; int accu=0; this->ComputeNumberOfCellsAndTypes(); if(this->NumberOf0DCells!=0) { accu++; result=0; } if(this->NumberOf1DCells!=0) { accu++; result=1; } if(this->NumberOf2DCells!=0) { accu++; result=2; } if(this->NumberOf3DCells!=0) { accu++; result=3; } if(accu!=1) // no cells at all or several dimensions { result=-1; } assert("post: valid_range" && (result>=-1) && (result<=3)); return result; } //---------------------------------------------------------------------------- // Description: // Get a list of types of cells in a dataset. The list consists of an array // of types (not necessarily in any order), with a single entry per type. // For example a dataset 5 triangles, 3 lines, and 100 hexahedra would // result a list of three entries, corresponding to the types VTK_TRIANGLE, // VTK_LINE, and VTK_HEXAHEDRON. // THIS METHOD IS THREAD SAFE IF FIRST CALLED FROM A SINGLE THREAD AND // THE DATASET IS NOT MODIFIED // \pre types_exist: types!=0 void vtkBridgeDataSet::GetCellTypes(vtkCellTypes *types) { assert("pre: types_exist" && types!=0); int i; int c; this->ComputeNumberOfCellsAndTypes(); // copy from `this->Types' to `types'. types->Reset(); c=this->Types->GetNumberOfTypes(); i=0; while(i<c) { types->InsertNextType(this->Types->GetCellType(i)); ++i; } } //---------------------------------------------------------------------------- // Description: // Cells of dimension `dim' (or all dimensions if -1) that explicitly define // the dataset. For instance, it will return only tetrahedra if the mesh is // defined by tetrahedra. If the mesh is composed of two parts, one with // tetrahedra and another part with triangles, it will return both, but will // not return edges and vertices. // \pre valid_dim_range: (dim>=-1) && (dim<=3) // \post result_exists: result!=0 vtkGenericCellIterator *vtkBridgeDataSet::NewCellIterator(int dim) { assert("pre: valid_dim_range" && (dim>=-1) && (dim<=3)); vtkBridgeCellIterator *result=vtkBridgeCellIterator::New(); result->InitWithDataSet(this,dim); // vtkBridgeCellIteratorOnDataSetCells assert("post: result_exists" && result!=0); return result; } //---------------------------------------------------------------------------- // Description: // Boundaries of dimension `dim' (or all dimensions if -1) of the dataset. // If `exteriorOnly' is true, only the exterior boundaries of the dataset // will be returned, otherwise it will return exterior and interior // boundaries. // \pre valid_dim_range: (dim>=-1) && (dim<=2) // \post result_exists: result!=0 vtkGenericCellIterator *vtkBridgeDataSet::NewBoundaryIterator(int dim, int exteriorOnly) { assert("pre: valid_dim_range" && (dim>=-1) && (dim<=2)); vtkBridgeCellIterator *result=vtkBridgeCellIterator::New(); result->InitWithDataSetBoundaries(this,dim,exteriorOnly); //vtkBridgeCellIteratorOnDataSetBoundaries(dim,exterior_only); assert("post: result_exists" && result!=0); return result; } //---------------------------------------------------------------------------- // Description: // Points composing the dataset; they can be on a vertex or isolated. // \post result_exists: result!=0 vtkGenericPointIterator *vtkBridgeDataSet::NewPointIterator() { vtkBridgePointIterator *result=vtkBridgePointIterator::New(); result->InitWithDataSet(this); assert("post: result_exists" && result!=0); return result; } //---------------------------------------------------------------------------- // Description: // Estimated size needed after tessellation (or special operation) vtkIdType vtkBridgeDataSet::GetEstimatedSize() { return this->GetNumberOfPoints()*this->GetNumberOfCells(); } //---------------------------------------------------------------------------- // Description: // Locate closest cell to position `x' (global coordinates) with respect to // a tolerance squared `tol2' and an initial guess `cell' (if valid). The // result consists in the `cell', the `subId' of the sub-cell (0 if primary // cell), the parametric coordinates `pcoord' of the position. It returns // whether the position is inside the cell or not. Tolerance is used to // control how close the point is to be considered "in" the cell. // THIS METHOD IS NOT THREAD SAFE. // \pre not_empty: GetNumberOfCells()>0 // \pre cell_exists: cell!=0 // \pre positive_tolerance: tol2>0 // \post clamped_pcoords: result implies (0<=pcoords[0]<=1 && ) int vtkBridgeDataSet::FindCell(double x[3], vtkGenericCellIterator* &cell, double tol2, int &subId, double pcoords[3]) { assert("pre: not_empty" && GetNumberOfCells()>0); assert("pre: cell_exists" && cell!=0); assert("pre: positive_tolerance" && tol2>0); vtkIdType cellid; vtkBridgeCell *c; vtkBridgeCellIterator *it=static_cast<vtkBridgeCellIterator *>(cell); vtkCell *c2; double *ignoredWeights=new double[this->Implementation->GetMaxCellSize()]; if(cell->IsAtEnd()) { cellid=this->Implementation->FindCell(x,0,0,tol2,subId,pcoords, ignoredWeights); } else { c=static_cast<vtkBridgeCell *>(cell->GetCell()); c2=c->Cell; // bridge cellid=c->GetId(); // adaptor cellid=this->Implementation->FindCell(x,c2,cellid,tol2,subId,pcoords, ignoredWeights); } delete [] ignoredWeights; if(cellid>=0) { it->InitWithOneCell(this,cellid); // at end it->Begin(); // clamp: int i=0; while(i<3) { if(pcoords[i]<0) { pcoords[i]=0; } else if(pcoords[i]>1) { pcoords[i]=1; } ++i; } } // A=>B: !A || B // result => clamped pcoords assert("post: clamped_pcoords" && ((cellid<0)||(pcoords[0]>=0 && pcoords[0]<=1 && pcoords[1]>=0 && pcoords[1]<=1 && pcoords[2]>=0 && pcoords[2]<=1))); return cellid>=0; // bool } //---------------------------------------------------------------------------- // Description: // Locate closest point `p' to position `x' (global coordinates) // \pre not_empty: GetNumberOfPoints()>0 // \pre p_exists: p!=0 void vtkBridgeDataSet::FindPoint(double x[3], vtkGenericPointIterator *p) { assert("pre: not_empty" && GetNumberOfPoints()>0); assert("pre: p_exists" && p!=0); vtkBridgePointIterator *bp=static_cast<vtkBridgePointIterator *>(p); if(this->Implementation!=0) { vtkIdType pt=this->Implementation->FindPoint(x); bp->InitWithOnePoint(this,pt); } else { bp->InitWithOnePoint(this,-1); } } //---------------------------------------------------------------------------- // Description: // Datasets are composite objects and need to check each part for MTime. unsigned long int vtkBridgeDataSet::GetMTime() { unsigned long result; unsigned long mtime; result = vtkGenericDataSet::GetMTime(); if(this->Implementation!=0) { mtime = this->Implementation->GetMTime(); result = ( mtime > result ? mtime : result ); } return result; } //---------------------------------------------------------------------------- // Description: // Compute the geometry bounding box. void vtkBridgeDataSet::ComputeBounds() { double *bounds; if ( this->GetMTime() > this->ComputeTime ) { if(this->Implementation!=0) { this->Implementation->ComputeBounds(); this->ComputeTime.Modified(); bounds=this->Implementation->GetBounds(); memcpy(this->Bounds,bounds,sizeof(double)*6); } else { vtkMath::UninitializeBounds(this->Bounds); } this->ComputeTime.Modified(); } } <commit_msg>BUG:Fixed memory leak<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkBridgeDataSet.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkBridgeDataSet - Implementation of vtkGenericDataSet. // .SECTION Description // It is just an example that show how to implement the Generic. It is also // used for testing and evaluating the Generic. #include "vtkBridgeDataSet.h" #include <assert.h> #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkCellTypes.h" #include "vtkCell.h" #include "vtkBridgeCellIterator.h" #include "vtkBridgePointIterator.h" #include "vtkBridgeCell.h" #include "vtkGenericCell.h" #include "vtkMath.h" #include "vtkGenericAttributeCollection.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkBridgeAttribute.h" #include "vtkGenericCellTessellator.h" #include "vtkGenericEdgeTable.h" #include "vtkSimpleCellTessellator.h" vtkCxxRevisionMacro(vtkBridgeDataSet, "1.5"); vtkStandardNewMacro(vtkBridgeDataSet); //---------------------------------------------------------------------------- // Default constructor. vtkBridgeDataSet::vtkBridgeDataSet( ) { this->Implementation = 0; this->Types=vtkCellTypes::New(); this->Tessellator=vtkSimpleCellTessellator::New(); } //---------------------------------------------------------------------------- vtkBridgeDataSet::~vtkBridgeDataSet( ) { if(this->Implementation!=0) { this->Implementation->Delete(); } this->Types->Delete(); } //---------------------------------------------------------------------------- void vtkBridgeDataSet::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "implementation: "; if(this->Implementation==0) { os << 0 << endl; } else { os << endl; this->Implementation->PrintSelf(os,indent.GetNextIndent()); } } //---------------------------------------------------------------------------- // Description: // Set the dataset that will be manipulated through the adaptor interface. // \pre ds_exists: ds!=0 void vtkBridgeDataSet::SetDataSet(vtkDataSet *ds) { int i; int c; vtkPointData *pd; vtkCellData *cd; vtkBridgeAttribute *a; vtkSetObjectBodyMacro(Implementation,vtkDataSet,ds); // refresh the attribute collection this->Attributes->Reset(); if(ds!=0) { // point data pd=ds->GetPointData(); c=pd->GetNumberOfArrays(); i=0; while(i<c) { a=vtkBridgeAttribute::New(); a->InitWithPointData(pd,i); this->Attributes->InsertNextAttribute(a); a->Delete(); ++i; } // same thing for cell data. cd=ds->GetCellData(); c=cd->GetNumberOfArrays(); i=0; while(i<c) { a=vtkBridgeAttribute::New(); a->InitWithCellData(cd,i); this->Attributes->InsertNextAttribute(a); a->Delete(); ++i; } this->Tessellator->Initialize(this); } this->Modified(); } //---------------------------------------------------------------------------- // Description: // Number of points composing the dataset. See NewPointIterator for more // details. // \post positive_result: result>=0 vtkIdType vtkBridgeDataSet::GetNumberOfPoints() { vtkIdType result=0; if(this->Implementation!=0) { result=Implementation->GetNumberOfPoints(); } assert("post: positive_result" && result>=0); return result; } //---------------------------------------------------------------------------- // Description: // Compute the number of cells for each dimension and the list of types of // cells. // \pre implementation_exists: this->Implementation!=0 void vtkBridgeDataSet::ComputeNumberOfCellsAndTypes() { unsigned char type; vtkIdType cellId; vtkIdType numCells; vtkCell *c; if ( this->GetMTime() > this->ComputeNumberOfCellsTime ) // cache is obsolete { numCells=this->GetNumberOfCells(); this->NumberOf0DCells=0; this->NumberOf1DCells=0; this->NumberOf2DCells=0; this->NumberOf3DCells=0; this->Types->Reset(); if(this->Implementation!=0) { cellId=0; while(cellId<numCells) { c=this->Implementation->GetCell(cellId); switch(c->GetCellDimension()) { case 0: this->NumberOf0DCells++; break; case 1: this->NumberOf1DCells++; break; case 2: this->NumberOf2DCells++; break; case 3: this->NumberOf3DCells++; break; } type=c->GetCellType(); if(!Types->IsType(type)) { Types->InsertNextType(type); } cellId++; } } this->ComputeNumberOfCellsTime.Modified(); // cache is up-to-date assert("check: positive_dim0" && this->NumberOf0DCells>=0); assert("check: valid_dim0" && this->NumberOf0DCells<=numCells); assert("check: positive_dim1" && this->NumberOf1DCells>=0); assert("check: valid_dim1" && this->NumberOf1DCells<=numCells); assert("check: positive_dim2" && this->NumberOf2DCells>=0); assert("check: valid_dim2" && this->NumberOf2DCells<=numCells); assert("check: positive_dim3" && this->NumberOf3DCells>=0); assert("check: valid_dim3" && this->NumberOf3DCells<=numCells); } } //---------------------------------------------------------------------------- // Description: // Number of cells that explicitly define the dataset. See NewCellIterator // for more details. // \pre valid_dim_range: (dim>=-1) && (dim<=3) // \post positive_result: result>=0 vtkIdType vtkBridgeDataSet::GetNumberOfCells(int dim) { assert("pre: valid_dim_range" && (dim>=-1) && (dim<=3)); vtkIdType result=0; if(this->Implementation!=0) { if(dim==-1) { result=this->Implementation->GetNumberOfCells(); } else { ComputeNumberOfCellsAndTypes(); switch(dim) { case 0: result=this->NumberOf0DCells; break; case 1: result=this->NumberOf1DCells; break; case 2: result=this->NumberOf2DCells; break; case 3: result=this->NumberOf3DCells; break; } } } assert("post: positive_result" && result>=0); return result; } //---------------------------------------------------------------------------- // Description: // Return -1 if the dataset is explicitly defined by cells of several // dimensions or if there is no cell. If the dataset is explicitly defined by // cells of a unique dimension, return this dimension. // \post valid_range: (result>=-1) && (result<=3) int vtkBridgeDataSet::GetCellDimension() { int result=0; int accu=0; this->ComputeNumberOfCellsAndTypes(); if(this->NumberOf0DCells!=0) { accu++; result=0; } if(this->NumberOf1DCells!=0) { accu++; result=1; } if(this->NumberOf2DCells!=0) { accu++; result=2; } if(this->NumberOf3DCells!=0) { accu++; result=3; } if(accu!=1) // no cells at all or several dimensions { result=-1; } assert("post: valid_range" && (result>=-1) && (result<=3)); return result; } //---------------------------------------------------------------------------- // Description: // Get a list of types of cells in a dataset. The list consists of an array // of types (not necessarily in any order), with a single entry per type. // For example a dataset 5 triangles, 3 lines, and 100 hexahedra would // result a list of three entries, corresponding to the types VTK_TRIANGLE, // VTK_LINE, and VTK_HEXAHEDRON. // THIS METHOD IS THREAD SAFE IF FIRST CALLED FROM A SINGLE THREAD AND // THE DATASET IS NOT MODIFIED // \pre types_exist: types!=0 void vtkBridgeDataSet::GetCellTypes(vtkCellTypes *types) { assert("pre: types_exist" && types!=0); int i; int c; this->ComputeNumberOfCellsAndTypes(); // copy from `this->Types' to `types'. types->Reset(); c=this->Types->GetNumberOfTypes(); i=0; while(i<c) { types->InsertNextType(this->Types->GetCellType(i)); ++i; } } //---------------------------------------------------------------------------- // Description: // Cells of dimension `dim' (or all dimensions if -1) that explicitly define // the dataset. For instance, it will return only tetrahedra if the mesh is // defined by tetrahedra. If the mesh is composed of two parts, one with // tetrahedra and another part with triangles, it will return both, but will // not return edges and vertices. // \pre valid_dim_range: (dim>=-1) && (dim<=3) // \post result_exists: result!=0 vtkGenericCellIterator *vtkBridgeDataSet::NewCellIterator(int dim) { assert("pre: valid_dim_range" && (dim>=-1) && (dim<=3)); vtkBridgeCellIterator *result=vtkBridgeCellIterator::New(); result->InitWithDataSet(this,dim); // vtkBridgeCellIteratorOnDataSetCells assert("post: result_exists" && result!=0); return result; } //---------------------------------------------------------------------------- // Description: // Boundaries of dimension `dim' (or all dimensions if -1) of the dataset. // If `exteriorOnly' is true, only the exterior boundaries of the dataset // will be returned, otherwise it will return exterior and interior // boundaries. // \pre valid_dim_range: (dim>=-1) && (dim<=2) // \post result_exists: result!=0 vtkGenericCellIterator *vtkBridgeDataSet::NewBoundaryIterator(int dim, int exteriorOnly) { assert("pre: valid_dim_range" && (dim>=-1) && (dim<=2)); vtkBridgeCellIterator *result=vtkBridgeCellIterator::New(); result->InitWithDataSetBoundaries(this,dim,exteriorOnly); //vtkBridgeCellIteratorOnDataSetBoundaries(dim,exterior_only); assert("post: result_exists" && result!=0); return result; } //---------------------------------------------------------------------------- // Description: // Points composing the dataset; they can be on a vertex or isolated. // \post result_exists: result!=0 vtkGenericPointIterator *vtkBridgeDataSet::NewPointIterator() { vtkBridgePointIterator *result=vtkBridgePointIterator::New(); result->InitWithDataSet(this); assert("post: result_exists" && result!=0); return result; } //---------------------------------------------------------------------------- // Description: // Estimated size needed after tessellation (or special operation) vtkIdType vtkBridgeDataSet::GetEstimatedSize() { return this->GetNumberOfPoints()*this->GetNumberOfCells(); } //---------------------------------------------------------------------------- // Description: // Locate closest cell to position `x' (global coordinates) with respect to // a tolerance squared `tol2' and an initial guess `cell' (if valid). The // result consists in the `cell', the `subId' of the sub-cell (0 if primary // cell), the parametric coordinates `pcoord' of the position. It returns // whether the position is inside the cell or not. Tolerance is used to // control how close the point is to be considered "in" the cell. // THIS METHOD IS NOT THREAD SAFE. // \pre not_empty: GetNumberOfCells()>0 // \pre cell_exists: cell!=0 // \pre positive_tolerance: tol2>0 // \post clamped_pcoords: result implies (0<=pcoords[0]<=1 && ) int vtkBridgeDataSet::FindCell(double x[3], vtkGenericCellIterator* &cell, double tol2, int &subId, double pcoords[3]) { assert("pre: not_empty" && GetNumberOfCells()>0); assert("pre: cell_exists" && cell!=0); assert("pre: positive_tolerance" && tol2>0); vtkIdType cellid; vtkBridgeCell *c; vtkBridgeCellIterator *it=static_cast<vtkBridgeCellIterator *>(cell); vtkCell *c2; double *ignoredWeights=new double[this->Implementation->GetMaxCellSize()]; if(cell->IsAtEnd()) { cellid=this->Implementation->FindCell(x,0,0,tol2,subId,pcoords, ignoredWeights); } else { c=static_cast<vtkBridgeCell *>(cell->GetCell()); c2=c->Cell; // bridge cellid=c->GetId(); // adaptor cellid=this->Implementation->FindCell(x,c2,cellid,tol2,subId,pcoords, ignoredWeights); } delete [] ignoredWeights; if(cellid>=0) { it->InitWithOneCell(this,cellid); // at end it->Begin(); // clamp: int i=0; while(i<3) { if(pcoords[i]<0) { pcoords[i]=0; } else if(pcoords[i]>1) { pcoords[i]=1; } ++i; } } // A=>B: !A || B // result => clamped pcoords assert("post: clamped_pcoords" && ((cellid<0)||(pcoords[0]>=0 && pcoords[0]<=1 && pcoords[1]>=0 && pcoords[1]<=1 && pcoords[2]>=0 && pcoords[2]<=1))); return cellid>=0; // bool } //---------------------------------------------------------------------------- // Description: // Locate closest point `p' to position `x' (global coordinates) // \pre not_empty: GetNumberOfPoints()>0 // \pre p_exists: p!=0 void vtkBridgeDataSet::FindPoint(double x[3], vtkGenericPointIterator *p) { assert("pre: not_empty" && GetNumberOfPoints()>0); assert("pre: p_exists" && p!=0); vtkBridgePointIterator *bp=static_cast<vtkBridgePointIterator *>(p); if(this->Implementation!=0) { vtkIdType pt=this->Implementation->FindPoint(x); bp->InitWithOnePoint(this,pt); } else { bp->InitWithOnePoint(this,-1); } } //---------------------------------------------------------------------------- // Description: // Datasets are composite objects and need to check each part for MTime. unsigned long int vtkBridgeDataSet::GetMTime() { unsigned long result; unsigned long mtime; result = vtkGenericDataSet::GetMTime(); if(this->Implementation!=0) { mtime = this->Implementation->GetMTime(); result = ( mtime > result ? mtime : result ); } return result; } //---------------------------------------------------------------------------- // Description: // Compute the geometry bounding box. void vtkBridgeDataSet::ComputeBounds() { double *bounds; if ( this->GetMTime() > this->ComputeTime ) { if(this->Implementation!=0) { this->Implementation->ComputeBounds(); this->ComputeTime.Modified(); bounds=this->Implementation->GetBounds(); memcpy(this->Bounds,bounds,sizeof(double)*6); } else { vtkMath::UninitializeBounds(this->Bounds); } this->ComputeTime.Modified(); } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "SteelCoil.h" #include <QListIterator> #include <QMessageBox> #include <QFile> #include <unistd.h> #include <iostream> #include <QtSql> //class SteelCoil; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { delete ui; QFile img("image.png"); img.remove(); QFile img1("out.jpg"); img1.remove(); QFile img2("outi.jpg"); img2.remove(); } void MainWindow::init(){ ui->stackedWidget->setCurrentIndex(0); if(QCameraInfo::availableCameras().count() > 0){ camera = new QCamera(QCamera::FrontFace); qInfo("Front camera selected"); camera->setViewfinder(ui->viewWindow_ScanID); camera->setCaptureMode(QCamera::CaptureStillImage); camera->start(); } else{ qInfo("No camera available"); } // build sample database ds = new ShipmentSchedule(); ds->BuildDatabase(); //create ocr object ocr = new OCR(); } //main menu click functions void MainWindow::on_scanButton_Main_clicked() { ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_jobButton_Main_clicked() { ui->stackedWidget->setCurrentIndex(4); QVBoxLayout* containerLayout = new QVBoxLayout(); QWidget* widget = new QWidget(); QVector<RailCar*> cars = ds->getCars(); for(int i=0; i<cars.size(); i++){ containerLayout->addWidget(buildMainBlock(cars[i])); } widget->setLayout(containerLayout); ui->scrollArea_JobList->setWidget(widget); } //scanID click functions void MainWindow::on_backButton_ScanID_clicked() { ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_photoButton_ScanID_clicked() { camImage = QGuiApplication::primaryScreen()->grabWindow(ui->viewWindow_ScanID->winId()); ui->stackedWidget->setCurrentIndex(2); ui->viewWindow_VerifyID->setPixmap(camImage); //save the image if(camImage.save("image.png", "PNG")){ qInfo("image.png saved"); } else{ qInfo("Image not saved"); } //run ocr ocrID = ocr->getId("image.png"); //ocrID = "IHB 166590"; ui->railcarIDLabel_VerifyID->setText(ocrID); std::cerr<<ocrID.toStdString()<<endl; //set ocr output to textbox } //verifyID click functions void MainWindow::on_retakeButton_VerifyID_clicked() { ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_backButton_VerifyID_clicked() { ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_correctButton_VerifyID_clicked() { //get railcar object for confirmed id ocrID = ui->railcarIDLabel_VerifyID->text(); ocrCar = ds->GetCar(ocrID); if(ocrCar == nullptr){ QMessageBox::information(this,tr("NOTICE"),tr("GIVEN RAILCAR ID NOT FOUND")); return; } ui->stackedWidget->setCurrentIndex(3); QVBoxLayout* containerLayout = new QVBoxLayout(); QWidget* widget = new QWidget(); containerLayout->addWidget(buildMainBlock(ocrCar)); widget->setLayout(containerLayout); ui->scrollArea_ScanCoil->setWidget(widget); } //scanCoil click functions void MainWindow::on_scanIDButton_ScanCoil_clicked() { ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_mainButton_ScanCoil_clicked() { ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_confirmButton_ScanCoil_clicked() { //BARCODE SCANNING LOGIC HERE QString s = ui->barcodeInput_ScanCoil->text(); //assign plaintext QString subString=s.mid(0,1); QString barcodenum = s; ui->barcodeInput_ScanCoil->clear();//clear text box everytime ui->barcodeInput_ScanCoil->setFocus(); //parsing if(subString=="I"||subString=="O") { s = s.simplified(); QStringList barcode = s.split("A"); barcodenum = barcode.at(1); barcodenum = barcodenum.simplified(); } if (subString=="*") { QStringList barcode = s.split("*"); barcodenum = barcode.at(1); } //checking QVector<SteelCoil*> coils = ocrCar->getCoilVector(); for(int i=0; i<coils.size(); i++){ if(coils[i]->GetCoil() == barcodenum && !coils[i]->isVerified()){ coils[i]->verify(); ocrCar->verify(); ds->UpdateDatabase(coils[i]->GetCoil(), ocrCar); QVBoxLayout* containerLayout = new QVBoxLayout(); QWidget* widget = new QWidget(); containerLayout->addWidget(buildMainBlock(ocrCar)); widget->setLayout(containerLayout); ui->scrollArea_ScanCoil->setWidget(widget); return; } } //not found QMessageBox::information(this,tr("NOTICE"),tr("COIL ID DOES NOT MATCH RAIL CAR")); } //jobList click functions void MainWindow::on_mainButton_JobList_clicked() { ui->stackedWidget->setCurrentIndex(0); } //utility functions QWidget* MainWindow::buildMainBlock(RailCar* railCar){ QHBoxLayout* mainLayout = new QHBoxLayout(); QVBoxLayout* left = new QVBoxLayout(); QVBoxLayout* right = new QVBoxLayout(); QWidget* widget = new QWidget(); QLabel* id = new QLabel(); id->setText(railCar->getCarID()); id->setAlignment(Qt::AlignCenter | Qt::AlignLeft); if(railCar->isVerified()){ id->setStyleSheet("background-color: rgba(13, 135, 35, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px; padding: 5px;"); } else{ id->setStyleSheet("background-color: rgba(249, 36, 24, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px; padding: 5px;"); } id->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); left->addWidget(id); QWidget* empty = new QWidget(); empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); empty->setStyleSheet("border: 0px;"); left->addWidget(empty); QVector<SteelCoil*> coils = railCar->getCoilVector(); for(int i=0; i<coils.size(); i++){ right->addWidget(buildRailCar(coils[i])); } mainLayout->addLayout(left); mainLayout->addLayout(right); widget->setStyleSheet("border: 1px solid black; margin: 5px;"); widget->setLayout(mainLayout); return widget; } QLabel* MainWindow::buildRailCar(SteelCoil* sCoil){ QLabel* coil = new QLabel(); coil->setText(sCoil->GetCoil()); if(sCoil->isVerified()){ coil->setStyleSheet("background-color: rgba(13, 135, 35, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px;"); } else{ coil->setStyleSheet("background-color: rgba(246, 255, 12, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px;"); } coil->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); return coil; } <commit_msg>Update mainwindow.cpp<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "SteelCoil.h" #include <QListIterator> #include <QMessageBox> #include <QFile> #include <unistd.h> #include <iostream> #include <QtSql> //class SteelCoil; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { // remove extra comma at the end of the string verified_coils = verified_coils.left(verified_coils.length()-1); verified_RC = verified_RC.left(verified_RC.length()-1); qDebug() << verified_coils << " " << verified_RC; ds->UpdateDatabase(verified_coils, verified_RC); delete ui; QFile img("image.png"); img.remove(); QFile img1("out.jpg"); img1.remove(); QFile img2("outi.jpg"); img2.remove(); } void MainWindow::init(){ ui->stackedWidget->setCurrentIndex(0); if(QCameraInfo::availableCameras().count() > 0){ camera = new QCamera(QCamera::FrontFace); qInfo("Front camera selected"); camera->setViewfinder(ui->viewWindow_ScanID); camera->setCaptureMode(QCamera::CaptureStillImage); camera->start(); } else{ qInfo("No camera available"); } // build sample database ds = new ShipmentSchedule(); ds->BuildDatabase(); //create ocr object ocr = new OCR(); } //main menu click functions void MainWindow::on_scanButton_Main_clicked() { ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_jobButton_Main_clicked() { ui->stackedWidget->setCurrentIndex(4); QVBoxLayout* containerLayout = new QVBoxLayout(); QWidget* widget = new QWidget(); QVector<RailCar*> cars = ds->getCars(); for(int i=0; i<cars.size(); i++){ containerLayout->addWidget(buildMainBlock(cars[i])); } widget->setLayout(containerLayout); ui->scrollArea_JobList->setWidget(widget); } //scanID click functions void MainWindow::on_backButton_ScanID_clicked() { ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_photoButton_ScanID_clicked() { camImage = QGuiApplication::primaryScreen()->grabWindow(ui->viewWindow_ScanID->winId()); ui->stackedWidget->setCurrentIndex(2); ui->viewWindow_VerifyID->setPixmap(camImage); //save the image if(camImage.save("image.png", "PNG")){ qInfo("image.png saved"); } else{ qInfo("Image not saved"); } //run ocr ocrID = ocr->getId("image.png"); //ocrID = "IHB 166590"; ui->railcarIDLabel_VerifyID->setText(ocrID); std::cerr<<ocrID.toStdString()<<endl; //set ocr output to textbox } //verifyID click functions void MainWindow::on_retakeButton_VerifyID_clicked() { ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_backButton_VerifyID_clicked() { ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_correctButton_VerifyID_clicked() { //get railcar object for confirmed id ocrID = ui->railcarIDLabel_VerifyID->text(); ocrCar = ds->GetCar(ocrID); if(ocrCar == nullptr){ QMessageBox::information(this,tr("NOTICE"),tr("GIVEN RAILCAR ID NOT FOUND")); return; } ui->stackedWidget->setCurrentIndex(3); QVBoxLayout* containerLayout = new QVBoxLayout(); QWidget* widget = new QWidget(); containerLayout->addWidget(buildMainBlock(ocrCar)); widget->setLayout(containerLayout); ui->scrollArea_ScanCoil->setWidget(widget); } //scanCoil click functions void MainWindow::on_scanIDButton_ScanCoil_clicked() { ui->stackedWidget->setCurrentIndex(1); } void MainWindow::on_mainButton_ScanCoil_clicked() { ui->stackedWidget->setCurrentIndex(0); } void MainWindow::on_confirmButton_ScanCoil_clicked() { //BARCODE SCANNING LOGIC HERE QString s = ui->barcodeInput_ScanCoil->text(); //assign plaintext QString subString=s.mid(0,1); QString barcodenum = s; ui->barcodeInput_ScanCoil->clear();//clear text box everytime ui->barcodeInput_ScanCoil->setFocus(); //parsing if(subString=="I"||subString=="O") { s = s.simplified(); QStringList barcode = s.split("A"); barcodenum = barcode.at(1); barcodenum = barcodenum.simplified(); } if (subString=="*") { QStringList barcode = s.split("*"); barcodenum = barcode.at(1); } //checking QVector<SteelCoil*> coils = ocrCar->getCoilVector(); for(int i=0; i<coils.size(); i++){ if(coils[i]->GetCoil() == barcodenum && !coils[i]->isVerified()){ coils[i]->verify(); ocrCar->verify(); // save verified coils into string for updating database later verified_coils += "'" + coils[i]->GetCoil()+ "',"; // save verified railcar if (ocrCar->isVerified()) verified_RC += "'" + ocrCar->getCarID() + "',"; QVBoxLayout* containerLayout = new QVBoxLayout(); QWidget* widget = new QWidget(); containerLayout->addWidget(buildMainBlock(ocrCar)); widget->setLayout(containerLayout); ui->scrollArea_ScanCoil->setWidget(widget); return; } } //not found QMessageBox::information(this,tr("NOTICE"),tr("COIL ID DOES NOT MATCH RAIL CAR")); } //jobList click functions void MainWindow::on_mainButton_JobList_clicked() { ui->stackedWidget->setCurrentIndex(0); } //utility functions QWidget* MainWindow::buildMainBlock(RailCar* railCar){ QHBoxLayout* mainLayout = new QHBoxLayout(); QVBoxLayout* left = new QVBoxLayout(); QVBoxLayout* right = new QVBoxLayout(); QWidget* widget = new QWidget(); QLabel* id = new QLabel(); id->setText(railCar->getCarID()); id->setAlignment(Qt::AlignCenter | Qt::AlignLeft); if(railCar->isVerified()){ id->setStyleSheet("background-color: rgba(13, 135, 35, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px; padding: 5px;"); } else{ id->setStyleSheet("background-color: rgba(249, 36, 24, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px; padding: 5px;"); } id->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); left->addWidget(id); QWidget* empty = new QWidget(); empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); empty->setStyleSheet("border: 0px;"); left->addWidget(empty); QVector<SteelCoil*> coils = railCar->getCoilVector(); for(int i=0; i<coils.size(); i++){ right->addWidget(buildRailCar(coils[i])); } mainLayout->addLayout(left); mainLayout->addLayout(right); widget->setStyleSheet("border: 1px solid black; margin: 5px;"); widget->setLayout(mainLayout); return widget; } QLabel* MainWindow::buildRailCar(SteelCoil* sCoil){ QLabel* coil = new QLabel(); coil->setText(sCoil->GetCoil()); if(sCoil->isVerified()){ coil->setStyleSheet("background-color: rgba(13, 135, 35, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px;"); } else{ coil->setStyleSheet("background-color: rgba(246, 255, 12, .4); color: black; opacity: .5; border: 1px solid black; margin: 5px;"); } coil->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); return coil; } <|endoftext|>
<commit_before> #define OLDEST_FILE_NUMBER 1 #define MAXFILENUM 4 #define MAXUPLOADFILENUM 15 #define MAXFILESIZE_KB 12.5 * 1024 int WriteStumble::sCurrentFileNumber = 1; int WriteStumble::sUploadFileNumber = 0; nsCString Filename(int aFileNum) { return nsPrintfCString("feeding-%d.json.gz", aFileNum); } nsCString UploadFilename(int aFileNum) { return nsPrintfCString("upload-%.2d.json.gz", aFileNum); } nsCString GetDir() { return NS_LITERAL_CSTRING("stumble"); } void SetUploadFileNum() { for (int i = 1; i <= MAXUPLOADFILENUM; i++) { nsresult rv; nsCOMPtr<nsIFile> tmpFile; rv = nsDumpUtils::OpenTempFile(UploadFilename(i), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("OpenFile failed"); return; } int64_t fileSize = 0; rv = tmpFile->GetFileSize(&fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("GetFileSize failed"); return; } if (fileSize == 0) { WriteStumble::sUploadFileNumber = i - 1; tmpFile->Remove(true); return; } } WriteStumble::sUploadFileNumber = MAXUPLOADFILENUM; STUMBLER_DBG("SetUploadFile filenum = %d (End)\n", WriteStumble::sUploadFileNumber); } nsresult RemoveOldestUploadFile(int aFileCount) { // remove oldest upload file nsCOMPtr<nsIFile> tmpFile; nsresult rv = nsDumpUtils::OpenTempFile(UploadFilename(OLDEST_FILE_NUMBER), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); nsAutoString targetFilename; rv = tmpFile->GetLeafName(targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = tmpFile->Remove(true); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Rename the upload files. (keep the oldest file as 'upload-1.json.gz') for (int idx = 0; idx < aFileCount; idx++) { nsCOMPtr<nsIFile> file; nsDumpUtils::OpenTempFile(UploadFilename(idx+1), getter_AddRefs(file), GetDir(), nsDumpUtils::CREATE); nsAutoString currentFilename; rv = file->GetLeafName(currentFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = file->MoveTo(/* directory */ nullptr, targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } targetFilename = currentFilename; // keep current leafname for next iteration usage } WriteStumble::sUploadFileNumber--; return NS_OK; } nsresult WriteStumble::MoveOldestFileAsUploadFile() { nsresult rv; // make sure that uploadfile number is less than MAXUPLOADFILENUM if (sUploadFileNumber == MAXUPLOADFILENUM) { rv = RemoveOldestUploadFile(MAXUPLOADFILENUM); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } sUploadFileNumber++; // Find out the target name of upload file we need nsCOMPtr<nsIFile> tmpFile; rv = nsDumpUtils::OpenTempFile(UploadFilename(sUploadFileNumber), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); nsAutoString targetFilename; rv = tmpFile->GetLeafName(targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Rename the feeding file. (keep the oldest file as 'feeding-1.json.gz') // feeding-1.json.gz to upload-%d.json.gz // feeding-4.json.jz -> feeding-3.json.jz -> feeding-2.json.jz -> feeding-1.json.jz for (int idx = 0; idx < MAXFILENUM; idx++) { nsCOMPtr<nsIFile> file; nsDumpUtils::OpenTempFile(Filename(idx+1), getter_AddRefs(file), GetDir(), nsDumpUtils::CREATE); nsAutoString currentFilename; rv = file->GetLeafName(currentFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = file->MoveTo(/* directory */ nullptr, targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } targetFilename = currentFilename; // keep current leafname for next iteration usage } return NS_OK; } void WriteStumble::WriteJSON(Partition aPart, int aFileNum) { nsCOMPtr<nsIFile> tmpFile; nsresult rv; rv = nsDumpUtils::OpenTempFile(Filename(aFileNum), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("Open a file for stumble failed"); return; } nsRefPtr<nsGZFileWriter> gzWriter = new nsGZFileWriter(nsGZFileWriter::Append); rv = gzWriter->Init(tmpFile); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("gzWriter init failed"); return; } /* The json format is like below. {items:[ {item}, {item}, {item} ]} */ // Need to add "]}" after the last item if (aPart == End) { gzWriter->Write("]}"); rv = gzWriter->Finish(); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("gzWriter finish failed"); } sCurrentFileNumber++; return; } // Need to add "{items:[" before the first item if (aPart == Begining) { gzWriter->Write("{\"items\":[{"); } else if (aPart == Middle) { gzWriter->Write(",{"); } gzWriter->Write(mDesc.get()); // one item is end with '}' (e.g. {item}) gzWriter->Write("}"); rv = gzWriter->Finish(); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("gzWriter finish failed"); } // check if it is the end of this file int64_t fileSize = 0; rv = tmpFile->GetFileSize(&fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("GetFileSize failed"); return; } if (fileSize >= MAXFILESIZE_KB) { WriteJSON(End, sCurrentFileNumber); return; } } WriteStumble::Partition WriteStumble::SetCurrentFile() { nsresult rv; if (sCurrentFileNumber > MAXFILENUM) { rv = MoveOldestFileAsUploadFile(); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("Remove oldest file failed"); return Unknown; } sCurrentFileNumber = MAXFILENUM; } nsCOMPtr<nsIFile> tmpFile; rv = nsDumpUtils::OpenTempFile(Filename(sCurrentFileNumber), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("Open a file for stumble failed"); return Unknown; } int64_t fileSize = 0; rv = tmpFile->GetFileSize(&fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("GetFileSize failed"); return Unknown; } if (fileSize == 0) { return Begining; } else if (fileSize >= MAXFILESIZE_KB) { sCurrentFileNumber++; return SetCurrentFile(); } else { return Middle; } } void WriteStumble::Run() { STUMBLER_DBG("In WriteStumble\n"); Partition partition = SetCurrentFile(); if (partition == Unknown) { STUMBLER_ERR("SetCurrentFile failed, skip once"); return; } else { WriteJSON(partition, sCurrentFileNumber); return; } } <commit_msg>Assert is NOT main thread on every function<commit_after> #define OLDEST_FILE_NUMBER 1 #define MAXFILENUM 4 #define MAXUPLOADFILENUM 15 #define MAXFILESIZE_KB 12.5 * 1024 int WriteStumble::sCurrentFileNumber = 1; int WriteStumble::sUploadFileNumber = 0; nsCString Filename(int aFileNum) { return nsPrintfCString("feeding-%d.json.gz", aFileNum); } nsCString UploadFilename(int aFileNum) { return nsPrintfCString("upload-%.2d.json.gz", aFileNum); } nsCString GetDir() { return NS_LITERAL_CSTRING("stumble"); } void SetUploadFileNum() { MOZ_ASSERT(!NS_IsMainThread()); for (int i = 1; i <= MAXUPLOADFILENUM; i++) { nsresult rv; nsCOMPtr<nsIFile> tmpFile; rv = nsDumpUtils::OpenTempFile(UploadFilename(i), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("OpenFile failed"); return; } int64_t fileSize = 0; rv = tmpFile->GetFileSize(&fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("GetFileSize failed"); return; } if (fileSize == 0) { WriteStumble::sUploadFileNumber = i - 1; tmpFile->Remove(true); return; } } WriteStumble::sUploadFileNumber = MAXUPLOADFILENUM; STUMBLER_DBG("SetUploadFile filenum = %d (End)\n", WriteStumble::sUploadFileNumber); } nsresult RemoveOldestUploadFile(int aFileCount) { MOZ_ASSERT(!NS_IsMainThread()); // remove oldest upload file nsCOMPtr<nsIFile> tmpFile; nsresult rv = nsDumpUtils::OpenTempFile(UploadFilename(OLDEST_FILE_NUMBER), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); nsAutoString targetFilename; rv = tmpFile->GetLeafName(targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = tmpFile->Remove(true); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Rename the upload files. (keep the oldest file as 'upload-1.json.gz') for (int idx = 0; idx < aFileCount; idx++) { nsCOMPtr<nsIFile> file; nsDumpUtils::OpenTempFile(UploadFilename(idx+1), getter_AddRefs(file), GetDir(), nsDumpUtils::CREATE); nsAutoString currentFilename; rv = file->GetLeafName(currentFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = file->MoveTo(/* directory */ nullptr, targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } targetFilename = currentFilename; // keep current leafname for next iteration usage } WriteStumble::sUploadFileNumber--; return NS_OK; } nsresult WriteStumble::MoveOldestFileAsUploadFile() { MOZ_ASSERT(!NS_IsMainThread()); nsresult rv; // make sure that uploadfile number is less than MAXUPLOADFILENUM if (sUploadFileNumber == MAXUPLOADFILENUM) { rv = RemoveOldestUploadFile(MAXUPLOADFILENUM); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } sUploadFileNumber++; // Find out the target name of upload file we need nsCOMPtr<nsIFile> tmpFile; rv = nsDumpUtils::OpenTempFile(UploadFilename(sUploadFileNumber), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); nsAutoString targetFilename; rv = tmpFile->GetLeafName(targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Rename the feeding file. (keep the oldest file as 'feeding-1.json.gz') // feeding-1.json.gz to upload-%d.json.gz // feeding-4.json.jz -> feeding-3.json.jz -> feeding-2.json.jz -> feeding-1.json.jz for (int idx = 0; idx < MAXFILENUM; idx++) { nsCOMPtr<nsIFile> file; nsDumpUtils::OpenTempFile(Filename(idx+1), getter_AddRefs(file), GetDir(), nsDumpUtils::CREATE); nsAutoString currentFilename; rv = file->GetLeafName(currentFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = file->MoveTo(/* directory */ nullptr, targetFilename); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } targetFilename = currentFilename; // keep current leafname for next iteration usage } return NS_OK; } void WriteStumble::WriteJSON(Partition aPart, int aFileNum) { MOZ_ASSERT(!NS_IsMainThread()); nsCOMPtr<nsIFile> tmpFile; nsresult rv; rv = nsDumpUtils::OpenTempFile(Filename(aFileNum), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("Open a file for stumble failed"); return; } nsRefPtr<nsGZFileWriter> gzWriter = new nsGZFileWriter(nsGZFileWriter::Append); rv = gzWriter->Init(tmpFile); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("gzWriter init failed"); return; } /* The json format is like below. {items:[ {item}, {item}, {item} ]} */ // Need to add "]}" after the last item if (aPart == End) { gzWriter->Write("]}"); rv = gzWriter->Finish(); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("gzWriter finish failed"); } sCurrentFileNumber++; return; } // Need to add "{items:[" before the first item if (aPart == Begining) { gzWriter->Write("{\"items\":[{"); } else if (aPart == Middle) { gzWriter->Write(",{"); } gzWriter->Write(mDesc.get()); // one item is end with '}' (e.g. {item}) gzWriter->Write("}"); rv = gzWriter->Finish(); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("gzWriter finish failed"); } // check if it is the end of this file int64_t fileSize = 0; rv = tmpFile->GetFileSize(&fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("GetFileSize failed"); return; } if (fileSize >= MAXFILESIZE_KB) { WriteJSON(End, sCurrentFileNumber); return; } } WriteStumble::Partition WriteStumble::SetCurrentFile() { MOZ_ASSERT(!NS_IsMainThread()); nsresult rv; if (sCurrentFileNumber > MAXFILENUM) { rv = MoveOldestFileAsUploadFile(); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("Remove oldest file failed"); return Unknown; } sCurrentFileNumber = MAXFILENUM; } nsCOMPtr<nsIFile> tmpFile; rv = nsDumpUtils::OpenTempFile(Filename(sCurrentFileNumber), getter_AddRefs(tmpFile), GetDir(), nsDumpUtils::CREATE); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("Open a file for stumble failed"); return Unknown; } int64_t fileSize = 0; rv = tmpFile->GetFileSize(&fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { STUMBLER_ERR("GetFileSize failed"); return Unknown; } if (fileSize == 0) { return Begining; } else if (fileSize >= MAXFILESIZE_KB) { sCurrentFileNumber++; return SetCurrentFile(); } else { return Middle; } } void WriteStumble::Run() { MOZ_ASSERT(!NS_IsMainThread()); STUMBLER_DBG("In WriteStumble\n"); Partition partition = SetCurrentFile(); if (partition == Unknown) { STUMBLER_ERR("SetCurrentFile failed, skip once"); return; } else { WriteJSON(partition, sCurrentFileNumber); return; } } <|endoftext|>
<commit_before>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These tablegen backends emit Clang diagnostics tables. // //===----------------------------------------------------------------------===// #include "ClangDiagnosticsEmitter.h" #include "Record.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/VectorExtras.h" #include <set> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Diagnostic category computation code. //===----------------------------------------------------------------------===// namespace { class DiagGroupParentMap { RecordKeeper &Records; std::map<const Record*, std::vector<Record*> > Mapping; public: DiagGroupParentMap(RecordKeeper &records) : Records(records) { std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { std::vector<Record*> SubGroups = DiagGroups[i]->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) Mapping[SubGroups[j]].push_back(DiagGroups[i]); } } const std::vector<Record*> &getParents(const Record *Group) { return Mapping[Group]; } }; } // end anonymous namespace. static std::string getCategoryFromDiagGroup(const Record *Group, DiagGroupParentMap &DiagGroupParents) { // If the DiagGroup has a category, return it. std::string CatName = Group->getValueAsString("CategoryName"); if (!CatName.empty()) return CatName; // The diag group may the subgroup of one or more other diagnostic groups, // check these for a category as well. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group); for (unsigned i = 0, e = Parents.size(); i != e; ++i) { CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents); if (!CatName.empty()) return CatName; } return ""; } /// getDiagnosticCategory - Return the category that the specified diagnostic /// lives in. static std::string getDiagnosticCategory(const Record *R, DiagGroupParentMap &DiagGroupParents) { // If the diagnostic is in a group, and that group has a category, use it. if (DefInit *Group = dynamic_cast<DefInit*>(R->getValueInit("Group"))) { // Check the diagnostic's diag group for a category. std::string CatName = getCategoryFromDiagGroup(Group->getDef(), DiagGroupParents); if (!CatName.empty()) return CatName; } // If the diagnostic itself has a category, get it. return R->getValueAsString("CategoryName"); } namespace { class DiagCategoryIDMap { RecordKeeper &Records; StringMap<unsigned> CategoryIDs; std::vector<std::string> CategoryStrings; public: DiagCategoryIDMap(RecordKeeper &records) : Records(records) { DiagGroupParentMap ParentInfo(Records); // The zero'th category is "". CategoryStrings.push_back(""); CategoryIDs[""] = 0; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { std::string Category = getDiagnosticCategory(Diags[i], ParentInfo); if (Category.empty()) continue; // Skip diags with no category. unsigned &ID = CategoryIDs[Category]; if (ID != 0) continue; // Already seen. ID = CategoryStrings.size(); CategoryStrings.push_back(Category); } } unsigned getID(StringRef CategoryString) { return CategoryIDs[CategoryString]; } typedef std::vector<std::string>::iterator iterator; iterator begin() { return CategoryStrings.begin(); } iterator end() { return CategoryStrings.end(); } }; } // end anonymous namespace. //===----------------------------------------------------------------------===// // Warning Tables (.inc file) generation. //===----------------------------------------------------------------------===// void ClangDiagsDefsEmitter::run(raw_ostream &OS) { // Write the #if guard if (!Component.empty()) { std::string ComponentName = UppercaseString(Component); OS << "#ifdef " << ComponentName << "START\n"; OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName << ",\n"; OS << "#undef " << ComponentName << "START\n"; OS << "#endif\n\n"; } const std::vector<Record*> &Diags = Records.getAllDerivedDefinitions("Diagnostic"); DiagCategoryIDMap CategoryIDs(Records); DiagGroupParentMap DGParentMap(Records); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record &R = *Diags[i]; // Filter by component. if (!Component.empty() && Component != R.getValueAsString("Component")) continue; OS << "DIAG(" << R.getName() << ", "; OS << R.getValueAsDef("Class")->getName(); OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName(); // Description string. OS << ", \""; OS.write_escaped(R.getValueAsString("Text")) << '"'; // Warning associated with the diagnostic. if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) { OS << ", \""; OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"'; } else { OS << ", 0"; } // SFINAE bit if (R.getValueAsBit("SFINAE")) OS << ", true"; else OS << ", false"; // Category number. OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap)); OS << ")\n"; } } //===----------------------------------------------------------------------===// // Warning Group Tables generation //===----------------------------------------------------------------------===// struct GroupInfo { std::vector<const Record*> DiagsInGroup; std::vector<std::string> SubGroups; unsigned IDNo; }; void ClangDiagGroupsEmitter::run(raw_ostream &OS) { // Compute a mapping from a DiagGroup to all of its parents. DiagGroupParentMap DGParentMap(Records); // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of // groups to diags in the group. std::map<std::string, GroupInfo> DiagsInGroup; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (DI == 0) continue; std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { Record *Group = DiagGroups[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; // Walk through the groups emitting an array for each diagnostic of the diags // that are mapped to. OS << "\n#ifdef GET_DIAG_ARRAYS\n"; unsigned MaxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { MaxLen = std::max(MaxLen, (unsigned)I->first.size()); std::vector<const Record*> &V = I->second.DiagsInGroup; if (!V.empty()) { OS << "static const short DiagArray" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = V.size(); i != e; ++i) OS << "diag::" << V[i]->getName() << ", "; OS << "-1 };\n"; } const std::vector<std::string> &SubGroups = I->second.SubGroups; if (!SubGroups.empty()) { OS << "static const short DiagSubGroup" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) { std::map<std::string, GroupInfo>::iterator RI = DiagsInGroup.find(SubGroups[i]); assert(RI != DiagsInGroup.end() && "Referenced without existing?"); OS << RI->second.IDNo << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_DIAG_ARRAYS\n\n"; // Emit the table now. OS << "\n#ifdef GET_DIAG_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { // Group option string. OS << " { \""; OS.write_escaped(I->first) << "\"," << std::string(MaxLen-I->first.size()+1, ' '); // Diagnostics in the group. if (I->second.DiagsInGroup.empty()) OS << "0, "; else OS << "DiagArray" << I->second.IDNo << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << 0; else OS << "DiagSubGroup" << I->second.IDNo; OS << " },\n"; } OS << "#endif // GET_DIAG_TABLE\n\n"; // Emit the category table next. DiagCategoryIDMap CategoriesByID(Records); OS << "\n#ifdef GET_CATEGORY_TABLE\n"; for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(), E = CategoriesByID.end(); I != E; ++I) OS << "CATEGORY(\"" << *I << "\")\n"; OS << "#endif // GET_CATEGORY_TABLE\n\n"; } <commit_msg>Clang: separate the access-control diagnostics from other diagnostics that do not have SFINAE behavior.<commit_after>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These tablegen backends emit Clang diagnostics tables. // //===----------------------------------------------------------------------===// #include "ClangDiagnosticsEmitter.h" #include "Record.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/VectorExtras.h" #include <set> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Diagnostic category computation code. //===----------------------------------------------------------------------===// namespace { class DiagGroupParentMap { RecordKeeper &Records; std::map<const Record*, std::vector<Record*> > Mapping; public: DiagGroupParentMap(RecordKeeper &records) : Records(records) { std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { std::vector<Record*> SubGroups = DiagGroups[i]->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) Mapping[SubGroups[j]].push_back(DiagGroups[i]); } } const std::vector<Record*> &getParents(const Record *Group) { return Mapping[Group]; } }; } // end anonymous namespace. static std::string getCategoryFromDiagGroup(const Record *Group, DiagGroupParentMap &DiagGroupParents) { // If the DiagGroup has a category, return it. std::string CatName = Group->getValueAsString("CategoryName"); if (!CatName.empty()) return CatName; // The diag group may the subgroup of one or more other diagnostic groups, // check these for a category as well. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group); for (unsigned i = 0, e = Parents.size(); i != e; ++i) { CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents); if (!CatName.empty()) return CatName; } return ""; } /// getDiagnosticCategory - Return the category that the specified diagnostic /// lives in. static std::string getDiagnosticCategory(const Record *R, DiagGroupParentMap &DiagGroupParents) { // If the diagnostic is in a group, and that group has a category, use it. if (DefInit *Group = dynamic_cast<DefInit*>(R->getValueInit("Group"))) { // Check the diagnostic's diag group for a category. std::string CatName = getCategoryFromDiagGroup(Group->getDef(), DiagGroupParents); if (!CatName.empty()) return CatName; } // If the diagnostic itself has a category, get it. return R->getValueAsString("CategoryName"); } namespace { class DiagCategoryIDMap { RecordKeeper &Records; StringMap<unsigned> CategoryIDs; std::vector<std::string> CategoryStrings; public: DiagCategoryIDMap(RecordKeeper &records) : Records(records) { DiagGroupParentMap ParentInfo(Records); // The zero'th category is "". CategoryStrings.push_back(""); CategoryIDs[""] = 0; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { std::string Category = getDiagnosticCategory(Diags[i], ParentInfo); if (Category.empty()) continue; // Skip diags with no category. unsigned &ID = CategoryIDs[Category]; if (ID != 0) continue; // Already seen. ID = CategoryStrings.size(); CategoryStrings.push_back(Category); } } unsigned getID(StringRef CategoryString) { return CategoryIDs[CategoryString]; } typedef std::vector<std::string>::iterator iterator; iterator begin() { return CategoryStrings.begin(); } iterator end() { return CategoryStrings.end(); } }; } // end anonymous namespace. //===----------------------------------------------------------------------===// // Warning Tables (.inc file) generation. //===----------------------------------------------------------------------===// void ClangDiagsDefsEmitter::run(raw_ostream &OS) { // Write the #if guard if (!Component.empty()) { std::string ComponentName = UppercaseString(Component); OS << "#ifdef " << ComponentName << "START\n"; OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName << ",\n"; OS << "#undef " << ComponentName << "START\n"; OS << "#endif\n\n"; } const std::vector<Record*> &Diags = Records.getAllDerivedDefinitions("Diagnostic"); DiagCategoryIDMap CategoryIDs(Records); DiagGroupParentMap DGParentMap(Records); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record &R = *Diags[i]; // Filter by component. if (!Component.empty() && Component != R.getValueAsString("Component")) continue; OS << "DIAG(" << R.getName() << ", "; OS << R.getValueAsDef("Class")->getName(); OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName(); // Description string. OS << ", \""; OS.write_escaped(R.getValueAsString("Text")) << '"'; // Warning associated with the diagnostic. if (DefInit *DI = dynamic_cast<DefInit*>(R.getValueInit("Group"))) { OS << ", \""; OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"'; } else { OS << ", 0"; } // SFINAE bit if (R.getValueAsBit("SFINAE")) OS << ", true"; else OS << ", false"; // Access control bit if (R.getValueAsBit("AccessControl")) OS << ", true"; else OS << ", false"; // Category number. OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap)); OS << ")\n"; } } //===----------------------------------------------------------------------===// // Warning Group Tables generation //===----------------------------------------------------------------------===// struct GroupInfo { std::vector<const Record*> DiagsInGroup; std::vector<std::string> SubGroups; unsigned IDNo; }; void ClangDiagGroupsEmitter::run(raw_ostream &OS) { // Compute a mapping from a DiagGroup to all of its parents. DiagGroupParentMap DGParentMap(Records); // Invert the 1-[0/1] mapping of diags to group into a one to many mapping of // groups to diags in the group. std::map<std::string, GroupInfo> DiagsInGroup; std::vector<Record*> Diags = Records.getAllDerivedDefinitions("Diagnostic"); for (unsigned i = 0, e = Diags.size(); i != e; ++i) { const Record *R = Diags[i]; DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group")); if (DI == 0) continue; std::string GroupName = DI->getDef()->getValueAsString("GroupName"); DiagsInGroup[GroupName].DiagsInGroup.push_back(R); } // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty // groups (these are warnings that GCC supports that clang never produces). std::vector<Record*> DiagGroups = Records.getAllDerivedDefinitions("DiagGroup"); for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) { Record *Group = DiagGroups[i]; GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")]; std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups"); for (unsigned j = 0, e = SubGroups.size(); j != e; ++j) GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName")); } // Assign unique ID numbers to the groups. unsigned IDNo = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo) I->second.IDNo = IDNo; // Walk through the groups emitting an array for each diagnostic of the diags // that are mapped to. OS << "\n#ifdef GET_DIAG_ARRAYS\n"; unsigned MaxLen = 0; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { MaxLen = std::max(MaxLen, (unsigned)I->first.size()); std::vector<const Record*> &V = I->second.DiagsInGroup; if (!V.empty()) { OS << "static const short DiagArray" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = V.size(); i != e; ++i) OS << "diag::" << V[i]->getName() << ", "; OS << "-1 };\n"; } const std::vector<std::string> &SubGroups = I->second.SubGroups; if (!SubGroups.empty()) { OS << "static const short DiagSubGroup" << I->second.IDNo << "[] = { "; for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) { std::map<std::string, GroupInfo>::iterator RI = DiagsInGroup.find(SubGroups[i]); assert(RI != DiagsInGroup.end() && "Referenced without existing?"); OS << RI->second.IDNo << ", "; } OS << "-1 };\n"; } } OS << "#endif // GET_DIAG_ARRAYS\n\n"; // Emit the table now. OS << "\n#ifdef GET_DIAG_TABLE\n"; for (std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) { // Group option string. OS << " { \""; OS.write_escaped(I->first) << "\"," << std::string(MaxLen-I->first.size()+1, ' '); // Diagnostics in the group. if (I->second.DiagsInGroup.empty()) OS << "0, "; else OS << "DiagArray" << I->second.IDNo << ", "; // Subgroups. if (I->second.SubGroups.empty()) OS << 0; else OS << "DiagSubGroup" << I->second.IDNo; OS << " },\n"; } OS << "#endif // GET_DIAG_TABLE\n\n"; // Emit the category table next. DiagCategoryIDMap CategoriesByID(Records); OS << "\n#ifdef GET_CATEGORY_TABLE\n"; for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(), E = CategoriesByID.end(); I != E; ++I) OS << "CATEGORY(\"" << *I << "\")\n"; OS << "#endif // GET_CATEGORY_TABLE\n\n"; } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 NVIDIA 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. */ /*! \file scan.inl * \brief Inline file for scan.h. */ #include <thrust/detail/config.h> #include <thrust/detail/device/cuda/dispatch/scan.h> #include <thrust/detail/static_assert.h> namespace thrust { namespace detail { namespace device { namespace cuda { template<typename InputIterator, typename OutputIterator, typename AssociativeOperator> OutputIterator inclusive_scan(InputIterator first, InputIterator last, OutputIterator result, AssociativeOperator binary_op) { // we're attempting to launch a kernel, assert we're compiling with nvcc // ======================================================================== // X Note to the user: If you've found this line due to a compiler error, X // X you need to compile your code using nvcc, rather than g++ or cl.exe X // ======================================================================== THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) ); typedef typename thrust::iterator_value<OutputIterator>::type OutputType; // whether to use fast_scan or safe_scan // TODO profile this threshold //#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010 // // CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory // static const bool use_fast_scan = sizeof(OutputType) <= 16; //#else // // CUDA 3.0 and earlier must use safe_scan for non-pod types static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value; //#endif // XXX WAR nvcc unused variable warning (void) use_fast_scan; return thrust::detail::device::cuda::dispatch::inclusive_scan (first, last, result, binary_op, thrust::detail::integral_constant<bool, use_fast_scan>()); } template<typename InputIterator, typename OutputIterator, typename T, typename AssociativeOperator> OutputIterator exclusive_scan(InputIterator first, InputIterator last, OutputIterator result, T init, AssociativeOperator binary_op) { // we're attempting to launch a kernel, assert we're compiling with nvcc // ======================================================================== // X Note to the user: If you've found this line due to a compiler error, X // X you need to compile your code using nvcc, rather than g++ or cl.exe X // ======================================================================== THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) ); typedef typename thrust::iterator_value<OutputIterator>::type OutputType; // whether to use fast_scan or safe_scan // TODO profile this threshold //#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010 // // CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory // static const bool use_fast_scan = sizeof(OutputType) <= 16; //#else // // CUDA 3.0 and earlier must use safe_scan for non-pod types static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value; //#endif // XXX WAR nvcc 3.0 unused variable warning (void) use_fast_scan; return thrust::detail::device::cuda::dispatch::exclusive_scan (first, last, result, init, binary_op, thrust::detail::integral_constant<bool, use_fast_scan>()); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust <commit_msg>revert scan dispatch to use fast_scan more often<commit_after>/* * Copyright 2008-2010 NVIDIA 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. */ /*! \file scan.inl * \brief Inline file for scan.h. */ #include <thrust/detail/config.h> #include <thrust/detail/device/cuda/dispatch/scan.h> #include <thrust/detail/static_assert.h> namespace thrust { namespace detail { namespace device { namespace cuda { template<typename InputIterator, typename OutputIterator, typename AssociativeOperator> OutputIterator inclusive_scan(InputIterator first, InputIterator last, OutputIterator result, AssociativeOperator binary_op) { // we're attempting to launch a kernel, assert we're compiling with nvcc // ======================================================================== // X Note to the user: If you've found this line due to a compiler error, X // X you need to compile your code using nvcc, rather than g++ or cl.exe X // ======================================================================== THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) ); typedef typename thrust::iterator_value<OutputIterator>::type OutputType; // whether to use fast_scan or safe_scan // TODO profile this threshold #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010 // CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory static const bool use_fast_scan = sizeof(OutputType) <= 16; #else // CUDA 3.0 and earlier must use safe_scan for non-pod types static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value; #endif // XXX WAR nvcc unused variable warning (void) use_fast_scan; return thrust::detail::device::cuda::dispatch::inclusive_scan (first, last, result, binary_op, thrust::detail::integral_constant<bool, use_fast_scan>()); } template<typename InputIterator, typename OutputIterator, typename T, typename AssociativeOperator> OutputIterator exclusive_scan(InputIterator first, InputIterator last, OutputIterator result, T init, AssociativeOperator binary_op) { // we're attempting to launch a kernel, assert we're compiling with nvcc // ======================================================================== // X Note to the user: If you've found this line due to a compiler error, X // X you need to compile your code using nvcc, rather than g++ or cl.exe X // ======================================================================== THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) ); typedef typename thrust::iterator_value<OutputIterator>::type OutputType; // whether to use fast_scan or safe_scan // TODO profile this threshold #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC && CUDA_VERSION >= 3010 // CUDA 3.1 and higher support non-pod types in statically-allocated __shared__ memory static const bool use_fast_scan = sizeof(OutputType) <= 16; #else // CUDA 3.0 and earlier must use safe_scan for non-pod types static const bool use_fast_scan = sizeof(OutputType) <= 16 && thrust::detail::is_pod<OutputType>::value; #endif // XXX WAR nvcc 3.0 unused variable warning (void) use_fast_scan; return thrust::detail::device::cuda::dispatch::exclusive_scan (first, last, result, init, binary_op, thrust::detail::integral_constant<bool, use_fast_scan>()); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust <|endoftext|>
<commit_before>/** * Non-metric Space Library * * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info). * With contributions from Lawrence Cayton (http://lcayton.com/). * * For the complete list of contributors and further details see: * https://github.com/searchivarius/NonMetricSpaceLib * * Copyright (c) 2014 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <cmath> #include <fstream> #include <string> #include <sstream> #include "space_sparse_scalar_fast.h" #include "logging.h" #include "experimentconf.h" namespace similarity { #ifdef __SSE4_2__ #include <immintrin.h> #include <smmintrin.h> #include <tmmintrin.h> const static __m128i shuffle_mask16[16] = { _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,7,6,5,4), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,7,6,5,4,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,11,10,9,8), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,11,10,9,8,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,11,10,9,8,7,6,5,4), _mm_set_epi8(-127,-127,-127,-127,11,10,9,8,7,6,5,4,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12,7,6,5,4), _mm_set_epi8(-127,-127,-127,-127,15,14,13,12,7,6,5,4,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12,11,10,9,8), _mm_set_epi8(-127,-127,-127,-127,15,14,13,12,11,10,9,8,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,15,14,13,12,11,10,9,8,7,6,5,4), _mm_set_epi8(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0), }; #endif /* * The efficient SIMD intersection is based on the code of Daniel Lemire (lemire.me). * * Lemire's code implemented an algorithm similar to one described in: * * Schlegel, Benjamin, Thomas Willhalm, and Wolfgang Lehner. * "Fast sorted-set intersection using simd instructions." ADMS Workshop, Seattle, WA, USA. 2011. * * The code was adapted, simplified, and modified by Leo as follows: * * 1) The original algorithm was used to obtain only IDs. * to extract both IDs and respective floating-point values, * we need to call _mm_cmpistrm twice. * 2) During partitioning we scale ids so that * none of them is a multiple of 65536. * The latter trick allows us to employ a slightly faster * version of the _mm_cmpistrm. * */ float ScalarProjectFast(const char* pData1, size_t len1, const char* pData2, size_t len2) { float norm1 = 0, norm2 = 0; size_t blockQty1 = 0, blockQty2 = 0; const size_t* pBlockQtys1 = NULL; const size_t* pBlockQtys2 = NULL; const size_t* pBlockOffs1 = NULL; const size_t* pBlockOffs2 = NULL; const char* pBlockBeg1 = NULL; const char* pBlockBeg2 = NULL; ParseSparseElementHeader(pData1, blockQty1, norm1, pBlockQtys1, pBlockOffs1, pBlockBeg1); ParseSparseElementHeader(pData2, blockQty2, norm2, pBlockQtys2, pBlockOffs2, pBlockBeg2); float sum = 0; size_t bid1 = 0, bid2 = 0; // block ids size_t elemSize = 2 + sizeof(float); while (bid1 < blockQty1 && bid2 < blockQty2) { if (pBlockOffs1[bid1] == pBlockOffs2[bid2]) { size_t qty1 = pBlockQtys1[bid1]; const uint16_t* pBlockIds1 = reinterpret_cast<const uint16_t*>(pBlockBeg1); const float* pBlockVals1 = reinterpret_cast<const float*>(pBlockIds1 + qty1); size_t qty2 = pBlockQtys2[bid2]; const uint16_t* pBlockIds2 = reinterpret_cast<const uint16_t*>(pBlockBeg2); const float* pBlockVals2 = reinterpret_cast<const float*>(pBlockIds2 + qty2); size_t mx = max(qty1, qty2); float val1[mx]; float val2[mx]; float* pVal1 = val1; float* pVal2 = val2; size_t i1 = 0, i2 = 0; size_t iEnd1 = qty1 / 8 * 8; size_t iEnd2 = qty2 / 8 * 8; if (i1 < iEnd1 && i2 < iEnd2) { while (pBlockIds1[i1 + 7] < pBlockIds2[i2]) { i1 += 8; if (i1 >= iEnd1) goto scalar_inter; } while (pBlockIds2[i2 + 7] < pBlockIds1[i1]) { i2 += 8; if (i2 >= iEnd2) goto scalar_inter; } __m128i id1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds1[i1])); __m128i id2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds2[i2])); while (true) { __m128i cmpRes = _mm_cmpistrm(id2, id1, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); int r = _mm_extract_epi32(cmpRes, 0); if (r) { int r1 = r & 15; __m128i v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals1[i1])); __m128 vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r1]); _mm_storeu_ps(pVal1, vs); pVal1 += _mm_popcnt_u32(r1); int r2 = (r >> 4) & 15; v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals1[i1+4])); vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r2]); _mm_storeu_ps(pVal1, vs); pVal1 += _mm_popcnt_u32(r2); cmpRes = _mm_cmpistrm(id1, id2, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); r = _mm_extract_epi32(cmpRes, 0); r1 = r & 15; v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals2[i2])); vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r1]); _mm_storeu_ps(pVal2, vs); pVal2 += _mm_popcnt_u32(r1); r2 = (r >> 4) & 15; v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals2[i2+4])); vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r2]); _mm_storeu_ps(pVal2, vs); pVal2 += _mm_popcnt_u32(r2); } const uint16_t id1max = pBlockIds1[i1 + 7]; if (id1max <= pBlockIds2[i2 + 7]) { i1 += 8; if (i1 >= iEnd1) goto scalar_inter; id1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds1[i1])); } if (id1max >= pBlockIds2[i2 + 7]) { i2 += 8; if (i2 >= iEnd2) goto scalar_inter; id2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds2[i2])); } } } scalar_inter: while (i1 < qty1 && i2 < qty2) { if (pBlockIds1[i1] == pBlockIds2[i2]) { *pVal1++ = pBlockVals1[i1]; *pVal2++ = pBlockVals2[i2]; ++i1; ++i2; } else if (pBlockIds1[i1] < pBlockIds2[i2]) { ++i1; } else { ++i2; } } pBlockBeg1 += elemSize * pBlockQtys1[bid1++]; pBlockBeg2 += elemSize * pBlockQtys2[bid2++]; ssize_t resQty = pVal1 - val1; CHECK(resQty == pVal2 - val2); ssize_t resQty4 = resQty /4 * 4; if (resQty4) { __m128 sum128 = _mm_set1_ps(0); for (ssize_t k = 0; k < resQty4; k += 4) { sum128 = _mm_add_ps(sum128, _mm_mul_ps(_mm_loadu_ps(val1 + k), _mm_loadu_ps(val2 + k))); } sum += _mm_extract_ps(sum128, 0); sum += _mm_extract_ps(sum128, 1); sum += _mm_extract_ps(sum128, 2); sum += _mm_extract_ps(sum128, 3); } for (ssize_t k = resQty4 ; k < resQty; ++k) sum += val1[k] * val2[k]; } else if (pBlockOffs1[bid1] < pBlockOffs2[bid2]) { pBlockBeg1 += elemSize * pBlockQtys1[bid1++]; } else { pBlockBeg2 += elemSize * pBlockQtys2[bid2++]; } } // These two loops are necessary to carry out size checks below while (bid1 < blockQty1) { pBlockBeg1 += elemSize * pBlockQtys1[bid1++]; } while (bid2 < blockQty2) { pBlockBeg2 += elemSize * pBlockQtys2[bid2++]; } CHECK(pBlockBeg1 - pData1 == (ssize_t)len1); CHECK(pBlockBeg2 - pData2 == (ssize_t)len2); /* * Sometimes due to rounding errors, we get values > 1 or < -1. * This throws off other functions that use scalar product, e.g., acos */ return max(float(-1), min(float(1), sum / sqrt(norm1) / sqrt(norm2))); } float SpaceSparseCosineSimilarityFast::HiddenDistance(const Object* obj1, const Object* obj2) const { CHECK(obj1->datalength() > 0); CHECK(obj2->datalength() > 0); float val = 1 - ScalarProjectFast(obj1->data(), obj1->datalength(), obj2->data(), obj2->datalength()); return max(val, float(0)); } float SpaceSparseAngularDistanceFast::HiddenDistance(const Object* obj1, const Object* obj2) const { CHECK(obj1->datalength() > 0); CHECK(obj2->datalength() > 0); return acos(ScalarProjectFast(obj1->data(), obj1->datalength(), obj2->data(), obj2->datalength())); } } // namespace similarity <commit_msg>Spelling out the changes that Daniel and Leo made<commit_after>/** * Non-metric Space Library * * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info). * With contributions from Lawrence Cayton (http://lcayton.com/). * * For the complete list of contributors and further details see: * https://github.com/searchivarius/NonMetricSpaceLib * * Copyright (c) 2014 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <cmath> #include <fstream> #include <string> #include <sstream> #include "space_sparse_scalar_fast.h" #include "logging.h" #include "experimentconf.h" namespace similarity { #ifdef __SSE4_2__ #include <immintrin.h> #include <smmintrin.h> #include <tmmintrin.h> const static __m128i shuffle_mask16[16] = { _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,7,6,5,4), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,7,6,5,4,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,11,10,9,8), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,11,10,9,8,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,11,10,9,8,7,6,5,4), _mm_set_epi8(-127,-127,-127,-127,11,10,9,8,7,6,5,4,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12,7,6,5,4), _mm_set_epi8(-127,-127,-127,-127,15,14,13,12,7,6,5,4,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,-127,-127,-127,-127,15,14,13,12,11,10,9,8), _mm_set_epi8(-127,-127,-127,-127,15,14,13,12,11,10,9,8,3,2,1,0), _mm_set_epi8(-127,-127,-127,-127,15,14,13,12,11,10,9,8,7,6,5,4), _mm_set_epi8(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0), }; #endif /* * The efficient SIMD intersection is based on the code of Daniel Lemire (lemire.me). * * Lemire's code implemented an algorithm similar to one described in: * * Schlegel, Benjamin, Thomas Willhalm, and Wolfgang Lehner. * "Fast sorted-set intersection using simd instructions." ADMS Workshop, Seattle, WA, USA. 2011. * * Daniel improved the code of Schlegel et al by replacing a slow function * _mm_cmpistri with a faster analog _mm_cmpistrm. The _mm_cmpistrm is * fast, but it cannot deal with IDs that are multiples of 65536. * Thus, some extra checking is need to handle the case of such IDs. * In this version, however, Leo works around this problem by * transforming IDs in advance. * * More details about Leo's changes: * * 1) The original algorithm was used to obtain only IDs. * to extract both IDs and respective floating-point values, * we need to call _mm_cmpistrm twice. * 2) During partitioning we scale ids so that * none of them is a multiple of 65536. * The latter trick allows us to employ a slightly faster * version of the _mm_cmpistrm. * */ float ScalarProjectFast(const char* pData1, size_t len1, const char* pData2, size_t len2) { float norm1 = 0, norm2 = 0; size_t blockQty1 = 0, blockQty2 = 0; const size_t* pBlockQtys1 = NULL; const size_t* pBlockQtys2 = NULL; const size_t* pBlockOffs1 = NULL; const size_t* pBlockOffs2 = NULL; const char* pBlockBeg1 = NULL; const char* pBlockBeg2 = NULL; ParseSparseElementHeader(pData1, blockQty1, norm1, pBlockQtys1, pBlockOffs1, pBlockBeg1); ParseSparseElementHeader(pData2, blockQty2, norm2, pBlockQtys2, pBlockOffs2, pBlockBeg2); float sum = 0; size_t bid1 = 0, bid2 = 0; // block ids size_t elemSize = 2 + sizeof(float); while (bid1 < blockQty1 && bid2 < blockQty2) { if (pBlockOffs1[bid1] == pBlockOffs2[bid2]) { size_t qty1 = pBlockQtys1[bid1]; const uint16_t* pBlockIds1 = reinterpret_cast<const uint16_t*>(pBlockBeg1); const float* pBlockVals1 = reinterpret_cast<const float*>(pBlockIds1 + qty1); size_t qty2 = pBlockQtys2[bid2]; const uint16_t* pBlockIds2 = reinterpret_cast<const uint16_t*>(pBlockBeg2); const float* pBlockVals2 = reinterpret_cast<const float*>(pBlockIds2 + qty2); size_t mx = max(qty1, qty2); float val1[mx]; float val2[mx]; float* pVal1 = val1; float* pVal2 = val2; size_t i1 = 0, i2 = 0; size_t iEnd1 = qty1 / 8 * 8; size_t iEnd2 = qty2 / 8 * 8; if (i1 < iEnd1 && i2 < iEnd2) { while (pBlockIds1[i1 + 7] < pBlockIds2[i2]) { i1 += 8; if (i1 >= iEnd1) goto scalar_inter; } while (pBlockIds2[i2 + 7] < pBlockIds1[i1]) { i2 += 8; if (i2 >= iEnd2) goto scalar_inter; } __m128i id1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds1[i1])); __m128i id2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds2[i2])); while (true) { __m128i cmpRes = _mm_cmpistrm(id2, id1, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); int r = _mm_extract_epi32(cmpRes, 0); if (r) { int r1 = r & 15; __m128i v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals1[i1])); __m128 vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r1]); _mm_storeu_ps(pVal1, vs); pVal1 += _mm_popcnt_u32(r1); int r2 = (r >> 4) & 15; v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals1[i1+4])); vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r2]); _mm_storeu_ps(pVal1, vs); pVal1 += _mm_popcnt_u32(r2); cmpRes = _mm_cmpistrm(id1, id2, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); r = _mm_extract_epi32(cmpRes, 0); r1 = r & 15; v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals2[i2])); vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r1]); _mm_storeu_ps(pVal2, vs); pVal2 += _mm_popcnt_u32(r1); r2 = (r >> 4) & 15; v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockVals2[i2+4])); vs = (__m128)_mm_shuffle_epi8(v, shuffle_mask16[r2]); _mm_storeu_ps(pVal2, vs); pVal2 += _mm_popcnt_u32(r2); } const uint16_t id1max = pBlockIds1[i1 + 7]; if (id1max <= pBlockIds2[i2 + 7]) { i1 += 8; if (i1 >= iEnd1) goto scalar_inter; id1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds1[i1])); } if (id1max >= pBlockIds2[i2 + 7]) { i2 += 8; if (i2 >= iEnd2) goto scalar_inter; id2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&pBlockIds2[i2])); } } } scalar_inter: while (i1 < qty1 && i2 < qty2) { if (pBlockIds1[i1] == pBlockIds2[i2]) { *pVal1++ = pBlockVals1[i1]; *pVal2++ = pBlockVals2[i2]; ++i1; ++i2; } else if (pBlockIds1[i1] < pBlockIds2[i2]) { ++i1; } else { ++i2; } } pBlockBeg1 += elemSize * pBlockQtys1[bid1++]; pBlockBeg2 += elemSize * pBlockQtys2[bid2++]; ssize_t resQty = pVal1 - val1; CHECK(resQty == pVal2 - val2); ssize_t resQty4 = resQty /4 * 4; if (resQty4) { __m128 sum128 = _mm_set1_ps(0); for (ssize_t k = 0; k < resQty4; k += 4) { sum128 = _mm_add_ps(sum128, _mm_mul_ps(_mm_loadu_ps(val1 + k), _mm_loadu_ps(val2 + k))); } sum += _mm_extract_ps(sum128, 0); sum += _mm_extract_ps(sum128, 1); sum += _mm_extract_ps(sum128, 2); sum += _mm_extract_ps(sum128, 3); } for (ssize_t k = resQty4 ; k < resQty; ++k) sum += val1[k] * val2[k]; } else if (pBlockOffs1[bid1] < pBlockOffs2[bid2]) { pBlockBeg1 += elemSize * pBlockQtys1[bid1++]; } else { pBlockBeg2 += elemSize * pBlockQtys2[bid2++]; } } // These two loops are necessary to carry out size checks below while (bid1 < blockQty1) { pBlockBeg1 += elemSize * pBlockQtys1[bid1++]; } while (bid2 < blockQty2) { pBlockBeg2 += elemSize * pBlockQtys2[bid2++]; } CHECK(pBlockBeg1 - pData1 == (ssize_t)len1); CHECK(pBlockBeg2 - pData2 == (ssize_t)len2); /* * Sometimes due to rounding errors, we get values > 1 or < -1. * This throws off other functions that use scalar product, e.g., acos */ return max(float(-1), min(float(1), sum / sqrt(norm1) / sqrt(norm2))); } float SpaceSparseCosineSimilarityFast::HiddenDistance(const Object* obj1, const Object* obj2) const { CHECK(obj1->datalength() > 0); CHECK(obj2->datalength() > 0); float val = 1 - ScalarProjectFast(obj1->data(), obj1->datalength(), obj2->data(), obj2->datalength()); return max(val, float(0)); } float SpaceSparseAngularDistanceFast::HiddenDistance(const Object* obj1, const Object* obj2) const { CHECK(obj1->datalength() > 0); CHECK(obj2->datalength() > 0); return acos(ScalarProjectFast(obj1->data(), obj1->datalength(), obj2->data(), obj2->datalength())); } } // namespace similarity <|endoftext|>
<commit_before>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> // SYSTEM INCLUDES #include <assert.h> #include <math.h> // APPLICATION INCLUDES #include <mp/MpInputDeviceManager.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsServerTask.h> #include <os/OsTimer.h> #ifdef RTL_ENABLED # include <rtl_macro.h> #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #ifndef M_PI # define M_PI 3.14159265358979323846 #endif // 0 is the Highest priority #define SINE_WAVE_DEVICE_PRIORITY 0 // STATIC VARIABLE INITIALIZATIONS // PRIVATE CLASSES class MpSineWaveGeneratorServer : public OsServerTask { public: MpSineWaveGeneratorServer(unsigned int startFrameTime, unsigned int samplesPerFrame, unsigned int samplesPerSecond, unsigned int magnitude, unsigned int periodMicroseconds, int underOverRunTime, MpInputDeviceHandle deviceId, MpInputDeviceManager& inputDeviceManager) : OsServerTask("MpSineWaveGeneratorServer-%d", NULL, DEF_MAX_MSGS, SINE_WAVE_DEVICE_PRIORITY), mNextFrameTime(startFrameTime), mSamplesPerFrame(samplesPerFrame), mSamplesPerSecond(samplesPerSecond), mMagnatude(magnitude), mSinePeriodMicroseconds(periodMicroseconds), mUnderOverRunTime(underOverRunTime), mDeviceId(deviceId), mpInputDeviceManager(&inputDeviceManager), mpFrameData(NULL), mTimer(getMessageQueue(), 0) { mpFrameData = new MpAudioSample[samplesPerFrame]; }; virtual ~MpSineWaveGeneratorServer() { OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer start\n"); // Do not continue until the task is safely shutdown waitUntilShutDown(); assert(isShutDown()); if(mpFrameData) { delete mpFrameData; mpFrameData = NULL; } OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer end\n"); }; virtual UtlBoolean start(void) { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start start\n"); // start the task UtlBoolean result = OsServerTask::start(); OsTime noDelay(0, 0); int microSecondsPerFrame = (mSamplesPerFrame * 1000000 / mSamplesPerSecond) - mUnderOverRunTime; assert(microSecondsPerFrame > 0); OsTime framePeriod(0, microSecondsPerFrame); // Start re-occurring timer which causes handleMessage to be called // periodically mTimer.periodicEvery(noDelay, framePeriod); OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start end\n"); return(result); }; virtual void requestShutdown(void) { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown start\n"); // Stop the timer first so it stops queuing messages mTimer.stop(); // Then stop the server task OsServerTask::requestShutdown(); OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown end\n"); }; UtlBoolean handleMessage(OsMsg& rMsg) { #ifdef RTL_ENABLED RTL_BLOCK("MpSineWaveGeneratorServer.handleMessage"); #endif // Build a frame of signal and push it to the device manager assert(mpFrameData); for(unsigned int frameIndex = 0; frameIndex < mSamplesPerFrame; frameIndex++) { mpFrameData[frameIndex] = MpSineWaveGeneratorDeviceDriver::calculateSample(mNextFrameTime, mMagnatude, mSinePeriodMicroseconds, frameIndex, mSamplesPerFrame, mSamplesPerSecond); } mpInputDeviceManager->pushFrame(mDeviceId, mSamplesPerFrame, mpFrameData, mNextFrameTime); mNextFrameTime += mSamplesPerFrame * 1000 / mSamplesPerSecond; return(TRUE); } private: MpFrameTime mNextFrameTime; unsigned int mSamplesPerFrame; unsigned int mSamplesPerSecond; unsigned int mMagnatude; unsigned int mSinePeriodMicroseconds; int mUnderOverRunTime; MpInputDeviceHandle mDeviceId; MpInputDeviceManager* mpInputDeviceManager; MpAudioSample* mpFrameData; OsTimer mTimer; }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MpSineWaveGeneratorDeviceDriver::MpSineWaveGeneratorDeviceDriver(const UtlString& name, MpInputDeviceManager& deviceManager, unsigned int magnitude, unsigned int periodInMicroseconds, int underOverRunTime) : MpInputDeviceDriver(name, deviceManager), mMagnitude(magnitude), mPeriodInMicroseconds(periodInMicroseconds), mUnderOverRunTime(underOverRunTime), mpReaderTask(NULL) { } // Destructor MpSineWaveGeneratorDeviceDriver::~MpSineWaveGeneratorDeviceDriver() { OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver start\n"); if(mpReaderTask) { OsStatus stat = disableDevice(); assert(stat == OS_SUCCESS); } OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver end\n"); } /* ============================ MANIPULATORS ============================== */ OsStatus MpSineWaveGeneratorDeviceDriver::enableDevice(unsigned samplesPerFrame, unsigned samplesPerSec, MpFrameTime currentFrameTime) { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice start\n"); OsStatus result = OS_INVALID; assert(mpReaderTask == NULL); if(mpReaderTask == NULL) { mpReaderTask = new MpSineWaveGeneratorServer(currentFrameTime, samplesPerFrame, samplesPerSec, mMagnitude, mPeriodInMicroseconds, mUnderOverRunTime, getDeviceId(), *mpInputDeviceManager); if(mpReaderTask->start()) { result = OS_SUCCESS; mIsEnabled = TRUE; } } OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice end\n"); return(result); } OsStatus MpSineWaveGeneratorDeviceDriver::disableDevice() { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice start\n"); OsStatus result = OS_TASK_NOT_STARTED; //assert(mpReaderTask); if(mpReaderTask) { mpReaderTask->requestShutdown(); delete mpReaderTask; mpReaderTask = NULL; result = OS_SUCCESS; mIsEnabled = FALSE; } OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice end\n"); return(result); } /* ============================ ACCESSORS ================================= */ MpAudioSample MpSineWaveGeneratorDeviceDriver::calculateSample(MpFrameTime frameStartTime, unsigned int magnitude, unsigned int periodInMicroseconds, unsigned int frameSampleIndex, unsigned int samplesPerFrame, unsigned int samplesPerSecond) { double time = ((frameStartTime + frameSampleIndex * 1000.0 / samplesPerSecond) / ((double) periodInMicroseconds) * 1000.0 ) * 2.0 * M_PI; MpAudioSample sample = (MpAudioSample)(sin(time) * (double)magnitude); return(sample); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>MpSineWaveGeneratorDeviceDriver: New line char is not needed when adding log message.<commit_after>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> // SYSTEM INCLUDES #include <assert.h> #include <math.h> // APPLICATION INCLUDES #include <mp/MpInputDeviceManager.h> #include <mp/MpSineWaveGeneratorDeviceDriver.h> #include <os/OsServerTask.h> #include <os/OsTimer.h> #ifdef RTL_ENABLED # include <rtl_macro.h> #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #ifndef M_PI # define M_PI 3.14159265358979323846 #endif // 0 is the Highest priority #define SINE_WAVE_DEVICE_PRIORITY 0 // STATIC VARIABLE INITIALIZATIONS // PRIVATE CLASSES class MpSineWaveGeneratorServer : public OsServerTask { public: MpSineWaveGeneratorServer(unsigned int startFrameTime, unsigned int samplesPerFrame, unsigned int samplesPerSecond, unsigned int magnitude, unsigned int periodMicroseconds, int underOverRunTime, MpInputDeviceHandle deviceId, MpInputDeviceManager& inputDeviceManager) : OsServerTask("MpSineWaveGeneratorServer-%d", NULL, DEF_MAX_MSGS, SINE_WAVE_DEVICE_PRIORITY), mNextFrameTime(startFrameTime), mSamplesPerFrame(samplesPerFrame), mSamplesPerSecond(samplesPerSecond), mMagnatude(magnitude), mSinePeriodMicroseconds(periodMicroseconds), mUnderOverRunTime(underOverRunTime), mDeviceId(deviceId), mpInputDeviceManager(&inputDeviceManager), mpFrameData(NULL), mTimer(getMessageQueue(), 0) { mpFrameData = new MpAudioSample[samplesPerFrame]; }; virtual ~MpSineWaveGeneratorServer() { OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer start"); // Do not continue until the task is safely shutdown waitUntilShutDown(); assert(isShutDown()); if(mpFrameData) { delete mpFrameData; mpFrameData = NULL; } OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer end"); }; virtual UtlBoolean start(void) { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start start"); // start the task UtlBoolean result = OsServerTask::start(); OsTime noDelay(0, 0); int microSecondsPerFrame = (mSamplesPerFrame * 1000000 / mSamplesPerSecond) - mUnderOverRunTime; assert(microSecondsPerFrame > 0); OsTime framePeriod(0, microSecondsPerFrame); // Start re-occurring timer which causes handleMessage to be called // periodically mTimer.periodicEvery(noDelay, framePeriod); OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start end"); return(result); }; virtual void requestShutdown(void) { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown start"); // Stop the timer first so it stops queuing messages mTimer.stop(); // Then stop the server task OsServerTask::requestShutdown(); OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown end"); }; UtlBoolean handleMessage(OsMsg& rMsg) { #ifdef RTL_ENABLED RTL_BLOCK("MpSineWaveGeneratorServer.handleMessage"); #endif // Build a frame of signal and push it to the device manager assert(mpFrameData); for(unsigned int frameIndex = 0; frameIndex < mSamplesPerFrame; frameIndex++) { mpFrameData[frameIndex] = MpSineWaveGeneratorDeviceDriver::calculateSample(mNextFrameTime, mMagnatude, mSinePeriodMicroseconds, frameIndex, mSamplesPerFrame, mSamplesPerSecond); } mpInputDeviceManager->pushFrame(mDeviceId, mSamplesPerFrame, mpFrameData, mNextFrameTime); mNextFrameTime += mSamplesPerFrame * 1000 / mSamplesPerSecond; return(TRUE); } private: MpFrameTime mNextFrameTime; unsigned int mSamplesPerFrame; unsigned int mSamplesPerSecond; unsigned int mMagnatude; unsigned int mSinePeriodMicroseconds; int mUnderOverRunTime; MpInputDeviceHandle mDeviceId; MpInputDeviceManager* mpInputDeviceManager; MpAudioSample* mpFrameData; OsTimer mTimer; }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MpSineWaveGeneratorDeviceDriver::MpSineWaveGeneratorDeviceDriver(const UtlString& name, MpInputDeviceManager& deviceManager, unsigned int magnitude, unsigned int periodInMicroseconds, int underOverRunTime) : MpInputDeviceDriver(name, deviceManager), mMagnitude(magnitude), mPeriodInMicroseconds(periodInMicroseconds), mUnderOverRunTime(underOverRunTime), mpReaderTask(NULL) { } // Destructor MpSineWaveGeneratorDeviceDriver::~MpSineWaveGeneratorDeviceDriver() { OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver start"); if(mpReaderTask) { OsStatus stat = disableDevice(); assert(stat == OS_SUCCESS); } OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver end"); } /* ============================ MANIPULATORS ============================== */ OsStatus MpSineWaveGeneratorDeviceDriver::enableDevice(unsigned samplesPerFrame, unsigned samplesPerSec, MpFrameTime currentFrameTime) { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice start"); OsStatus result = OS_INVALID; assert(mpReaderTask == NULL); if(mpReaderTask == NULL) { mpReaderTask = new MpSineWaveGeneratorServer(currentFrameTime, samplesPerFrame, samplesPerSec, mMagnitude, mPeriodInMicroseconds, mUnderOverRunTime, getDeviceId(), *mpInputDeviceManager); if(mpReaderTask->start()) { result = OS_SUCCESS; mIsEnabled = TRUE; } } OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice end"); return(result); } OsStatus MpSineWaveGeneratorDeviceDriver::disableDevice() { OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice start"); OsStatus result = OS_TASK_NOT_STARTED; //assert(mpReaderTask); if(mpReaderTask) { mpReaderTask->requestShutdown(); delete mpReaderTask; mpReaderTask = NULL; result = OS_SUCCESS; mIsEnabled = FALSE; } OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice end"); return(result); } /* ============================ ACCESSORS ================================= */ MpAudioSample MpSineWaveGeneratorDeviceDriver::calculateSample(MpFrameTime frameStartTime, unsigned int magnitude, unsigned int periodInMicroseconds, unsigned int frameSampleIndex, unsigned int samplesPerFrame, unsigned int samplesPerSecond) { double time = ((frameStartTime + frameSampleIndex * 1000.0 / samplesPerSecond) / ((double) periodInMicroseconds) * 1000.0 ) * 2.0 * M_PI; MpAudioSample sample = (MpAudioSample)(sin(time) * (double)magnitude); return(sample); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include "mp/MpInputDeviceManager.h" #include "mp/MprFromInputDevice.h" #include "mp/MpOutputDeviceManager.h" #include "mp/MprToOutputDevice.h" #include "mp/MpFlowGraphBase.h" #include "mp/MpMisc.h" #include "mp/MpMediaTask.h" #include "os/OsTask.h" #ifdef RTL_ENABLED # include <rtl_macro.h> #else # define RTL_BLOCK(x) # define RTL_EVENT(x,y) #endif #include <os/OsFS.h> #define TEST_TIME_MS 10000 ///< Time to runs test (in milliseconds) #define AUDIO_BUFS_NUM 500 ///< Number of buffers in buffer pool we'll use. #define BUFFERS_TO_BUFFER_ON_INPUT 3 ///< Number of buffers to buffer in input manager. #define BUFFERS_TO_BUFFER_ON_OUTPUT 0 ///< Number of buffers to buffer in output manager. #define TEST_SAMPLES_PER_FRAME 80 ///< in samples #define TEST_SAMPLES_PER_SECOND 8000 ///< in samples/sec (Hz) #define BUFFER_ON_OUTPUT_MS (BUFFERS_TO_BUFFER_ON_OUTPUT*TEST_SAMPLES_PER_FRAME*1000/TEST_SAMPLES_PER_SECOND) ///< Buffer size in output manager in milliseconds. #define USE_TEST_INPUT_DRIVER #define USE_TEST_OUTPUT_DRIVER // OS-specific device drivers #ifdef __pingtel_on_posix__ // [ # define USE_OSS_INPUT_DRIVER # define USE_OSS_OUTPUT_DRIVER #endif // __pingtel_on_posix__ ] #ifdef WIN32 // [ # define USE_WNT_INPUT_DRIVER #endif // WIN32 ] #ifdef USE_TEST_INPUT_DRIVER // [ # include <mp/MpSineWaveGeneratorDeviceDriver.h> #endif // USE_TEST_INPUT_DRIVER ] #ifdef USE_WNT_INPUT_DRIVER // [ # include <mp/MpInputDeviceDriverWnt.h> #endif // USE_WNT_INPUT_DRIVER ] #ifdef __pingtel_on_posix__ // [ # include <mp/MpidOSS.h> #endif // __pingtel_on_posix__ ] #ifdef USE_TEST_OUTPUT_DRIVER // [ # include <mp/MpodBufferRecorder.h> #endif // USE_TEST_OUTPUT_DRIVER ] #ifdef __pingtel_on_posix__ // [ # include <mp/MpodOSS.h> #endif // __pingtel_on_posix__ ] /// Unit test for MprSplitter class MpInputOutputFrameworkTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpInputOutputFrameworkTest); CPPUNIT_TEST(testShortCircuit); CPPUNIT_TEST_SUITE_END(); public: // This function will be called before every test to setup framework. void setUp() { // Setup media task CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpStartUp(TEST_SAMPLES_PER_SECOND, TEST_SAMPLES_PER_FRAME, 6*10, 0)); // Create flowgraph mpFlowGraph = new MpFlowGraphBase(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT(mpFlowGraph != NULL); // Call getMediaTask() which causes the task to get instantiated mpMediaTask = MpMediaTask::getMediaTask(10); CPPUNIT_ASSERT(mpMediaTask != NULL); // Create input and output device managers mpInputDeviceManager = new MpInputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFERS_TO_BUFFER_ON_INPUT, *MpMisc.RawAudioPool); CPPUNIT_ASSERT(mpInputDeviceManager != NULL); mpOutputDeviceManager = new MpOutputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFER_ON_OUTPUT_MS); CPPUNIT_ASSERT(mpOutputDeviceManager != NULL); // No drivers in managers mInputDeviceNumber = 0; mOutputDeviceNumber = 0; // NOTE: Next functions would add devices only if they are available in // current environment. createTestInputDriver(); createWntInputDrivers(); createOSSInputDrivers(); createTestOutputDriver(); createOSSOutputDrivers(); } // This function will be called after every test to clean up framework. void tearDown() { // This should normally be done by haltFramework, but if we aborted due // to an assertion the flowgraph will need to be shutdown here if (mpFlowGraph && mpFlowGraph->isStarted()) { osPrintf("WARNING: flowgraph found still running, shutting down\n"); // ignore the result and keep going mpFlowGraph->stop(); // Request processing of another frame so that the STOP_FLOWGRAPH // message gets handled mpFlowGraph->processNextFrame(); } #ifdef xUSE_TEST_OUTPUT_DRIVER // [ OsFile::openAndWrite("capture.raw", (const char*)sinkDevice.getBufferData(), sinkDevice.getBufferLength()*sizeof(MpAudioSample)); #endif // USE_TEST_OUTPUT_DRIVER ] // Free all input device drivers for (; mInputDeviceNumber>0; mInputDeviceNumber--) { MpInputDeviceDriver *pDriver = mpInputDeviceManager->removeDevice(mInputDeviceNumber); CPPUNIT_ASSERT(pDriver != NULL); CPPUNIT_ASSERT(!pDriver->isEnabled()); delete pDriver; } // Free all output device drivers for (; mOutputDeviceNumber>0; mOutputDeviceNumber--) { MpOutputDeviceDriver *pDriver = mpOutputDeviceManager->removeDevice(mOutputDeviceNumber); CPPUNIT_ASSERT(pDriver != NULL); CPPUNIT_ASSERT(!pDriver->isEnabled()); delete pDriver; } // Free device managers delete mpOutputDeviceManager; mpOutputDeviceManager = NULL; delete mpInputDeviceManager; mpInputDeviceManager = NULL; // Free flowgraph delete mpFlowGraph; mpFlowGraph = NULL; // Free media task delete mpMediaTask; mpMediaTask = NULL; // Clear all Media Tasks data CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpShutdown()); } void testShortCircuit() { enableConsoleOutput(1); #ifdef RTL_ENABLED RTL_START(10000000); #endif MpInputDeviceHandle sourceDeviceId = 0; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpInputDeviceManager->getDeviceId("SineGenerator", sourceDeviceId)); MpOutputDeviceHandle sinkDeviceId = 0; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->getDeviceId("BufferRecorder", sinkDeviceId)); // Create source (input) and sink (output) resources. MprFromInputDevice sourceResource("MprFromInputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, mpInputDeviceManager, sourceDeviceId); MprToOutputDevice sinkResource("MprToOutputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, mpOutputDeviceManager, sinkDeviceId); try { // Add source and sink resources to flowgraph and link them together. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(sourceResource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(sinkResource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addLink(sourceResource, 0, sinkResource, 0)); // Enable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpInputDeviceManager->enableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->enableDevice(sinkDeviceId)); // Set flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->setFlowgraphTickerSource(sinkDeviceId)); // Enable resources CPPUNIT_ASSERT(sourceResource.enable()); CPPUNIT_ASSERT(sinkResource.enable()); // Manage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpMediaTask->manageFlowGraph(*mpFlowGraph)); // Start flowgraph CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpMediaTask->startFlowGraph(*mpFlowGraph)); // Run test! OsTask::delay(TEST_TIME_MS); // Clear flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->setFlowgraphTickerSource(MP_INVALID_OUTPUT_DEVICE_HANDLE)); // OsTask::delay(50); // Disable resources CPPUNIT_ASSERT(sourceResource.disable()); CPPUNIT_ASSERT(sinkResource.disable()); MpMediaTask::signalFrameStart(); // Unmanage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpMediaTask->unmanageFlowGraph(*mpFlowGraph)); MpMediaTask::signalFrameStart(); // Disable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpInputDeviceManager->disableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->disableDevice(sinkDeviceId)); // Remove resources from flowgraph. We should remove them explicitly // here, because they are stored on the stack and will be destroyed. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sinkResource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sourceResource)); mpFlowGraph->processNextFrame(); } catch (CppUnit::Exception& e) { // Remove resources from flowgraph. We should remove them explicitly // here, because they are stored on the stack and will be destroyed. // If we will not catch this assert we'll have this resources destroyed // while still referenced in flowgraph, causing crash. if (sinkResource.getFlowGraph() != NULL) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sinkResource)); } if (sourceResource.getFlowGraph() != NULL) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sourceResource)); } mpFlowGraph->processNextFrame(); // Rethrow exception. throw(e); } #ifdef RTL_ENABLED RTL_WRITE("testShortCircuit.rtl"); #endif } protected: MpFlowGraphBase *mpFlowGraph; ///< Flowgraph for our fromInputDevice and ///< toOutputDevice resources. MpMediaTask *mpMediaTask; ///< Pointer to media task instance. MpInputDeviceManager *mpInputDeviceManager; ///< Manager for input devices. MpOutputDeviceManager *mpOutputDeviceManager; ///< Manager for output devices. unsigned mInputDeviceNumber; unsigned mOutputDeviceNumber; /// Add passed device to input device manager. void manageInputDevice(MpInputDeviceDriver *pDriver) { // Add driver to manager MpInputDeviceHandle deviceId = mpInputDeviceManager->addDevice(*pDriver); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(!mpInputDeviceManager->isDeviceEnabled(deviceId)); // Driver is successfully added mInputDeviceNumber++; } /// Add passed device to output device manager. void manageOutputDevice(MpOutputDeviceDriver *pDriver) { // Add driver to manager MpOutputDeviceHandle deviceId = mpOutputDeviceManager->addDevice(pDriver); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(!mpOutputDeviceManager->isDeviceEnabled(deviceId)); // Driver is successfully added mOutputDeviceNumber++; } void createTestInputDriver() { #ifdef USE_TEST_INPUT_DRIVER // [ // Create driver MpSineWaveGeneratorDeviceDriver *pDriver = new MpSineWaveGeneratorDeviceDriver("SineGenerator", *mpInputDeviceManager, 32000, 3000, 0); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageInputDevice(pDriver); #endif // USE_TEST_INPUT_DRIVER ] } void createWntInputDrivers() { #ifdef USE_WNT_INPUT_DRIVER // [ // Create driver MpInputDeviceDriverWnt *pDriver = new MpInputDeviceDriverWnt("SoundMAX HD Audio", *mpInputDeviceManager); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageInputDevice(pDriver); #endif // USE_WNT_INPUT_DRIVER ] } void createOSSInputDrivers() { #ifdef USE_OSS_INPUT_DRIVER // [ // Create driver MpidOSS *pDriver = new MpidOSS("/dev/dsp", *mpInputDeviceManager); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageInputDevice(pDriver); #endif // USE_OSS_INPUT_DRIVER ] } void createTestOutputDriver() { #ifdef USE_TEST_OUTPUT_DRIVER // [ // Create driver MpodBufferRecorder *pDriver = new MpodBufferRecorder("BufferRecorder", TEST_TIME_MS); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageOutputDevice(pDriver); #endif // USE_TEST_OUTPUT_DRIVER ] } void createOSSOutputDrivers() { #ifdef USE_OSS_OUTPUT_DRIVER // [ // Create driver MpodOSS *pDriver = new MpodOSS("/dev/dsp"); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageOutputDevice(pDriver); #endif // USE_OSS_OUTPUT_DRIVER ] } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpInputOutputFrameworkTest); <commit_msg>MpInputOutputFrameworkTest: Make short-circuit test even more resistant to failed CPPUnit assertions.<commit_after>// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <sipxunit/TestUtilities.h> #include "mp/MpInputDeviceManager.h" #include "mp/MprFromInputDevice.h" #include "mp/MpOutputDeviceManager.h" #include "mp/MprToOutputDevice.h" #include "mp/MpFlowGraphBase.h" #include "mp/MpMisc.h" #include "mp/MpMediaTask.h" #include "os/OsTask.h" #ifdef RTL_ENABLED # include <rtl_macro.h> #else # define RTL_BLOCK(x) # define RTL_EVENT(x,y) #endif #include <os/OsFS.h> #define TEST_TIME_MS 10000 ///< Time to runs test (in milliseconds) #define AUDIO_BUFS_NUM 500 ///< Number of buffers in buffer pool we'll use. #define BUFFERS_TO_BUFFER_ON_INPUT 3 ///< Number of buffers to buffer in input manager. #define BUFFERS_TO_BUFFER_ON_OUTPUT 0 ///< Number of buffers to buffer in output manager. #define TEST_SAMPLES_PER_FRAME 80 ///< in samples #define TEST_SAMPLES_PER_SECOND 8000 ///< in samples/sec (Hz) #define BUFFER_ON_OUTPUT_MS (BUFFERS_TO_BUFFER_ON_OUTPUT*TEST_SAMPLES_PER_FRAME*1000/TEST_SAMPLES_PER_SECOND) ///< Buffer size in output manager in milliseconds. #define USE_TEST_INPUT_DRIVER #define USE_TEST_OUTPUT_DRIVER // OS-specific device drivers #ifdef __pingtel_on_posix__ // [ # define USE_OSS_INPUT_DRIVER # define USE_OSS_OUTPUT_DRIVER #endif // __pingtel_on_posix__ ] #ifdef WIN32 // [ # define USE_WNT_INPUT_DRIVER #endif // WIN32 ] #ifdef USE_TEST_INPUT_DRIVER // [ # include <mp/MpSineWaveGeneratorDeviceDriver.h> #endif // USE_TEST_INPUT_DRIVER ] #ifdef USE_WNT_INPUT_DRIVER // [ # include <mp/MpInputDeviceDriverWnt.h> #endif // USE_WNT_INPUT_DRIVER ] #ifdef __pingtel_on_posix__ // [ # include <mp/MpidOSS.h> #endif // __pingtel_on_posix__ ] #ifdef USE_TEST_OUTPUT_DRIVER // [ # include <mp/MpodBufferRecorder.h> #endif // USE_TEST_OUTPUT_DRIVER ] #ifdef __pingtel_on_posix__ // [ # include <mp/MpodOSS.h> #endif // __pingtel_on_posix__ ] /// Unit test for MprSplitter class MpInputOutputFrameworkTest : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(MpInputOutputFrameworkTest); CPPUNIT_TEST(testShortCircuit); CPPUNIT_TEST_SUITE_END(); public: // This function will be called before every test to setup framework. void setUp() { // Setup media task CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpStartUp(TEST_SAMPLES_PER_SECOND, TEST_SAMPLES_PER_FRAME, 6*10, 0)); // Create flowgraph mpFlowGraph = new MpFlowGraphBase(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND); CPPUNIT_ASSERT(mpFlowGraph != NULL); // Call getMediaTask() which causes the task to get instantiated mpMediaTask = MpMediaTask::getMediaTask(10); CPPUNIT_ASSERT(mpMediaTask != NULL); // Create input and output device managers mpInputDeviceManager = new MpInputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFERS_TO_BUFFER_ON_INPUT, *MpMisc.RawAudioPool); CPPUNIT_ASSERT(mpInputDeviceManager != NULL); mpOutputDeviceManager = new MpOutputDeviceManager(TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, BUFFER_ON_OUTPUT_MS); CPPUNIT_ASSERT(mpOutputDeviceManager != NULL); // No drivers in managers mInputDeviceNumber = 0; mOutputDeviceNumber = 0; // NOTE: Next functions would add devices only if they are available in // current environment. createTestInputDriver(); createWntInputDrivers(); createOSSInputDrivers(); createTestOutputDriver(); createOSSOutputDrivers(); } // This function will be called after every test to clean up framework. void tearDown() { // This should normally be done by haltFramework, but if we aborted due // to an assertion the flowgraph will need to be shutdown here if (mpFlowGraph && mpFlowGraph->isStarted()) { osPrintf("WARNING: flowgraph found still running, shutting down\n"); // ignore the result and keep going mpFlowGraph->stop(); // Request processing of another frame so that the STOP_FLOWGRAPH // message gets handled mpFlowGraph->processNextFrame(); } #ifdef xUSE_TEST_OUTPUT_DRIVER // [ OsFile::openAndWrite("capture.raw", (const char*)sinkDevice.getBufferData(), sinkDevice.getBufferLength()*sizeof(MpAudioSample)); #endif // USE_TEST_OUTPUT_DRIVER ] // Free all input device drivers for (; mInputDeviceNumber>0; mInputDeviceNumber--) { MpInputDeviceDriver *pDriver = mpInputDeviceManager->removeDevice(mInputDeviceNumber); CPPUNIT_ASSERT(pDriver != NULL); delete pDriver; } // Free all output device drivers for (; mOutputDeviceNumber>0; mOutputDeviceNumber--) { MpOutputDeviceDriver *pDriver = mpOutputDeviceManager->removeDevice(mOutputDeviceNumber); CPPUNIT_ASSERT(pDriver != NULL); delete pDriver; } // Free device managers delete mpOutputDeviceManager; mpOutputDeviceManager = NULL; delete mpInputDeviceManager; mpInputDeviceManager = NULL; // Free flowgraph delete mpFlowGraph; mpFlowGraph = NULL; // Free media task delete mpMediaTask; mpMediaTask = NULL; // Clear all Media Tasks data CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpShutdown()); } void testShortCircuit() { enableConsoleOutput(1); #ifdef RTL_ENABLED RTL_START(10000000); #endif MpInputDeviceHandle sourceDeviceId = 0; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpInputDeviceManager->getDeviceId("SineGenerator", sourceDeviceId)); MpOutputDeviceHandle sinkDeviceId = 0; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->getDeviceId("BufferRecorder", sinkDeviceId)); // Create source (input) and sink (output) resources. MprFromInputDevice sourceResource("MprFromInputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, mpInputDeviceManager, sourceDeviceId); MprToOutputDevice sinkResource("MprToOutputDevice", TEST_SAMPLES_PER_FRAME, TEST_SAMPLES_PER_SECOND, mpOutputDeviceManager, sinkDeviceId); try { // Add source and sink resources to flowgraph and link them together. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(sourceResource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addResource(sinkResource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->addLink(sourceResource, 0, sinkResource, 0)); // Enable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpInputDeviceManager->enableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->enableDevice(sinkDeviceId)); // Set flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->setFlowgraphTickerSource(sinkDeviceId)); try { // Enable resources CPPUNIT_ASSERT(sourceResource.enable()); CPPUNIT_ASSERT(sinkResource.enable()); // Manage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpMediaTask->manageFlowGraph(*mpFlowGraph)); // Start flowgraph CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpMediaTask->startFlowGraph(*mpFlowGraph)); // Run test! OsTask::delay(TEST_TIME_MS); // Clear flowgraph ticker CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->setFlowgraphTickerSource(MP_INVALID_OUTPUT_DEVICE_HANDLE)); } catch (CppUnit::Exception& e) { // Clear flowgraph ticker if assert failed. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->setFlowgraphTickerSource(MP_INVALID_OUTPUT_DEVICE_HANDLE)); // Rethrow exception. throw(e); } // Disable resources CPPUNIT_ASSERT(sourceResource.disable()); CPPUNIT_ASSERT(sinkResource.disable()); MpMediaTask::signalFrameStart(); // Unmanage flowgraph with media task. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpMediaTask->unmanageFlowGraph(*mpFlowGraph)); MpMediaTask::signalFrameStart(); // Disable devices CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpInputDeviceManager->disableDevice(sourceDeviceId)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpOutputDeviceManager->disableDevice(sinkDeviceId)); // Remove resources from flowgraph. We should remove them explicitly // here, because they are stored on the stack and will be destroyed. CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sinkResource)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sourceResource)); mpFlowGraph->processNextFrame(); } catch (CppUnit::Exception& e) { // Remove resources from flowgraph. We should remove them explicitly // here, because they are stored on the stack and will be destroyed. // If we will not catch this assert we'll have this resources destroyed // while still referenced in flowgraph, causing crash. if (sinkResource.getFlowGraph() != NULL) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sinkResource)); } if (sourceResource.getFlowGraph() != NULL) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, mpFlowGraph->removeResource(sourceResource)); } mpFlowGraph->processNextFrame(); // Rethrow exception. throw(e); } #ifdef RTL_ENABLED RTL_WRITE("testShortCircuit.rtl"); #endif } protected: MpFlowGraphBase *mpFlowGraph; ///< Flowgraph for our fromInputDevice and ///< toOutputDevice resources. MpMediaTask *mpMediaTask; ///< Pointer to media task instance. MpInputDeviceManager *mpInputDeviceManager; ///< Manager for input devices. MpOutputDeviceManager *mpOutputDeviceManager; ///< Manager for output devices. unsigned mInputDeviceNumber; unsigned mOutputDeviceNumber; /// Add passed device to input device manager. void manageInputDevice(MpInputDeviceDriver *pDriver) { // Add driver to manager MpInputDeviceHandle deviceId = mpInputDeviceManager->addDevice(*pDriver); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(!mpInputDeviceManager->isDeviceEnabled(deviceId)); // Driver is successfully added mInputDeviceNumber++; } /// Add passed device to output device manager. void manageOutputDevice(MpOutputDeviceDriver *pDriver) { // Add driver to manager MpOutputDeviceHandle deviceId = mpOutputDeviceManager->addDevice(pDriver); CPPUNIT_ASSERT(deviceId > 0); CPPUNIT_ASSERT(!mpOutputDeviceManager->isDeviceEnabled(deviceId)); // Driver is successfully added mOutputDeviceNumber++; } void createTestInputDriver() { #ifdef USE_TEST_INPUT_DRIVER // [ // Create driver MpSineWaveGeneratorDeviceDriver *pDriver = new MpSineWaveGeneratorDeviceDriver("SineGenerator", *mpInputDeviceManager, 32000, 3000, 0); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageInputDevice(pDriver); #endif // USE_TEST_INPUT_DRIVER ] } void createWntInputDrivers() { #ifdef USE_WNT_INPUT_DRIVER // [ // Create driver MpInputDeviceDriverWnt *pDriver = new MpInputDeviceDriverWnt("SoundMAX HD Audio", *mpInputDeviceManager); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageInputDevice(pDriver); #endif // USE_WNT_INPUT_DRIVER ] } void createOSSInputDrivers() { #ifdef USE_OSS_INPUT_DRIVER // [ // Create driver MpidOSS *pDriver = new MpidOSS("/dev/dsp", *mpInputDeviceManager); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageInputDevice(pDriver); #endif // USE_OSS_INPUT_DRIVER ] } void createTestOutputDriver() { #ifdef USE_TEST_OUTPUT_DRIVER // [ // Create driver MpodBufferRecorder *pDriver = new MpodBufferRecorder("BufferRecorder", TEST_TIME_MS); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageOutputDevice(pDriver); #endif // USE_TEST_OUTPUT_DRIVER ] } void createOSSOutputDrivers() { #ifdef USE_OSS_OUTPUT_DRIVER // [ // Create driver MpodOSS *pDriver = new MpodOSS("/dev/dsp"); CPPUNIT_ASSERT(pDriver != NULL); // Add driver to manager manageOutputDevice(pDriver); #endif // USE_OSS_OUTPUT_DRIVER ] } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpInputOutputFrameworkTest); <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "nearest_neighbor.hpp" #include <string> #include <utility> #include <vector> namespace jubatus { namespace core { namespace driver { nearest_neighbor::nearest_neighbor( pfi::lang::shared_ptr<core::nearest_neighbor::nearest_neighbor_base> nn, pfi::lang::shared_ptr<fv_converter::datum_to_fv_converter> converter) : mixable_holder_(new framework::mixable_holder), converter_(converter), nn_(nn) { nn_->register_mixables_to_holder(*mixable_holder_); } void nearest_neighbor::set_row( const std::string& id, const fv_converter::datum& datum) { common::sfv_t v; converter_->convert(datum, v); nn_->set_row(id, v); } std::vector<std::pair<std::string, float> > nearest_neighbor::neighbor_row_from_id(const std::string& id, size_t size) { std::vector<std::pair<std::string, float> > ret; nn_->neighbor_row(id, ret, size); return ret; } std::vector<std::pair<std::string, float> > nearest_neighbor::neighbor_row_from_data( const fv_converter::datum& datum, size_t size) { common::sfv_t v; converter_->convert(datum, v); std::vector<std::pair<std::string, float> > ret; nn_->neighbor_row(v, ret, size); return ret; } std::vector<std::pair<std::string, float> > nearest_neighbor::similar_row(const std::string& id, size_t ret_num) { std::vector<std::pair<std::string, float> > ret; nn_->similar_row(id, ret, ret_num); return ret; } std::vector<std::pair<std::string, float> > nearest_neighbor::similar_row( const core::fv_converter::datum& datum, size_t ret_num) { common::sfv_t v; converter_->convert(datum, v); std::vector<std::pair<std::string, float> > ret; nn_->similar_row(v, ret, ret_num); return ret; } void nearest_neighbor::clear() { converter_->clear_weights(); nn_->clear(); } } // namespace driver } // namespace core } // namespace jubatus <commit_msg>Add a TODO comment for #461<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "nearest_neighbor.hpp" #include <string> #include <utility> #include <vector> namespace jubatus { namespace core { namespace driver { nearest_neighbor::nearest_neighbor( pfi::lang::shared_ptr<core::nearest_neighbor::nearest_neighbor_base> nn, pfi::lang::shared_ptr<fv_converter::datum_to_fv_converter> converter) : mixable_holder_(new framework::mixable_holder), converter_(converter), nn_(nn) { nn_->register_mixables_to_holder(*mixable_holder_); // We cannot register mixables of fv converter, because mixable_weight_manager // does not support mixing with push_mixer. // TODO(beam2d): Support mixing weight manager with push_mixer and register // mixables of fv converter here. } void nearest_neighbor::set_row( const std::string& id, const fv_converter::datum& datum) { common::sfv_t v; converter_->convert(datum, v); nn_->set_row(id, v); } std::vector<std::pair<std::string, float> > nearest_neighbor::neighbor_row_from_id(const std::string& id, size_t size) { std::vector<std::pair<std::string, float> > ret; nn_->neighbor_row(id, ret, size); return ret; } std::vector<std::pair<std::string, float> > nearest_neighbor::neighbor_row_from_data( const fv_converter::datum& datum, size_t size) { common::sfv_t v; converter_->convert(datum, v); std::vector<std::pair<std::string, float> > ret; nn_->neighbor_row(v, ret, size); return ret; } std::vector<std::pair<std::string, float> > nearest_neighbor::similar_row(const std::string& id, size_t ret_num) { std::vector<std::pair<std::string, float> > ret; nn_->similar_row(id, ret, ret_num); return ret; } std::vector<std::pair<std::string, float> > nearest_neighbor::similar_row( const core::fv_converter::datum& datum, size_t ret_num) { common::sfv_t v; converter_->convert(datum, v); std::vector<std::pair<std::string, float> > ret; nn_->similar_row(v, ret, ret_num); return ret; } void nearest_neighbor::clear() { converter_->clear_weights(); nn_->clear(); } } // namespace driver } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE WebRtcEndpoint #include <boost/test/unit_test.hpp> #include <MediaPipelineImpl.hpp> #include <objects/WebRtcEndpointImpl.hpp> #include <IceCandidate.hpp> #include <mutex> #include <condition_variable> #include <ModuleManager.hpp> #include <KurentoException.hpp> #include <MediaSet.hpp> using namespace kurento; boost::property_tree::ptree config; std::string mediaPipelineId; ModuleManager moduleManager; std::once_flag init_flag; static void init_internal() { boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs; gst_init (NULL, NULL); moduleManager.loadModulesFromDirectories ("../../src/server"); config.add ("configPath", "../../../tests" ); config.add ("modules.kurento.SdpEndpoint.numAudioMedias", 1); config.add ("modules.kurento.SdpEndpoint.numVideoMedias", 1); ac.put ("name", "opus/48000/2"); audioCodecs.push_back (std::make_pair ("", ac) ); config.add_child ("modules.kurento.SdpEndpoint.audioCodecs", audioCodecs); vc.put ("name", "VP8/90000"); videoCodecs.push_back (std::make_pair ("", vc) ); config.add_child ("modules.kurento.SdpEndpoint.videoCodecs", videoCodecs); mediaPipelineId = moduleManager.getFactory ("MediaPipeline")->createObject ( config, "", Json::Value() )->getId(); } static void init() { std::call_once (init_flag, init_internal); } static std::shared_ptr <WebRtcEndpointImpl> createWebrtc (void) { std::shared_ptr <kurento::MediaObjectImpl> webrtcEndpoint; Json::Value constructorParams; constructorParams ["mediaPipeline"] = mediaPipelineId; webrtcEndpoint = moduleManager.getFactory ("WebRtcEndpoint")->createObject ( config, "", constructorParams ); return std::dynamic_pointer_cast <WebRtcEndpointImpl> (webrtcEndpoint); } static void releaseWebRtc (std::shared_ptr<WebRtcEndpointImpl> &ep) { std::string id = ep->getId(); ep.reset(); MediaSet::getMediaSet ()->release (id); } BOOST_AUTO_TEST_CASE (gathering_done) { init (); std::atomic<bool> gathering_done (false); std::condition_variable cv; std::mutex mtx; std::unique_lock<std::mutex> lck (mtx); std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc(); webRtcEp->signalOnIceGatheringDone.connect ([&] (OnIceGatheringDone event) { gathering_done = true; cv.notify_one(); }); webRtcEp->generateOffer (); webRtcEp->gatherCandidates (); cv.wait_for (lck, std::chrono::seconds (5), [&] () { return gathering_done.load(); }); if (!gathering_done) { BOOST_ERROR ("Gathering not done"); } releaseWebRtc (webRtcEp); } BOOST_AUTO_TEST_CASE (ice_state_changes) { init (); std::atomic<bool> ice_state_changed (false); std::condition_variable cv; std::mutex mtx; std::unique_lock<std::mutex> lck (mtx); std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc(); std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc(); webRtcEpOfferer->setName ("offerer"); webRtcEpAnswerer->setName ("answerer"); webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) { webRtcEpAnswerer->addIceCandidate (event.getCandidate() ); }); webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) { webRtcEpOfferer->addIceCandidate (event.getCandidate() ); }); webRtcEpOfferer->signalOnIceComponentStateChanged.connect ([&] ( OnIceComponentStateChanged event) { ice_state_changed = true; cv.notify_one(); }); std::string offer = webRtcEpOfferer->generateOffer (); std::string answer = webRtcEpAnswerer->processOffer (offer); webRtcEpOfferer->processAnswer (answer); std::cout << offer << std::endl; webRtcEpOfferer->gatherCandidates (); webRtcEpAnswerer->gatherCandidates (); cv.wait_for (lck, std::chrono::seconds (5), [&] () { return ice_state_changed.load(); }); if (!ice_state_changed) { BOOST_ERROR ("ICE state not chagned"); } releaseWebRtc (webRtcEpOfferer); releaseWebRtc (webRtcEpAnswerer); } BOOST_AUTO_TEST_CASE (stun_turn_properties) { std::string stunServerAddress ("10.0.0.1"); int stunServerPort = 2345; std::string turnUrl ("user0:[email protected]:3456"); init (); std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc(); webRtcEp->setStunServerAddress (stunServerAddress); std::string stunServerAddressRet = webRtcEp->getStunServerAddress (); BOOST_CHECK (stunServerAddressRet == stunServerAddress); webRtcEp->setStunServerPort (stunServerPort); int stunServerPortRet = webRtcEp->getStunServerPort (); BOOST_CHECK (stunServerPortRet == stunServerPort); webRtcEp->setTurnUrl (turnUrl); std::string turnUrlRet = webRtcEp->getTurnUrl (); BOOST_CHECK (turnUrlRet == turnUrl); releaseWebRtc (webRtcEp); } <commit_msg>webRtcEndpoint: remove console out<commit_after>/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE WebRtcEndpoint #include <boost/test/unit_test.hpp> #include <MediaPipelineImpl.hpp> #include <objects/WebRtcEndpointImpl.hpp> #include <IceCandidate.hpp> #include <mutex> #include <condition_variable> #include <ModuleManager.hpp> #include <KurentoException.hpp> #include <MediaSet.hpp> using namespace kurento; boost::property_tree::ptree config; std::string mediaPipelineId; ModuleManager moduleManager; std::once_flag init_flag; static void init_internal() { boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs; gst_init (NULL, NULL); moduleManager.loadModulesFromDirectories ("../../src/server"); config.add ("configPath", "../../../tests" ); config.add ("modules.kurento.SdpEndpoint.numAudioMedias", 1); config.add ("modules.kurento.SdpEndpoint.numVideoMedias", 1); ac.put ("name", "opus/48000/2"); audioCodecs.push_back (std::make_pair ("", ac) ); config.add_child ("modules.kurento.SdpEndpoint.audioCodecs", audioCodecs); vc.put ("name", "VP8/90000"); videoCodecs.push_back (std::make_pair ("", vc) ); config.add_child ("modules.kurento.SdpEndpoint.videoCodecs", videoCodecs); mediaPipelineId = moduleManager.getFactory ("MediaPipeline")->createObject ( config, "", Json::Value() )->getId(); } static void init() { std::call_once (init_flag, init_internal); } static std::shared_ptr <WebRtcEndpointImpl> createWebrtc (void) { std::shared_ptr <kurento::MediaObjectImpl> webrtcEndpoint; Json::Value constructorParams; constructorParams ["mediaPipeline"] = mediaPipelineId; webrtcEndpoint = moduleManager.getFactory ("WebRtcEndpoint")->createObject ( config, "", constructorParams ); return std::dynamic_pointer_cast <WebRtcEndpointImpl> (webrtcEndpoint); } static void releaseWebRtc (std::shared_ptr<WebRtcEndpointImpl> &ep) { std::string id = ep->getId(); ep.reset(); MediaSet::getMediaSet ()->release (id); } BOOST_AUTO_TEST_CASE (gathering_done) { init (); std::atomic<bool> gathering_done (false); std::condition_variable cv; std::mutex mtx; std::unique_lock<std::mutex> lck (mtx); std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc(); webRtcEp->signalOnIceGatheringDone.connect ([&] (OnIceGatheringDone event) { gathering_done = true; cv.notify_one(); }); webRtcEp->generateOffer (); webRtcEp->gatherCandidates (); cv.wait_for (lck, std::chrono::seconds (5), [&] () { return gathering_done.load(); }); if (!gathering_done) { BOOST_ERROR ("Gathering not done"); } releaseWebRtc (webRtcEp); } BOOST_AUTO_TEST_CASE (ice_state_changes) { init (); std::atomic<bool> ice_state_changed (false); std::condition_variable cv; std::mutex mtx; std::unique_lock<std::mutex> lck (mtx); std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc(); std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc(); webRtcEpOfferer->setName ("offerer"); webRtcEpAnswerer->setName ("answerer"); webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) { webRtcEpAnswerer->addIceCandidate (event.getCandidate() ); }); webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) { webRtcEpOfferer->addIceCandidate (event.getCandidate() ); }); webRtcEpOfferer->signalOnIceComponentStateChanged.connect ([&] ( OnIceComponentStateChanged event) { ice_state_changed = true; cv.notify_one(); }); std::string offer = webRtcEpOfferer->generateOffer (); std::string answer = webRtcEpAnswerer->processOffer (offer); webRtcEpOfferer->processAnswer (answer); webRtcEpOfferer->gatherCandidates (); webRtcEpAnswerer->gatherCandidates (); cv.wait_for (lck, std::chrono::seconds (5), [&] () { return ice_state_changed.load(); }); if (!ice_state_changed) { BOOST_ERROR ("ICE state not chagned"); } releaseWebRtc (webRtcEpOfferer); releaseWebRtc (webRtcEpAnswerer); } BOOST_AUTO_TEST_CASE (stun_turn_properties) { std::string stunServerAddress ("10.0.0.1"); int stunServerPort = 2345; std::string turnUrl ("user0:[email protected]:3456"); init (); std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc(); webRtcEp->setStunServerAddress (stunServerAddress); std::string stunServerAddressRet = webRtcEp->getStunServerAddress (); BOOST_CHECK (stunServerAddressRet == stunServerAddress); webRtcEp->setStunServerPort (stunServerPort); int stunServerPortRet = webRtcEp->getStunServerPort (); BOOST_CHECK (stunServerPortRet == stunServerPort); webRtcEp->setTurnUrl (turnUrl); std::string turnUrlRet = webRtcEp->getTurnUrl (); BOOST_CHECK (turnUrlRet == turnUrl); releaseWebRtc (webRtcEp); } <|endoftext|>
<commit_before>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGL/RenderTarget.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include <cmath> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> const double OpenGLRenderTarget<T>::d_yfov_tan = 0.267949192431123; //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) : d_owner(owner), d_area(0, 0, 0, 0), d_matrix(1.0f), d_matrixValid(false), d_viewDistance(0) { } //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::~OpenGLRenderTarget() { } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::setArea(const Rectf& area) { d_area = area; d_matrixValid = false; RenderTargetEventArgs args(this); T::fireEvent(RenderTarget::EventAreaChanged, args); } //----------------------------------------------------------------------------// template <typename T> const Rectf& OpenGLRenderTarget<T>::getArea() const { return d_area; } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::activate() { glViewport(static_cast<GLsizei>(d_area.left()), static_cast<GLsizei>(d_area.top()), static_cast<GLsizei>(d_area.getWidth()), static_cast<GLsizei>(d_area.getHeight())); if (!d_matrixValid) updateMatrix(); d_owner.setViewProjectionMatrix(d_matrix); RenderTarget::activate(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::deactivate() { } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); const OpenGLGeometryBufferBase& gb = static_cast<const OpenGLGeometryBufferBase&>(buff); const GLint vp[4] = { static_cast<GLint>(d_area.left()), static_cast<GLint>(d_area.top()), static_cast<GLint>(d_area.getWidth()), static_cast<GLint>(d_area.getHeight()) }; GLdouble in_x, in_y, in_z; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); const glm::mat4& projMatrix = d_matrix; const glm::mat4& modelMatrix = gb.getModelMatrix(); // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; in_z = -d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = p_in.x; in_y = vp[3] - p_in.y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // project points to orientate them with GeometryBuffer plane glm::vec3 projected1; glm::vec3 projected2; glm::vec3 projected3; in_x = 0.0; in_y = 0.0; projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 1.0; in_y = 0.0; projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 0.0; in_y = 1.0; projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // calculate vectors for generating the plane const glm::vec3 pv1 = projected2 - projected1; const glm::vec3 pv2 = projected3 - projected1; // given the vectors, calculate the plane normal const glm::vec3 planeNormal = glm::cross(pv1, pv2); // calculate plane const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); const double pl_d = - glm::dot(projected1, planeNormalNormalized); // calculate vector of picking ray const glm::vec3 rv = unprojected1 - unprojected2; // calculate intersection of ray and plane const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); const double pn_dot_rv = glm::dot(rv, planeNormal); const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; p_out.x = static_cast<float>(is_x); p_out.y = static_cast<float>(is_y); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::updateMatrix() const { const float w = d_area.getWidth(); const float h = d_area.getHeight(); // We need to check if width or height are zero and act accordingly to prevent running into issues // with divisions by zero which would lead to undefined values, as well as faulty clipping planes // This is mostly important for avoiding asserts const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); const float aspect = widthAndHeightNotZero ? w / h : 1.0f; const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; d_viewDistance = midx / (aspect * d_yfov_tan); glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); glm::vec3 center = glm::vec3(midx, midy, 1); glm::vec3 up = glm::vec3(0, -1, 0); glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0)); // Projection matrix abuse! glm::mat4 viewMatrix = glm::lookAt(eye, center, up); d_matrix = projectionMatrix * viewMatrix; d_matrixValid = true; //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices d_activationCounter = -1; } //----------------------------------------------------------------------------// template <typename T> Renderer& OpenGLRenderTarget<T>::getOwner() { return d_owner; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: Adding missing qualifier<commit_after>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGL/RenderTarget.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include <cmath> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> const double OpenGLRenderTarget<T>::d_yfov_tan = 0.267949192431123; //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) : d_owner(owner), d_area(0, 0, 0, 0), d_matrix(1.0f), d_matrixValid(false), d_viewDistance(0) { } //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::~OpenGLRenderTarget() { } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::setArea(const Rectf& area) { d_area = area; d_matrixValid = false; RenderTargetEventArgs args(this); T::fireEvent(RenderTarget::EventAreaChanged, args); } //----------------------------------------------------------------------------// template <typename T> const Rectf& OpenGLRenderTarget<T>::getArea() const { return d_area; } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::activate() { glViewport(static_cast<GLsizei>(d_area.left()), static_cast<GLsizei>(d_area.top()), static_cast<GLsizei>(d_area.getWidth()), static_cast<GLsizei>(d_area.getHeight())); if (!d_matrixValid) updateMatrix(); d_owner.setViewProjectionMatrix(d_matrix); RenderTarget::activate(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::deactivate() { } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); const OpenGLGeometryBufferBase& gb = static_cast<const OpenGLGeometryBufferBase&>(buff); const GLint vp[4] = { static_cast<GLint>(d_area.left()), static_cast<GLint>(d_area.top()), static_cast<GLint>(d_area.getWidth()), static_cast<GLint>(d_area.getHeight()) }; GLdouble in_x, in_y, in_z; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); const glm::mat4& projMatrix = d_matrix; const glm::mat4& modelMatrix = gb.getModelMatrix(); // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; in_z = -d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = p_in.x; in_y = vp[3] - p_in.y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // project points to orientate them with GeometryBuffer plane glm::vec3 projected1; glm::vec3 projected2; glm::vec3 projected3; in_x = 0.0; in_y = 0.0; projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 1.0; in_y = 0.0; projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 0.0; in_y = 1.0; projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // calculate vectors for generating the plane const glm::vec3 pv1 = projected2 - projected1; const glm::vec3 pv2 = projected3 - projected1; // given the vectors, calculate the plane normal const glm::vec3 planeNormal = glm::cross(pv1, pv2); // calculate plane const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); const double pl_d = - glm::dot(projected1, planeNormalNormalized); // calculate vector of picking ray const glm::vec3 rv = unprojected1 - unprojected2; // calculate intersection of ray and plane const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); const double pn_dot_rv = glm::dot(rv, planeNormal); const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; p_out.x = static_cast<float>(is_x); p_out.y = static_cast<float>(is_y); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::updateMatrix() const { const float w = d_area.getWidth(); const float h = d_area.getHeight(); // We need to check if width or height are zero and act accordingly to prevent running into issues // with divisions by zero which would lead to undefined values, as well as faulty clipping planes // This is mostly important for avoiding asserts const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); const float aspect = widthAndHeightNotZero ? w / h : 1.0f; const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; d_viewDistance = midx / (aspect * d_yfov_tan); glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); glm::vec3 center = glm::vec3(midx, midy, 1); glm::vec3 up = glm::vec3(0, -1, 0); glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0)); // Projection matrix abuse! glm::mat4 viewMatrix = glm::lookAt(eye, center, up); d_matrix = projectionMatrix * viewMatrix; d_matrixValid = true; //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices RenderTarget::d_activationCounter = -1; } //----------------------------------------------------------------------------// template <typename T> Renderer& OpenGLRenderTarget<T>::getOwner() { return d_owner; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/* chiasmusjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "chiasmusjob.h" #include "chiasmusbackend.h" #include "symcryptrunprocessbase.h" #include "kleo/cryptoconfig.h" #include "ui/passphrasedialog.h" #include <gpg-error.h> #include <kshell.h> #include <klocale.h> #include <kdebug.h> #include <kmessagebox.h> #include <qtimer.h> #include <qfileinfo.h> #include <qvariant.h> #include <memory> #include <cassert> Kleo::ChiasmusJob::ChiasmusJob( Mode mode ) : Kleo::SpecialJob( 0, 0 ), mSymCryptRun( 0 ), mError( 0 ), mCanceled( false ), mTimeout( true ), mMode( mode ) { } Kleo::ChiasmusJob::~ChiasmusJob() {} GpgME::Error Kleo::ChiasmusJob::setup() { if ( !checkPreconditions() ) return mError = gpg_error( GPG_ERR_INV_VALUE ); const Kleo::CryptoConfigEntry * class_ = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "symcryptrun-class" ); const Kleo::CryptoConfigEntry * chiasmus = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "path" ); const Kleo::CryptoConfigEntry * timeoutEntry = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "timeout" ); if ( !class_ || !chiasmus || !timeoutEntry ) return mError = gpg_error( GPG_ERR_INTERNAL ); mSymCryptRun = new SymCryptRunProcessBase( class_->stringValue(), KShell::tildeExpand( chiasmus->urlValue().path() ), mKey, mOptions, mMode == Encrypt ? SymCryptRunProcessBase::Encrypt : SymCryptRunProcessBase::Decrypt, this, "symcryptrun" ); QTimer::singleShot( timeoutEntry->uintValue() * 1000, this, SLOT( slotTimeout() ) ); return 0; } namespace { struct LaterDeleter { QObject * _this; LaterDeleter( QObject * o ) : _this( o ) {} ~LaterDeleter() { if ( _this ) _this->deleteLater(); } void disable() { _this = 0; } }; } GpgME::Error Kleo::ChiasmusJob::start() { LaterDeleter d( this ); if ( const GpgME::Error err = setup() ) return mError = err; connect( mSymCryptRun, SIGNAL(processExited(KProcess*)), this, SLOT(slotProcessExited(KProcess*)) ); if ( !mSymCryptRun->launch( mInput ) ) return mError = gpg_error( GPG_ERR_ENOENT ); // what else? d.disable(); return mError = 0; } GpgME::Error Kleo::ChiasmusJob::slotProcessExited( KProcess * proc ) { if ( proc != mSymCryptRun ) mError = gpg_error( GPG_ERR_INTERNAL ); else if ( mCanceled ) mError = gpg_error( GPG_ERR_CANCELED ); else if ( mTimeout ) mError = gpg_error( GPG_ERR_TIMEOUT ); else if ( !proc->normalExit() ) mError = gpg_error( GPG_ERR_GENERAL ); else switch ( proc->exitStatus() ) { case 0: // success mOutput = mSymCryptRun->output(); mError = 0; break; default: case 1: // Some error occured mStderr = mSymCryptRun->stderr(); mError = gpg_error( GPG_ERR_GENERAL ); break; case 2: // No valid passphrase was provided mError = gpg_error( GPG_ERR_INV_PASSPHRASE ); break; case 3: // Canceled mError = gpg_error( GPG_ERR_CANCELED ); break; } const Kleo::CryptoConfigEntry * showOutput = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "show-output" ); if ( showOutput && showOutput->boolValue() ) { showChiasmusOutput(); } emit done(); emit SpecialJob::result( mError, QVariant( mOutput ) ); return mError; } void Kleo::ChiasmusJob::showChiasmusOutput() { kdDebug() << k_funcinfo << endl; if ( mStderr.isEmpty() ) return; KMessageBox::information( 0 /*how to get a parent widget?*/, mStderr, i18n( "Output from chiasmus" ) ); } GpgME::Error Kleo::ChiasmusJob::exec() { if ( const GpgME::Error err = setup() ) return mError = err; if ( !mSymCryptRun->launch( mInput, KProcess::Block ) ) { delete mSymCryptRun; mSymCryptRun = 0; return mError = gpg_error( GPG_ERR_ENOENT ); // what else? } const GpgME::Error err = slotProcessExited( mSymCryptRun ); delete mSymCryptRun; mSymCryptRun = 0; return err; } bool Kleo::ChiasmusJob::checkPreconditions() const { return !mKey.isEmpty(); } void Kleo::ChiasmusJob::slotCancel() { if ( mSymCryptRun ) mSymCryptRun->kill(); mCanceled = true; } void Kleo::ChiasmusJob::slotTimeout() { if ( !mSymCryptRun ) return; mSymCryptRun->kill(); mTimeout = true; } void Kleo::ChiasmusJob::showErrorDialog( QWidget * parent, const QString & caption ) const { if ( !mError ) return; if ( mError.isCanceled() ) return; const QString msg = ( mMode == Encrypt ? i18n( "Encryption failed: %1" ) : i18n( "Decryption failed: %1" ) ) .arg( QString::fromLocal8Bit( mError.asString() ) ); if ( !mStderr.isEmpty() ) { const QString details = i18n( "The following was received on stderr:\n%1" ).arg( mStderr ); KMessageBox::detailedError( parent, msg, details, caption ); } else { KMessageBox::error( parent, msg, caption ); } } #include "chiasmusjob.moc" <commit_msg>Initialize the timeout error flag to false, not true.<commit_after>/* chiasmusjob.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2005 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "chiasmusjob.h" #include "chiasmusbackend.h" #include "symcryptrunprocessbase.h" #include "kleo/cryptoconfig.h" #include "ui/passphrasedialog.h" #include <gpg-error.h> #include <kshell.h> #include <klocale.h> #include <kdebug.h> #include <kmessagebox.h> #include <qtimer.h> #include <qfileinfo.h> #include <qvariant.h> #include <memory> #include <cassert> Kleo::ChiasmusJob::ChiasmusJob( Mode mode ) : Kleo::SpecialJob( 0, 0 ), mSymCryptRun( 0 ), mError( 0 ), mCanceled( false ), mTimeout( false ), mMode( mode ) { } Kleo::ChiasmusJob::~ChiasmusJob() {} GpgME::Error Kleo::ChiasmusJob::setup() { if ( !checkPreconditions() ) return mError = gpg_error( GPG_ERR_INV_VALUE ); const Kleo::CryptoConfigEntry * class_ = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "symcryptrun-class" ); const Kleo::CryptoConfigEntry * chiasmus = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "path" ); const Kleo::CryptoConfigEntry * timeoutEntry = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "timeout" ); if ( !class_ || !chiasmus || !timeoutEntry ) return mError = gpg_error( GPG_ERR_INTERNAL ); mSymCryptRun = new SymCryptRunProcessBase( class_->stringValue(), KShell::tildeExpand( chiasmus->urlValue().path() ), mKey, mOptions, mMode == Encrypt ? SymCryptRunProcessBase::Encrypt : SymCryptRunProcessBase::Decrypt, this, "symcryptrun" ); QTimer::singleShot( timeoutEntry->uintValue() * 1000, this, SLOT( slotTimeout() ) ); return 0; } namespace { struct LaterDeleter { QObject * _this; LaterDeleter( QObject * o ) : _this( o ) {} ~LaterDeleter() { if ( _this ) _this->deleteLater(); } void disable() { _this = 0; } }; } GpgME::Error Kleo::ChiasmusJob::start() { LaterDeleter d( this ); if ( const GpgME::Error err = setup() ) return mError = err; connect( mSymCryptRun, SIGNAL(processExited(KProcess*)), this, SLOT(slotProcessExited(KProcess*)) ); if ( !mSymCryptRun->launch( mInput ) ) return mError = gpg_error( GPG_ERR_ENOENT ); // what else? d.disable(); return mError = 0; } GpgME::Error Kleo::ChiasmusJob::slotProcessExited( KProcess * proc ) { if ( proc != mSymCryptRun ) mError = gpg_error( GPG_ERR_INTERNAL ); else if ( mCanceled ) mError = gpg_error( GPG_ERR_CANCELED ); else if ( mTimeout ) mError = gpg_error( GPG_ERR_TIMEOUT ); else if ( !proc->normalExit() ) mError = gpg_error( GPG_ERR_GENERAL ); else switch ( proc->exitStatus() ) { case 0: // success mOutput = mSymCryptRun->output(); mError = 0; break; default: case 1: // Some error occured mStderr = mSymCryptRun->stderr(); mError = gpg_error( GPG_ERR_GENERAL ); break; case 2: // No valid passphrase was provided mError = gpg_error( GPG_ERR_INV_PASSPHRASE ); break; case 3: // Canceled mError = gpg_error( GPG_ERR_CANCELED ); break; } const Kleo::CryptoConfigEntry * showOutput = ChiasmusBackend::instance()->config()->entry( "Chiasmus", "General", "show-output" ); if ( showOutput && showOutput->boolValue() ) { showChiasmusOutput(); } emit done(); emit SpecialJob::result( mError, QVariant( mOutput ) ); return mError; } void Kleo::ChiasmusJob::showChiasmusOutput() { kdDebug() << k_funcinfo << endl; if ( mStderr.isEmpty() ) return; KMessageBox::information( 0 /*how to get a parent widget?*/, mStderr, i18n( "Output from chiasmus" ) ); } GpgME::Error Kleo::ChiasmusJob::exec() { if ( const GpgME::Error err = setup() ) return mError = err; if ( !mSymCryptRun->launch( mInput, KProcess::Block ) ) { delete mSymCryptRun; mSymCryptRun = 0; return mError = gpg_error( GPG_ERR_ENOENT ); // what else? } const GpgME::Error err = slotProcessExited( mSymCryptRun ); delete mSymCryptRun; mSymCryptRun = 0; return err; } bool Kleo::ChiasmusJob::checkPreconditions() const { return !mKey.isEmpty(); } void Kleo::ChiasmusJob::slotCancel() { if ( mSymCryptRun ) mSymCryptRun->kill(); mCanceled = true; } void Kleo::ChiasmusJob::slotTimeout() { if ( !mSymCryptRun ) return; mSymCryptRun->kill(); mTimeout = true; } void Kleo::ChiasmusJob::showErrorDialog( QWidget * parent, const QString & caption ) const { if ( !mError ) return; if ( mError.isCanceled() ) return; const QString msg = ( mMode == Encrypt ? i18n( "Encryption failed: %1" ) : i18n( "Decryption failed: %1" ) ) .arg( QString::fromLocal8Bit( mError.asString() ) ); if ( !mStderr.isEmpty() ) { const QString details = i18n( "The following was received on stderr:\n%1" ).arg( mStderr ); KMessageBox::detailedError( parent, msg, details, caption ); } else { KMessageBox::error( parent, msg, caption ); } } #include "chiasmusjob.moc" <|endoftext|>
<commit_before>/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * wxparaver * * Paraver Trace Visualization and Analysis Tool * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ /* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\ | @file: $HeadURL$ | @last_commit: $Date$ | @version: $Revision$ \* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ #include "windows_tree.h" #include "loadedwindows.h" #include "gtimeline.h" #include "ghistogram.h" #include "paravermain.h" wxTreeCtrl * createTree( wxImageList *imageList ) { wxChoicebook *choiceWindowBrowser = paraverMain::myParaverMain->choiceWindowBrowser; wxTreeCtrl *newTree = new wxTreeCtrl( choiceWindowBrowser, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT|wxTR_DEFAULT_STYLE ); #ifndef WIN32 newTree->SetWindowStyle( wxTR_HAS_BUTTONS|wxTR_HIDE_ROOT|wxTR_SINGLE ); #endif newTree->SetImageList( imageList ); newTree->AddRoot( wxT( "Root" ), -1, -1, new TreeBrowserItemData( _( "Root" ), (gTimeline *)NULL ) ); return newTree; } wxTreeCtrl *getAllTracesTree() { wxChoicebook *choiceWindowBrowser = paraverMain::myParaverMain->choiceWindowBrowser; return (wxTreeCtrl *) choiceWindowBrowser->GetPage( 0 ); } wxTreeCtrl *getSelectedTraceTree( Trace *trace ) { wxChoicebook *choiceWindowBrowser = paraverMain::myParaverMain->choiceWindowBrowser; PRV_INT16 currentTrace = paraverMain::myParaverMain->getTracePosition( trace ); return (wxTreeCtrl *) choiceWindowBrowser->GetPage( currentTrace + 1 ); } void appendHistogram2Tree( gHistogram *ghistogram ) { // Refresh tree in current page and always in global page wxTreeCtrl *allTracesPage = getAllTracesTree(); wxTreeCtrl *currentPage = getSelectedTraceTree( ghistogram->GetHistogram()->getControlWindow()->getTrace() ); TreeBrowserItemData *currentData = new TreeBrowserItemData( wxString::FromAscii( ghistogram->GetHistogram()->getName().c_str() ), ghistogram ); wxTreeItemId currentWindowId1 = allTracesPage->AppendItem( allTracesPage->GetRootItem(), wxString::FromAscii( ghistogram->GetHistogram()->getName().c_str() ), 0, -1, currentData ); wxTreeItemId currentWindowId2 = currentPage->AppendItem( currentPage->GetRootItem(), wxString::FromAscii( ghistogram->GetHistogram()->getName().c_str() ), 0, -1, new TreeBrowserItemData( *currentData ) ); } wxTreeItemId getItemIdFromGTimeline( wxTreeItemId root, gTimeline *wanted, bool &found ) { wxTreeItemIdValue cookie; found = false; wxTreeItemId itemCurrent = getAllTracesTree()->GetFirstChild( root, cookie ); wxTreeItemId itemLast = getAllTracesTree()->GetLastChild( root ); while ( !found && itemCurrent.IsOk() && itemCurrent != itemLast ) { gTimeline *tmpTimeline = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemCurrent )))->getTimeline(); if ( tmpTimeline != NULL && tmpTimeline == wanted ) { root = itemCurrent; found = true; } else if ( tmpTimeline != NULL ) { root = getItemIdFromGTimeline( itemCurrent, wanted, found ); } if( !found ) itemCurrent = getAllTracesTree()->GetNextChild( root, cookie ); } if( !found && itemLast.IsOk() ) { if (((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline() == wanted ) { root = itemLast; found = true; } else { root = getItemIdFromGTimeline( itemLast, wanted, found ); } } return root; } // TODO: Separate recursion function to remove bool from parameters in main definition gTimeline *getGTimelineFromWindow( wxTreeItemId root, Window *wanted, bool &found ) { gTimeline *retgt = NULL; wxTreeItemIdValue cookie; found = false; wxTreeItemId itemCurrent = getAllTracesTree()->GetFirstChild( root, cookie ); wxTreeItemId itemLast = getAllTracesTree()->GetLastChild( root ); while ( !found && itemCurrent.IsOk() && itemCurrent != itemLast ) { gTimeline *tmpTimeline = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemCurrent )))->getTimeline(); if ( tmpTimeline != NULL && tmpTimeline->GetMyWindow() == wanted ) { retgt = tmpTimeline; found = true; } else if ( tmpTimeline != NULL ) { retgt = getGTimelineFromWindow( itemCurrent, wanted, found ); } if( !found ) itemCurrent = getAllTracesTree()->GetNextChild( root, cookie ); } if( !found && itemLast.IsOk() ) { if (((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline()->GetMyWindow() == wanted ) { retgt = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline(); found = true; } else { retgt = getGTimelineFromWindow( itemLast, wanted, found ); } } return retgt; } wxTreeItemId getItemIdFromWindow( wxTreeItemId root, Window *wanted, bool &found ) { wxTreeItemId retItemId; wxTreeItemIdValue cookie; found = false; wxTreeItemId itemCurrent = getAllTracesTree()->GetFirstChild( root, cookie ); wxTreeItemId itemLast = getAllTracesTree()->GetLastChild( root ); while ( !found && itemCurrent.IsOk() && itemCurrent != itemLast ) { gTimeline *tmpTimeline = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemCurrent )))->getTimeline(); if ( tmpTimeline != NULL && tmpTimeline->GetMyWindow() == wanted ) { retItemId = itemCurrent; found = true; } else if ( tmpTimeline != NULL ) { retItemId = getItemIdFromWindow( itemCurrent, wanted, found ); } if( !found ) itemCurrent = getAllTracesTree()->GetNextChild( root, cookie ); } if( !found && itemLast.IsOk() ) { if (((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline()->GetMyWindow() == wanted ) { retItemId = itemLast; found = true; } else { retItemId = getItemIdFromWindow( itemLast, wanted, found ); } } return retItemId; } // precond : current is a derived gTimeline void getParentGTimeline( gTimeline *current, vector< gTimeline * > & parents ) { // find item for given current gTimeline. bool found; wxTreeItemId item = getItemIdFromGTimeline( getAllTracesTree()->GetRootItem(), current, found ); // fill vector with parents wxTreeItemIdValue cookie; parents.push_back(((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( getAllTracesTree()->GetFirstChild( item, cookie ))))->getTimeline()); parents.push_back(((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( getAllTracesTree()->GetNextChild( item, cookie ) )))->getTimeline()); } void BuildTree( paraverMain *parent, wxTreeCtrl *root1, wxTreeItemId idRoot1, wxTreeCtrl *root2, wxTreeItemId idRoot2, Window *window, string nameSuffix ) { wxTreeItemId currentWindowId1, currentWindowId2; TreeBrowserItemData *currentData; string composedName = window->getName() + " @ " + window->getTrace()->getTraceName(); wxPoint tmpPos( window->getPosX(), window->getPosY() ); gTimeline* tmpTimeline = new gTimeline( parent, wxID_ANY, wxString::FromAscii( composedName.c_str() ), tmpPos ); LoadedWindows::getInstance()->add( window ); tmpTimeline->SetMyWindow( window ); tmpTimeline->SetClientSize( wxSize( window->getWidth(), window->getHeight() ) ); currentData = new TreeBrowserItemData( wxString::FromAscii( window->getName().c_str() ), tmpTimeline ); int iconNumber = 1; // number of timeline icon if ( window->isDerivedWindow() ) { string derivedFunctionName = window->getLevelFunction( DERIVED ); // GUI should'nt know these tags -> add operation to kernel if ( derivedFunctionName == "add" ) iconNumber = 2; else if ( derivedFunctionName == "product" ) iconNumber = 3; else if ( derivedFunctionName == "substract" ) iconNumber = 4; else if ( derivedFunctionName == "divide" ) iconNumber = 5; else if ( derivedFunctionName == "maximum" ) iconNumber = 6; else if ( derivedFunctionName == "minimum" ) iconNumber = 7; else if ( derivedFunctionName == "different" ) iconNumber = 8; else if ( derivedFunctionName == "controlled: clear by" ) iconNumber = 9; else if ( derivedFunctionName == "controlled: maximum" ) iconNumber = 10; else if ( derivedFunctionName == "controlled: add" ) iconNumber = 11; } currentWindowId1 = root1->AppendItem( idRoot1, wxString::FromAscii( window->getName().c_str() ), iconNumber, -1, currentData ); currentWindowId2 = root2->AppendItem( idRoot2, wxString::FromAscii( window->getName().c_str() ), iconNumber, -1, new TreeBrowserItemData( *currentData ) ); if ( window->getParent( 0 ) != NULL ) { BuildTree( parent, root1, currentWindowId1, root2, currentWindowId2, window->getParent( 0 ) ); BuildTree( parent, root1, currentWindowId1, root2, currentWindowId2, window->getParent( 1 ) ); } parent->SetCurrentWindow( (wxWindow *)tmpTimeline ); } bool updateTreeItem( wxTreeCtrl *tree, wxTreeItemId& id, vector< Window * > &allWindows, vector< Histogram * > &allHistograms, wxWindow **currentWindow, bool allTracesTree ) { bool destroy = false; TreeBrowserItemData *itemData = (TreeBrowserItemData *)tree->GetItemData( id ); // No matter timeline or histogram, get its name and delete from given vector wxString tmpName; if( gTimeline *tmpTimeline = itemData->getTimeline() ) { Window *tmpWindow = tmpTimeline->GetMyWindow(); if( tmpWindow->isSync() ) tree->SetItemBold( id, true ); else tree->SetItemBold( id, false ); if( tmpTimeline->IsActive() && !tmpWindow->getDestroy() ) { *currentWindow = tmpTimeline; tree->SelectItem( id ); } tmpName = wxString::FromAscii( tmpWindow->getName().c_str() ); for ( vector<Window *>::iterator it = allWindows.begin(); it != allWindows.end(); it++ ) { if ( *it == tmpWindow ) { allWindows.erase( it ); break; } } if( tmpWindow->getDestroy() ) { if( paraverMain::myParaverMain->GetCurrentTimeline() == tmpWindow ) { paraverMain::myParaverMain->SetCurrentTimeline( NULL ); paraverMain::myParaverMain->clearProperties(); } if( !allTracesTree ) tmpTimeline->Destroy(); Window *parent1 = tmpWindow->getParent( 0 ); if( parent1 != NULL ) { parent1->setChild( NULL ); parent1->setDestroy( true ); } Window *parent2 = tmpWindow->getParent( 1 ); if( parent2 != NULL ) { parent2->setChild( NULL ); parent2->setDestroy( true ); } destroy = true; } } else if( gHistogram *tmpHistogram = itemData->getHistogram() ) { Histogram *tmpHisto = tmpHistogram->GetHistogram(); if( tmpHistogram->IsActive() && !tmpHisto->getDestroy() ) { *currentWindow = tmpHistogram; tree->SelectItem( id ); } tmpName = wxString::FromAscii( tmpHisto->getName().c_str() ); for ( vector<Histogram *>::iterator it = allHistograms.begin(); it != allHistograms.end(); it++ ) { if ( *it == tmpHisto ) { allHistograms.erase( it ); break; } } if( tmpHisto->getDestroy() ) { if( paraverMain::myParaverMain->GetCurrentHisto() == tmpHisto ) { paraverMain::myParaverMain->SetCurrentHisto( NULL ); paraverMain::myParaverMain->clearProperties(); } if( !allTracesTree ) tmpHistogram->Destroy(); destroy = true; } } // Update its name if( tmpName != tree->GetItemText( id ) ) tree->SetItemText( id, tmpName ); // Recursive update if( tree->ItemHasChildren( id ) ) { wxTreeItemIdValue cookie; wxTreeItemId currentChild = tree->GetFirstChild( id, cookie ); while( currentChild.IsOk() ) { updateTreeItem( tree, currentChild, allWindows, allHistograms, currentWindow, allTracesTree ); if( !destroy ) currentChild = tree->GetNextChild( id, cookie ); else currentChild = tree->GetFirstChild( id, cookie ); } } if( destroy ) tree->Delete( id ); return destroy; } void iconizeWindows( wxTreeCtrl *tree, wxTreeItemId& id, bool iconize ) { wxTreeItemIdValue cookie; wxTreeItemId currentChild = tree->GetFirstChild( id, cookie ); unsigned int numberChild = tree->GetChildrenCount( id, false ); unsigned int current = 0; while( current < numberChild ) { if ( currentChild.IsOk() ) { TreeBrowserItemData *itemData = (TreeBrowserItemData *)tree->GetItemData( currentChild ); if( gTimeline *tmpTimeline = itemData->getTimeline() ) { if( tmpTimeline->GetMyWindow()->getShowWindow() ) tmpTimeline->Show( iconize ); } else if( gHistogram *tmpHistogram = itemData->getHistogram() ) { if( tmpHistogram->GetHistogram()->getShowWindow() ) tmpHistogram->Show( iconize ); } if( tree->ItemHasChildren( currentChild ) ) iconizeWindows( tree, currentChild, iconize ); } currentChild = tree->GetNextChild( id, cookie ); ++current; } } <commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * wxparaver * * Paraver Trace Visualization and Analysis Tool * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ /* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\ | @file: $HeadURL$ | @last_commit: $Date$ | @version: $Revision$ \* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ #include "windows_tree.h" #include "loadedwindows.h" #include "gtimeline.h" #include "ghistogram.h" #include "paravermain.h" wxTreeCtrl * createTree( wxImageList *imageList ) { wxChoicebook *choiceWindowBrowser = paraverMain::myParaverMain->choiceWindowBrowser; wxTreeCtrl *newTree = new wxTreeCtrl( choiceWindowBrowser, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HIDE_ROOT|wxTR_DEFAULT_STYLE ); #ifndef WIN32 newTree->SetWindowStyle( wxTR_HAS_BUTTONS|wxTR_HIDE_ROOT|wxTR_SINGLE ); #endif newTree->SetImageList( imageList ); newTree->AddRoot( wxT( "Root" ), -1, -1, new TreeBrowserItemData( _( "Root" ), (gTimeline *)NULL ) ); return newTree; } wxTreeCtrl *getAllTracesTree() { wxChoicebook *choiceWindowBrowser = paraverMain::myParaverMain->choiceWindowBrowser; return (wxTreeCtrl *) choiceWindowBrowser->GetPage( 0 ); } wxTreeCtrl *getSelectedTraceTree( Trace *trace ) { wxChoicebook *choiceWindowBrowser = paraverMain::myParaverMain->choiceWindowBrowser; PRV_INT16 currentTrace = paraverMain::myParaverMain->getTracePosition( trace ); return (wxTreeCtrl *) choiceWindowBrowser->GetPage( currentTrace + 1 ); } void appendHistogram2Tree( gHistogram *ghistogram ) { // Refresh tree in current page and always in global page wxTreeCtrl *allTracesPage = getAllTracesTree(); wxTreeCtrl *currentPage = getSelectedTraceTree( ghistogram->GetHistogram()->getControlWindow()->getTrace() ); TreeBrowserItemData *currentData = new TreeBrowserItemData( wxString::FromAscii( ghistogram->GetHistogram()->getName().c_str() ), ghistogram ); wxTreeItemId tmpCurrentWindowId; tmpCurrentWindowId = allTracesPage->AppendItem( allTracesPage->GetRootItem(), wxString::FromAscii( ghistogram->GetHistogram()->getName().c_str() ), 0, -1, currentData ); tmpCurrentWindowId = currentPage->AppendItem( currentPage->GetRootItem(), wxString::FromAscii( ghistogram->GetHistogram()->getName().c_str() ), 0, -1, new TreeBrowserItemData( *currentData ) ); } wxTreeItemId getItemIdFromGTimeline( wxTreeItemId root, gTimeline *wanted, bool &found ) { wxTreeItemIdValue cookie; found = false; wxTreeItemId itemCurrent = getAllTracesTree()->GetFirstChild( root, cookie ); wxTreeItemId itemLast = getAllTracesTree()->GetLastChild( root ); while ( !found && itemCurrent.IsOk() && itemCurrent != itemLast ) { gTimeline *tmpTimeline = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemCurrent )))->getTimeline(); if ( tmpTimeline != NULL && tmpTimeline == wanted ) { root = itemCurrent; found = true; } else if ( tmpTimeline != NULL ) { root = getItemIdFromGTimeline( itemCurrent, wanted, found ); } if( !found ) itemCurrent = getAllTracesTree()->GetNextChild( root, cookie ); } if( !found && itemLast.IsOk() ) { if (((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline() == wanted ) { root = itemLast; found = true; } else { root = getItemIdFromGTimeline( itemLast, wanted, found ); } } return root; } // TODO: Separate recursion function to remove bool from parameters in main definition gTimeline *getGTimelineFromWindow( wxTreeItemId root, Window *wanted, bool &found ) { gTimeline *retgt = NULL; wxTreeItemIdValue cookie; found = false; wxTreeItemId itemCurrent = getAllTracesTree()->GetFirstChild( root, cookie ); wxTreeItemId itemLast = getAllTracesTree()->GetLastChild( root ); while ( !found && itemCurrent.IsOk() && itemCurrent != itemLast ) { gTimeline *tmpTimeline = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemCurrent )))->getTimeline(); if ( tmpTimeline != NULL && tmpTimeline->GetMyWindow() == wanted ) { retgt = tmpTimeline; found = true; } else if ( tmpTimeline != NULL ) { retgt = getGTimelineFromWindow( itemCurrent, wanted, found ); } if( !found ) itemCurrent = getAllTracesTree()->GetNextChild( root, cookie ); } if( !found && itemLast.IsOk() ) { if (((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline()->GetMyWindow() == wanted ) { retgt = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline(); found = true; } else { retgt = getGTimelineFromWindow( itemLast, wanted, found ); } } return retgt; } wxTreeItemId getItemIdFromWindow( wxTreeItemId root, Window *wanted, bool &found ) { wxTreeItemId retItemId; wxTreeItemIdValue cookie; found = false; wxTreeItemId itemCurrent = getAllTracesTree()->GetFirstChild( root, cookie ); wxTreeItemId itemLast = getAllTracesTree()->GetLastChild( root ); while ( !found && itemCurrent.IsOk() && itemCurrent != itemLast ) { gTimeline *tmpTimeline = ((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemCurrent )))->getTimeline(); if ( tmpTimeline != NULL && tmpTimeline->GetMyWindow() == wanted ) { retItemId = itemCurrent; found = true; } else if ( tmpTimeline != NULL ) { retItemId = getItemIdFromWindow( itemCurrent, wanted, found ); } if( !found ) itemCurrent = getAllTracesTree()->GetNextChild( root, cookie ); } if( !found && itemLast.IsOk() ) { if (((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( itemLast )))->getTimeline()->GetMyWindow() == wanted ) { retItemId = itemLast; found = true; } else { retItemId = getItemIdFromWindow( itemLast, wanted, found ); } } return retItemId; } // precond : current is a derived gTimeline void getParentGTimeline( gTimeline *current, vector< gTimeline * > & parents ) { // find item for given current gTimeline. bool found; wxTreeItemId item = getItemIdFromGTimeline( getAllTracesTree()->GetRootItem(), current, found ); // fill vector with parents wxTreeItemIdValue cookie; parents.push_back(((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( getAllTracesTree()->GetFirstChild( item, cookie ))))->getTimeline()); parents.push_back(((TreeBrowserItemData *)(getAllTracesTree()->GetItemData( getAllTracesTree()->GetNextChild( item, cookie ) )))->getTimeline()); } void BuildTree( paraverMain *parent, wxTreeCtrl *root1, wxTreeItemId idRoot1, wxTreeCtrl *root2, wxTreeItemId idRoot2, Window *window, string nameSuffix ) { wxTreeItemId currentWindowId1, currentWindowId2; TreeBrowserItemData *currentData; string composedName = window->getName() + " @ " + window->getTrace()->getTraceName(); wxPoint tmpPos( window->getPosX(), window->getPosY() ); gTimeline* tmpTimeline = new gTimeline( parent, wxID_ANY, wxString::FromAscii( composedName.c_str() ), tmpPos ); LoadedWindows::getInstance()->add( window ); tmpTimeline->SetMyWindow( window ); tmpTimeline->SetClientSize( wxSize( window->getWidth(), window->getHeight() ) ); currentData = new TreeBrowserItemData( wxString::FromAscii( window->getName().c_str() ), tmpTimeline ); int iconNumber = 1; // number of timeline icon if ( window->isDerivedWindow() ) { string derivedFunctionName = window->getLevelFunction( DERIVED ); // GUI should'nt know these tags -> add operation to kernel if ( derivedFunctionName == "add" ) iconNumber = 2; else if ( derivedFunctionName == "product" ) iconNumber = 3; else if ( derivedFunctionName == "substract" ) iconNumber = 4; else if ( derivedFunctionName == "divide" ) iconNumber = 5; else if ( derivedFunctionName == "maximum" ) iconNumber = 6; else if ( derivedFunctionName == "minimum" ) iconNumber = 7; else if ( derivedFunctionName == "different" ) iconNumber = 8; else if ( derivedFunctionName == "controlled: clear by" ) iconNumber = 9; else if ( derivedFunctionName == "controlled: maximum" ) iconNumber = 10; else if ( derivedFunctionName == "controlled: add" ) iconNumber = 11; } currentWindowId1 = root1->AppendItem( idRoot1, wxString::FromAscii( window->getName().c_str() ), iconNumber, -1, currentData ); currentWindowId2 = root2->AppendItem( idRoot2, wxString::FromAscii( window->getName().c_str() ), iconNumber, -1, new TreeBrowserItemData( *currentData ) ); if ( window->getParent( 0 ) != NULL ) { BuildTree( parent, root1, currentWindowId1, root2, currentWindowId2, window->getParent( 0 ) ); BuildTree( parent, root1, currentWindowId1, root2, currentWindowId2, window->getParent( 1 ) ); } parent->SetCurrentWindow( (wxWindow *)tmpTimeline ); } bool updateTreeItem( wxTreeCtrl *tree, wxTreeItemId& id, vector< Window * > &allWindows, vector< Histogram * > &allHistograms, wxWindow **currentWindow, bool allTracesTree ) { bool destroy = false; TreeBrowserItemData *itemData = (TreeBrowserItemData *)tree->GetItemData( id ); // No matter timeline or histogram, get its name and delete from given vector wxString tmpName; if( gTimeline *tmpTimeline = itemData->getTimeline() ) { Window *tmpWindow = tmpTimeline->GetMyWindow(); if( tmpWindow->isSync() ) tree->SetItemBold( id, true ); else tree->SetItemBold( id, false ); if( tmpTimeline->IsActive() && !tmpWindow->getDestroy() ) { *currentWindow = tmpTimeline; tree->SelectItem( id ); } tmpName = wxString::FromAscii( tmpWindow->getName().c_str() ); for ( vector<Window *>::iterator it = allWindows.begin(); it != allWindows.end(); it++ ) { if ( *it == tmpWindow ) { allWindows.erase( it ); break; } } if( tmpWindow->getDestroy() ) { if( paraverMain::myParaverMain->GetCurrentTimeline() == tmpWindow ) { paraverMain::myParaverMain->SetCurrentTimeline( NULL ); paraverMain::myParaverMain->clearProperties(); } if( !allTracesTree ) tmpTimeline->Destroy(); Window *parent1 = tmpWindow->getParent( 0 ); if( parent1 != NULL ) { parent1->setChild( NULL ); parent1->setDestroy( true ); } Window *parent2 = tmpWindow->getParent( 1 ); if( parent2 != NULL ) { parent2->setChild( NULL ); parent2->setDestroy( true ); } destroy = true; } } else if( gHistogram *tmpHistogram = itemData->getHistogram() ) { Histogram *tmpHisto = tmpHistogram->GetHistogram(); if( tmpHistogram->IsActive() && !tmpHisto->getDestroy() ) { *currentWindow = tmpHistogram; tree->SelectItem( id ); } tmpName = wxString::FromAscii( tmpHisto->getName().c_str() ); for ( vector<Histogram *>::iterator it = allHistograms.begin(); it != allHistograms.end(); it++ ) { if ( *it == tmpHisto ) { allHistograms.erase( it ); break; } } if( tmpHisto->getDestroy() ) { if( paraverMain::myParaverMain->GetCurrentHisto() == tmpHisto ) { paraverMain::myParaverMain->SetCurrentHisto( NULL ); paraverMain::myParaverMain->clearProperties(); } if( !allTracesTree ) tmpHistogram->Destroy(); destroy = true; } } // Update its name if( tmpName != tree->GetItemText( id ) ) tree->SetItemText( id, tmpName ); // Recursive update if( tree->ItemHasChildren( id ) ) { wxTreeItemIdValue cookie; wxTreeItemId currentChild = tree->GetFirstChild( id, cookie ); while( currentChild.IsOk() ) { updateTreeItem( tree, currentChild, allWindows, allHistograms, currentWindow, allTracesTree ); if( !destroy ) currentChild = tree->GetNextChild( id, cookie ); else currentChild = tree->GetFirstChild( id, cookie ); } } if( destroy ) tree->Delete( id ); return destroy; } void iconizeWindows( wxTreeCtrl *tree, wxTreeItemId& id, bool iconize ) { wxTreeItemIdValue cookie; wxTreeItemId currentChild = tree->GetFirstChild( id, cookie ); unsigned int numberChild = tree->GetChildrenCount( id, false ); unsigned int current = 0; while( current < numberChild ) { if ( currentChild.IsOk() ) { TreeBrowserItemData *itemData = (TreeBrowserItemData *)tree->GetItemData( currentChild ); if( gTimeline *tmpTimeline = itemData->getTimeline() ) { if( tmpTimeline->GetMyWindow()->getShowWindow() ) tmpTimeline->Show( iconize ); } else if( gHistogram *tmpHistogram = itemData->getHistogram() ) { if( tmpHistogram->GetHistogram()->getShowWindow() ) tmpHistogram->Show( iconize ); } if( tree->ItemHasChildren( currentChild ) ) iconizeWindows( tree, currentChild, iconize ); } currentChild = tree->GetNextChild( id, cookie ); ++current; } } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // Copyright 2006 Carnegie Mellon University. All rights reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file COPYING at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // // __END_LICENSE__ /// \file PixelTypeInfo.cc /// /// Functions that return information about types by ID. /// #include <vw/Image/PixelTypeInfo.h> vw::int32 vw::channel_size( vw::ChannelTypeEnum type ) { switch( type ) { case VW_CHANNEL_BOOL: return sizeof(bool); case VW_CHANNEL_CHAR: case VW_CHANNEL_INT8: case VW_CHANNEL_UINT8: case VW_CHANNEL_GENERIC_1_BYTE: return 1; case VW_CHANNEL_INT16: case VW_CHANNEL_UINT16: case VW_CHANNEL_GENERIC_2_BYTE: return 2; case VW_CHANNEL_INT32: case VW_CHANNEL_UINT32: case VW_CHANNEL_FLOAT32: case VW_CHANNEL_GENERIC_4_BYTE: return 4; case VW_CHANNEL_INT64: case VW_CHANNEL_UINT64: case VW_CHANNEL_FLOAT64: case VW_CHANNEL_GENERIC_8_BYTE: return 8; default: vw_throw( ArgumentErr() << "Unrecognized or unsupported channel type (" << type << ")." ); return 0; // never reached } } const char *vw::channel_type_name( vw::ChannelTypeEnum format ) { switch( format ) { case VW_CHANNEL_BOOL: return "BOOL"; case VW_CHANNEL_CHAR: return "CHAR"; case VW_CHANNEL_INT8: return "INT8"; case VW_CHANNEL_UINT8: return "UINT8"; case VW_CHANNEL_INT16: return "INT16"; case VW_CHANNEL_UINT16: return "UINT16"; case VW_CHANNEL_INT32: return "INT32"; case VW_CHANNEL_UINT32: return "UINT32"; case VW_CHANNEL_FLOAT32: return "FLOAT32"; case VW_CHANNEL_INT64: return "INT64"; case VW_CHANNEL_UINT64: return "UINT64"; case VW_CHANNEL_FLOAT64: return "FLOAT64"; default: return "UNKNOWN"; } } vw::int32 vw::num_channels( vw::PixelFormatEnum format ) { switch( format ) { case VW_PIXEL_SCALAR: case VW_PIXEL_GRAY: case VW_PIXEL_GENERIC_1_CHANNEL: return 1; case VW_PIXEL_GRAYA: case VW_PIXEL_SCALAR_MASKED: case VW_PIXEL_GRAY_MASKED: case VW_PIXEL_GENERIC_2_CHANNEL: return 2; case VW_PIXEL_RGB: case VW_PIXEL_HSV: case VW_PIXEL_XYZ: case VW_PIXEL_LUV: case VW_PIXEL_LAB: case VW_PIXEL_GRAYA_MASKED: case VW_PIXEL_GENERIC_3_CHANNEL: return 3; case VW_PIXEL_RGBA: case VW_PIXEL_RGB_MASKED: case VW_PIXEL_HSV_MASKED: case VW_PIXEL_XYZ_MASKED: case VW_PIXEL_LUV_MASKED: case VW_PIXEL_LAB_MASKED: case VW_PIXEL_GENERIC_4_CHANNEL: return 4; case VW_PIXEL_RGBA_MASKED: return 5; default: vw_throw( ArgumentErr() << "Unrecognized or unsupported pixel format (" << format << ")." ); return 0; // never reached } } const char *vw::pixel_format_name( vw::PixelFormatEnum format ) { switch( format ) { case VW_PIXEL_SCALAR: return "SCALAR"; case VW_PIXEL_GRAY: return "GRAY"; case VW_PIXEL_GRAYA: return "GRAYA"; case VW_PIXEL_RGB: return "RGB"; case VW_PIXEL_RGBA: return "RGBA"; case VW_PIXEL_HSV: return "HSV"; case VW_PIXEL_XYZ: return "XYZ"; case VW_PIXEL_LUV: return "LUV"; case VW_PIXEL_LAB: return "LAB"; case VW_PIXEL_SCALAR_MASKED: return "SCALAR_MASKED"; case VW_PIXEL_GRAY_MASKED: return "GRAY_MASKED"; case VW_PIXEL_GRAYA_MASKED: return "GRAYA_MASKED"; case VW_PIXEL_RGB_MASKED: return "RGB_MASKED"; case VW_PIXEL_RGBA_MASKED: return "RGBA_MASKED"; case VW_PIXEL_HSV_MASKED: return "HSV_MASKED"; case VW_PIXEL_XYZ_MASKED: return "XYZ_MASKED"; case VW_PIXEL_LUV_MASKED: return "LUV_MASKED"; case VW_PIXEL_LAB_MASKED: return "LAB_MASKED"; default: return "UNKNOWN"; } } <commit_msg>Added some missing enums to various case statements.<commit_after>// __BEGIN_LICENSE__ // // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // Copyright 2006 Carnegie Mellon University. All rights reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file COPYING at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // // __END_LICENSE__ /// \file PixelTypeInfo.cc /// /// Functions that return information about types by ID. /// #include <vw/Image/PixelTypeInfo.h> vw::int32 vw::channel_size( vw::ChannelTypeEnum type ) { switch( type ) { case VW_CHANNEL_BOOL: return sizeof(bool); case VW_CHANNEL_CHAR: case VW_CHANNEL_INT8: case VW_CHANNEL_UINT8: case VW_CHANNEL_GENERIC_1_BYTE: return 1; case VW_CHANNEL_INT16: case VW_CHANNEL_UINT16: case VW_CHANNEL_FLOAT16: case VW_CHANNEL_GENERIC_2_BYTE: return 2; case VW_CHANNEL_INT32: case VW_CHANNEL_UINT32: case VW_CHANNEL_FLOAT32: case VW_CHANNEL_GENERIC_4_BYTE: return 4; case VW_CHANNEL_INT64: case VW_CHANNEL_UINT64: case VW_CHANNEL_FLOAT64: case VW_CHANNEL_GENERIC_8_BYTE: return 8; default: vw_throw( ArgumentErr() << "Unrecognized or unsupported channel type (" << type << ")." ); return 0; // never reached } } const char *vw::channel_type_name( vw::ChannelTypeEnum format ) { switch( format ) { case VW_CHANNEL_BOOL: return "BOOL"; case VW_CHANNEL_CHAR: return "CHAR"; case VW_CHANNEL_INT8: return "INT8"; case VW_CHANNEL_UINT8: return "UINT8"; case VW_CHANNEL_INT16: return "INT16"; case VW_CHANNEL_UINT16: return "UINT16"; case VW_CHANNEL_INT32: return "INT32"; case VW_CHANNEL_UINT32: return "UINT32"; case VW_CHANNEL_FLOAT16: return "FLOAT16"; case VW_CHANNEL_FLOAT32: return "FLOAT32"; case VW_CHANNEL_INT64: return "INT64"; case VW_CHANNEL_UINT64: return "UINT64"; case VW_CHANNEL_FLOAT64: return "FLOAT64"; case VW_CHANNEL_GENERIC_1_BYTE: return "GENERIC_1_BYTE"; case VW_CHANNEL_GENERIC_2_BYTE: return "GENERIC_2_BYTE"; case VW_CHANNEL_GENERIC_4_BYTE: return "GENERIC_3_BYTE"; case VW_CHANNEL_GENERIC_8_BYTE: return "GENERIC_4_BYTE"; default: return "UNKNOWN"; } } vw::int32 vw::num_channels( vw::PixelFormatEnum format ) { switch( format ) { case VW_PIXEL_SCALAR: case VW_PIXEL_GRAY: case VW_PIXEL_GENERIC_1_CHANNEL: return 1; case VW_PIXEL_GRAYA: case VW_PIXEL_SCALAR_MASKED: case VW_PIXEL_GRAY_MASKED: case VW_PIXEL_GENERIC_2_CHANNEL: return 2; case VW_PIXEL_RGB: case VW_PIXEL_HSV: case VW_PIXEL_XYZ: case VW_PIXEL_LUV: case VW_PIXEL_LAB: case VW_PIXEL_GRAYA_MASKED: case VW_PIXEL_GENERIC_3_CHANNEL: return 3; case VW_PIXEL_RGBA: case VW_PIXEL_RGB_MASKED: case VW_PIXEL_HSV_MASKED: case VW_PIXEL_XYZ_MASKED: case VW_PIXEL_LUV_MASKED: case VW_PIXEL_LAB_MASKED: case VW_PIXEL_GENERIC_4_CHANNEL: return 4; case VW_PIXEL_RGBA_MASKED: return 5; default: vw_throw( ArgumentErr() << "Unrecognized or unsupported pixel format (" << format << ")." ); return 0; // never reached } } const char *vw::pixel_format_name( vw::PixelFormatEnum format ) { switch( format ) { case VW_PIXEL_SCALAR: return "SCALAR"; case VW_PIXEL_GRAY: return "GRAY"; case VW_PIXEL_GRAYA: return "GRAYA"; case VW_PIXEL_RGB: return "RGB"; case VW_PIXEL_RGBA: return "RGBA"; case VW_PIXEL_HSV: return "HSV"; case VW_PIXEL_XYZ: return "XYZ"; case VW_PIXEL_LUV: return "LUV"; case VW_PIXEL_LAB: return "LAB"; case VW_PIXEL_UNKNOWN_MASKED: return "UNKNOWN_MASKED"; case VW_PIXEL_SCALAR_MASKED: return "SCALAR_MASKED"; case VW_PIXEL_GRAY_MASKED: return "GRAY_MASKED"; case VW_PIXEL_GRAYA_MASKED: return "GRAYA_MASKED"; case VW_PIXEL_RGB_MASKED: return "RGB_MASKED"; case VW_PIXEL_RGBA_MASKED: return "RGBA_MASKED"; case VW_PIXEL_HSV_MASKED: return "HSV_MASKED"; case VW_PIXEL_XYZ_MASKED: return "XYZ_MASKED"; case VW_PIXEL_LUV_MASKED: return "LUV_MASKED"; case VW_PIXEL_LAB_MASKED: return "LAB_MASKED"; case VW_PIXEL_GENERIC_1_CHANNEL: return "VW_PIXEL_GENERIC_1_CHANNEL"; case VW_PIXEL_GENERIC_2_CHANNEL: return "VW_PIXEL_GENERIC_2_CHANNEL"; case VW_PIXEL_GENERIC_3_CHANNEL: return "VW_PIXEL_GENERIC_3_CHANNEL"; case VW_PIXEL_GENERIC_4_CHANNEL: return "VW_PIXEL_GENERIC_4_CHANNEL"; default: return "UNKNOWN"; } } <|endoftext|>